babylon.max.js 1.8 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314
  1. var __extends = (this && this.__extends) || function (d, b) {
  2. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  3. function __() { this.constructor = d; }
  4. __.prototype = b.prototype;
  5. d.prototype = new __();
  6. };
  7. var BABYLON;
  8. (function (BABYLON) {
  9. var Color3 = (function () {
  10. function Color3(r, g, b) {
  11. if (r === void 0) { r = 0; }
  12. if (g === void 0) { g = 0; }
  13. if (b === void 0) { b = 0; }
  14. this.r = r;
  15. this.g = g;
  16. this.b = b;
  17. }
  18. Color3.prototype.toString = function () {
  19. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  20. };
  21. // Operators
  22. Color3.prototype.toArray = function (array, index) {
  23. if (index === undefined) {
  24. index = 0;
  25. }
  26. array[index] = this.r;
  27. array[index + 1] = this.g;
  28. array[index + 2] = this.b;
  29. return this;
  30. };
  31. Color3.prototype.toColor4 = function (alpha) {
  32. if (alpha === void 0) { alpha = 1; }
  33. return new Color4(this.r, this.g, this.b, alpha);
  34. };
  35. Color3.prototype.asArray = function () {
  36. var result = [];
  37. this.toArray(result, 0);
  38. return result;
  39. };
  40. Color3.prototype.toLuminance = function () {
  41. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  42. };
  43. Color3.prototype.multiply = function (otherColor) {
  44. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  45. };
  46. Color3.prototype.multiplyToRef = function (otherColor, result) {
  47. result.r = this.r * otherColor.r;
  48. result.g = this.g * otherColor.g;
  49. result.b = this.b * otherColor.b;
  50. return this;
  51. };
  52. Color3.prototype.equals = function (otherColor) {
  53. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  54. };
  55. Color3.prototype.equalsFloats = function (r, g, b) {
  56. return this.r === r && this.g === g && this.b === b;
  57. };
  58. Color3.prototype.scale = function (scale) {
  59. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  60. };
  61. Color3.prototype.scaleToRef = function (scale, result) {
  62. result.r = this.r * scale;
  63. result.g = this.g * scale;
  64. result.b = this.b * scale;
  65. return this;
  66. };
  67. Color3.prototype.add = function (otherColor) {
  68. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  69. };
  70. Color3.prototype.addToRef = function (otherColor, result) {
  71. result.r = this.r + otherColor.r;
  72. result.g = this.g + otherColor.g;
  73. result.b = this.b + otherColor.b;
  74. return this;
  75. };
  76. Color3.prototype.subtract = function (otherColor) {
  77. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  78. };
  79. Color3.prototype.subtractToRef = function (otherColor, result) {
  80. result.r = this.r - otherColor.r;
  81. result.g = this.g - otherColor.g;
  82. result.b = this.b - otherColor.b;
  83. return this;
  84. };
  85. Color3.prototype.clone = function () {
  86. return new Color3(this.r, this.g, this.b);
  87. };
  88. Color3.prototype.copyFrom = function (source) {
  89. this.r = source.r;
  90. this.g = source.g;
  91. this.b = source.b;
  92. return this;
  93. };
  94. Color3.prototype.copyFromFloats = function (r, g, b) {
  95. this.r = r;
  96. this.g = g;
  97. this.b = b;
  98. return this;
  99. };
  100. Color3.prototype.toHexString = function () {
  101. var intR = (this.r * 255) | 0;
  102. var intG = (this.g * 255) | 0;
  103. var intB = (this.b * 255) | 0;
  104. return "#" + BABYLON.Tools.ToHex(intR) + BABYLON.Tools.ToHex(intG) + BABYLON.Tools.ToHex(intB);
  105. };
  106. // Statics
  107. Color3.FromHexString = function (hex) {
  108. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  109. BABYLON.Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  110. return new Color3(0, 0, 0);
  111. }
  112. var r = parseInt(hex.substring(1, 3), 16);
  113. var g = parseInt(hex.substring(3, 5), 16);
  114. var b = parseInt(hex.substring(5, 7), 16);
  115. return Color3.FromInts(r, g, b);
  116. };
  117. Color3.FromArray = function (array, offset) {
  118. if (offset === void 0) { offset = 0; }
  119. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  120. };
  121. Color3.FromInts = function (r, g, b) {
  122. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  123. };
  124. Color3.Lerp = function (start, end, amount) {
  125. var r = start.r + ((end.r - start.r) * amount);
  126. var g = start.g + ((end.g - start.g) * amount);
  127. var b = start.b + ((end.b - start.b) * amount);
  128. return new Color3(r, g, b);
  129. };
  130. Color3.Red = function () { return new Color3(1, 0, 0); };
  131. Color3.Green = function () { return new Color3(0, 1, 0); };
  132. Color3.Blue = function () { return new Color3(0, 0, 1); };
  133. Color3.Black = function () { return new Color3(0, 0, 0); };
  134. Color3.White = function () { return new Color3(1, 1, 1); };
  135. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  136. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  137. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  138. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  139. return Color3;
  140. })();
  141. BABYLON.Color3 = Color3;
  142. var Color4 = (function () {
  143. function Color4(r, g, b, a) {
  144. this.r = r;
  145. this.g = g;
  146. this.b = b;
  147. this.a = a;
  148. }
  149. // Operators
  150. Color4.prototype.addInPlace = function (right) {
  151. this.r += right.r;
  152. this.g += right.g;
  153. this.b += right.b;
  154. this.a += right.a;
  155. return this;
  156. };
  157. Color4.prototype.asArray = function () {
  158. var result = [];
  159. this.toArray(result, 0);
  160. return result;
  161. };
  162. Color4.prototype.toArray = function (array, index) {
  163. if (index === undefined) {
  164. index = 0;
  165. }
  166. array[index] = this.r;
  167. array[index + 1] = this.g;
  168. array[index + 2] = this.b;
  169. array[index + 3] = this.a;
  170. return this;
  171. };
  172. Color4.prototype.add = function (right) {
  173. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  174. };
  175. Color4.prototype.subtract = function (right) {
  176. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  177. };
  178. Color4.prototype.subtractToRef = function (right, result) {
  179. result.r = this.r - right.r;
  180. result.g = this.g - right.g;
  181. result.b = this.b - right.b;
  182. result.a = this.a - right.a;
  183. return this;
  184. };
  185. Color4.prototype.scale = function (scale) {
  186. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  187. };
  188. Color4.prototype.scaleToRef = function (scale, result) {
  189. result.r = this.r * scale;
  190. result.g = this.g * scale;
  191. result.b = this.b * scale;
  192. result.a = this.a * scale;
  193. return this;
  194. };
  195. Color4.prototype.toString = function () {
  196. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  197. };
  198. Color4.prototype.clone = function () {
  199. return new Color4(this.r, this.g, this.b, this.a);
  200. };
  201. Color4.prototype.copyFrom = function (source) {
  202. this.r = source.r;
  203. this.g = source.g;
  204. this.b = source.b;
  205. this.a = source.a;
  206. return this;
  207. };
  208. Color4.prototype.toHexString = function () {
  209. var intR = (this.r * 255) | 0;
  210. var intG = (this.g * 255) | 0;
  211. var intB = (this.b * 255) | 0;
  212. var intA = (this.a * 255) | 0;
  213. return "#" + BABYLON.Tools.ToHex(intR) + BABYLON.Tools.ToHex(intG) + BABYLON.Tools.ToHex(intB) + BABYLON.Tools.ToHex(intA);
  214. };
  215. // Statics
  216. Color4.FromHexString = function (hex) {
  217. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  218. BABYLON.Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  219. return new Color4(0, 0, 0, 0);
  220. }
  221. var r = parseInt(hex.substring(1, 3), 16);
  222. var g = parseInt(hex.substring(3, 5), 16);
  223. var b = parseInt(hex.substring(5, 7), 16);
  224. var a = parseInt(hex.substring(7, 9), 16);
  225. return Color4.FromInts(r, g, b, a);
  226. };
  227. Color4.Lerp = function (left, right, amount) {
  228. var result = new Color4(0, 0, 0, 0);
  229. Color4.LerpToRef(left, right, amount, result);
  230. return result;
  231. };
  232. Color4.LerpToRef = function (left, right, amount, result) {
  233. result.r = left.r + (right.r - left.r) * amount;
  234. result.g = left.g + (right.g - left.g) * amount;
  235. result.b = left.b + (right.b - left.b) * amount;
  236. result.a = left.a + (right.a - left.a) * amount;
  237. };
  238. Color4.FromArray = function (array, offset) {
  239. if (offset === void 0) { offset = 0; }
  240. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  241. };
  242. Color4.FromInts = function (r, g, b, a) {
  243. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  244. };
  245. return Color4;
  246. })();
  247. BABYLON.Color4 = Color4;
  248. var Vector2 = (function () {
  249. function Vector2(x, y) {
  250. this.x = x;
  251. this.y = y;
  252. }
  253. Vector2.prototype.toString = function () {
  254. return "{X: " + this.x + " Y:" + this.y + "}";
  255. };
  256. // Operators
  257. Vector2.prototype.toArray = function (array, index) {
  258. if (index === void 0) { index = 0; }
  259. array[index] = this.x;
  260. array[index + 1] = this.y;
  261. return this;
  262. };
  263. Vector2.prototype.asArray = function () {
  264. var result = [];
  265. this.toArray(result, 0);
  266. return result;
  267. };
  268. Vector2.prototype.copyFrom = function (source) {
  269. this.x = source.x;
  270. this.y = source.y;
  271. return this;
  272. };
  273. Vector2.prototype.copyFromFloats = function (x, y) {
  274. this.x = x;
  275. this.y = y;
  276. return this;
  277. };
  278. Vector2.prototype.add = function (otherVector) {
  279. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  280. };
  281. Vector2.prototype.addVector3 = function (otherVector) {
  282. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  283. };
  284. Vector2.prototype.subtract = function (otherVector) {
  285. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  286. };
  287. Vector2.prototype.subtractInPlace = function (otherVector) {
  288. this.x -= otherVector.x;
  289. this.y -= otherVector.y;
  290. return this;
  291. };
  292. Vector2.prototype.multiplyInPlace = function (otherVector) {
  293. this.x *= otherVector.x;
  294. this.y *= otherVector.y;
  295. return this;
  296. };
  297. Vector2.prototype.multiply = function (otherVector) {
  298. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  299. };
  300. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  301. result.x = this.x * otherVector.x;
  302. result.y = this.y * otherVector.y;
  303. return this;
  304. };
  305. Vector2.prototype.multiplyByFloats = function (x, y) {
  306. return new Vector2(this.x * x, this.y * y);
  307. };
  308. Vector2.prototype.divide = function (otherVector) {
  309. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  310. };
  311. Vector2.prototype.divideToRef = function (otherVector, result) {
  312. result.x = this.x / otherVector.x;
  313. result.y = this.y / otherVector.y;
  314. return this;
  315. };
  316. Vector2.prototype.negate = function () {
  317. return new Vector2(-this.x, -this.y);
  318. };
  319. Vector2.prototype.scaleInPlace = function (scale) {
  320. this.x *= scale;
  321. this.y *= scale;
  322. return this;
  323. };
  324. Vector2.prototype.scale = function (scale) {
  325. return new Vector2(this.x * scale, this.y * scale);
  326. };
  327. Vector2.prototype.equals = function (otherVector) {
  328. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  329. };
  330. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  331. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  332. return otherVector && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon);
  333. };
  334. // Properties
  335. Vector2.prototype.length = function () {
  336. return Math.sqrt(this.x * this.x + this.y * this.y);
  337. };
  338. Vector2.prototype.lengthSquared = function () {
  339. return (this.x * this.x + this.y * this.y);
  340. };
  341. // Methods
  342. Vector2.prototype.normalize = function () {
  343. var len = this.length();
  344. if (len === 0)
  345. return this;
  346. var num = 1.0 / len;
  347. this.x *= num;
  348. this.y *= num;
  349. return this;
  350. };
  351. Vector2.prototype.clone = function () {
  352. return new Vector2(this.x, this.y);
  353. };
  354. // Statics
  355. Vector2.Zero = function () {
  356. return new Vector2(0, 0);
  357. };
  358. Vector2.FromArray = function (array, offset) {
  359. if (offset === void 0) { offset = 0; }
  360. return new Vector2(array[offset], array[offset + 1]);
  361. };
  362. Vector2.FromArrayToRef = function (array, offset, result) {
  363. result.x = array[offset];
  364. result.y = array[offset + 1];
  365. };
  366. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  367. var squared = amount * amount;
  368. var cubed = amount * squared;
  369. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  370. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  371. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  372. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  373. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  374. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  375. return new Vector2(x, y);
  376. };
  377. Vector2.Clamp = function (value, min, max) {
  378. var x = value.x;
  379. x = (x > max.x) ? max.x : x;
  380. x = (x < min.x) ? min.x : x;
  381. var y = value.y;
  382. y = (y > max.y) ? max.y : y;
  383. y = (y < min.y) ? min.y : y;
  384. return new Vector2(x, y);
  385. };
  386. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  387. var squared = amount * amount;
  388. var cubed = amount * squared;
  389. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  390. var part2 = (-2.0 * cubed) + (3.0 * squared);
  391. var part3 = (cubed - (2.0 * squared)) + amount;
  392. var part4 = cubed - squared;
  393. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  394. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  395. return new Vector2(x, y);
  396. };
  397. Vector2.Lerp = function (start, end, amount) {
  398. var x = start.x + ((end.x - start.x) * amount);
  399. var y = start.y + ((end.y - start.y) * amount);
  400. return new Vector2(x, y);
  401. };
  402. Vector2.Dot = function (left, right) {
  403. return left.x * right.x + left.y * right.y;
  404. };
  405. Vector2.Normalize = function (vector) {
  406. var newVector = vector.clone();
  407. newVector.normalize();
  408. return newVector;
  409. };
  410. Vector2.Minimize = function (left, right) {
  411. var x = (left.x < right.x) ? left.x : right.x;
  412. var y = (left.y < right.y) ? left.y : right.y;
  413. return new Vector2(x, y);
  414. };
  415. Vector2.Maximize = function (left, right) {
  416. var x = (left.x > right.x) ? left.x : right.x;
  417. var y = (left.y > right.y) ? left.y : right.y;
  418. return new Vector2(x, y);
  419. };
  420. Vector2.Transform = function (vector, transformation) {
  421. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  422. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  423. return new Vector2(x, y);
  424. };
  425. Vector2.Distance = function (value1, value2) {
  426. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  427. };
  428. Vector2.DistanceSquared = function (value1, value2) {
  429. var x = value1.x - value2.x;
  430. var y = value1.y - value2.y;
  431. return (x * x) + (y * y);
  432. };
  433. return Vector2;
  434. })();
  435. BABYLON.Vector2 = Vector2;
  436. var Vector3 = (function () {
  437. function Vector3(x, y, z) {
  438. this.x = x;
  439. this.y = y;
  440. this.z = z;
  441. }
  442. Vector3.prototype.toString = function () {
  443. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  444. };
  445. // Operators
  446. Vector3.prototype.asArray = function () {
  447. var result = [];
  448. this.toArray(result, 0);
  449. return result;
  450. };
  451. Vector3.prototype.toArray = function (array, index) {
  452. if (index === void 0) { index = 0; }
  453. array[index] = this.x;
  454. array[index + 1] = this.y;
  455. array[index + 2] = this.z;
  456. return this;
  457. };
  458. Vector3.prototype.toQuaternion = function () {
  459. var result = new Quaternion(0, 0, 0, 1);
  460. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  461. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  462. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  463. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  464. var cosy = Math.cos(this.y * 0.5);
  465. var siny = Math.sin(this.y * 0.5);
  466. result.x = coszMinusx * siny;
  467. result.y = -sinzMinusx * siny;
  468. result.z = sinxPlusz * cosy;
  469. result.w = cosxPlusz * cosy;
  470. return result;
  471. };
  472. Vector3.prototype.addInPlace = function (otherVector) {
  473. this.x += otherVector.x;
  474. this.y += otherVector.y;
  475. this.z += otherVector.z;
  476. return this;
  477. };
  478. Vector3.prototype.add = function (otherVector) {
  479. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  480. };
  481. Vector3.prototype.addToRef = function (otherVector, result) {
  482. result.x = this.x + otherVector.x;
  483. result.y = this.y + otherVector.y;
  484. result.z = this.z + otherVector.z;
  485. return this;
  486. };
  487. Vector3.prototype.subtractInPlace = function (otherVector) {
  488. this.x -= otherVector.x;
  489. this.y -= otherVector.y;
  490. this.z -= otherVector.z;
  491. return this;
  492. };
  493. Vector3.prototype.subtract = function (otherVector) {
  494. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  495. };
  496. Vector3.prototype.subtractToRef = function (otherVector, result) {
  497. result.x = this.x - otherVector.x;
  498. result.y = this.y - otherVector.y;
  499. result.z = this.z - otherVector.z;
  500. return this;
  501. };
  502. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  503. return new Vector3(this.x - x, this.y - y, this.z - z);
  504. };
  505. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  506. result.x = this.x - x;
  507. result.y = this.y - y;
  508. result.z = this.z - z;
  509. return this;
  510. };
  511. Vector3.prototype.negate = function () {
  512. return new Vector3(-this.x, -this.y, -this.z);
  513. };
  514. Vector3.prototype.scaleInPlace = function (scale) {
  515. this.x *= scale;
  516. this.y *= scale;
  517. this.z *= scale;
  518. return this;
  519. };
  520. Vector3.prototype.scale = function (scale) {
  521. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  522. };
  523. Vector3.prototype.scaleToRef = function (scale, result) {
  524. result.x = this.x * scale;
  525. result.y = this.y * scale;
  526. result.z = this.z * scale;
  527. };
  528. Vector3.prototype.equals = function (otherVector) {
  529. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  530. };
  531. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  532. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  533. return otherVector && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Tools.WithinEpsilon(this.z, otherVector.z, epsilon);
  534. };
  535. Vector3.prototype.equalsToFloats = function (x, y, z) {
  536. return this.x === x && this.y === y && this.z === z;
  537. };
  538. Vector3.prototype.multiplyInPlace = function (otherVector) {
  539. this.x *= otherVector.x;
  540. this.y *= otherVector.y;
  541. this.z *= otherVector.z;
  542. return this;
  543. };
  544. Vector3.prototype.multiply = function (otherVector) {
  545. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  546. };
  547. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  548. result.x = this.x * otherVector.x;
  549. result.y = this.y * otherVector.y;
  550. result.z = this.z * otherVector.z;
  551. return this;
  552. };
  553. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  554. return new Vector3(this.x * x, this.y * y, this.z * z);
  555. };
  556. Vector3.prototype.divide = function (otherVector) {
  557. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  558. };
  559. Vector3.prototype.divideToRef = function (otherVector, result) {
  560. result.x = this.x / otherVector.x;
  561. result.y = this.y / otherVector.y;
  562. result.z = this.z / otherVector.z;
  563. return this;
  564. };
  565. Vector3.prototype.MinimizeInPlace = function (other) {
  566. if (other.x < this.x)
  567. this.x = other.x;
  568. if (other.y < this.y)
  569. this.y = other.y;
  570. if (other.z < this.z)
  571. this.z = other.z;
  572. return this;
  573. };
  574. Vector3.prototype.MaximizeInPlace = function (other) {
  575. if (other.x > this.x)
  576. this.x = other.x;
  577. if (other.y > this.y)
  578. this.y = other.y;
  579. if (other.z > this.z)
  580. this.z = other.z;
  581. return this;
  582. };
  583. // Properties
  584. Vector3.prototype.length = function () {
  585. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  586. };
  587. Vector3.prototype.lengthSquared = function () {
  588. return (this.x * this.x + this.y * this.y + this.z * this.z);
  589. };
  590. // Methods
  591. Vector3.prototype.normalize = function () {
  592. var len = this.length();
  593. if (len === 0 || len === 1.0)
  594. return this;
  595. var num = 1.0 / len;
  596. this.x *= num;
  597. this.y *= num;
  598. this.z *= num;
  599. return this;
  600. };
  601. Vector3.prototype.clone = function () {
  602. return new Vector3(this.x, this.y, this.z);
  603. };
  604. Vector3.prototype.copyFrom = function (source) {
  605. this.x = source.x;
  606. this.y = source.y;
  607. this.z = source.z;
  608. return this;
  609. };
  610. Vector3.prototype.copyFromFloats = function (x, y, z) {
  611. this.x = x;
  612. this.y = y;
  613. this.z = z;
  614. return this;
  615. };
  616. // Statics
  617. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  618. var d0 = Vector3.Dot(vector0, axis) - size;
  619. var d1 = Vector3.Dot(vector1, axis) - size;
  620. var s = d0 / (d0 - d1);
  621. return s;
  622. };
  623. Vector3.FromArray = function (array, offset) {
  624. if (!offset) {
  625. offset = 0;
  626. }
  627. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  628. };
  629. Vector3.FromFloatArray = function (array, offset) {
  630. if (!offset) {
  631. offset = 0;
  632. }
  633. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  634. };
  635. Vector3.FromArrayToRef = function (array, offset, result) {
  636. result.x = array[offset];
  637. result.y = array[offset + 1];
  638. result.z = array[offset + 2];
  639. };
  640. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  641. result.x = array[offset];
  642. result.y = array[offset + 1];
  643. result.z = array[offset + 2];
  644. };
  645. Vector3.FromFloatsToRef = function (x, y, z, result) {
  646. result.x = x;
  647. result.y = y;
  648. result.z = z;
  649. };
  650. Vector3.Zero = function () {
  651. return new Vector3(0, 0, 0);
  652. };
  653. Vector3.Up = function () {
  654. return new Vector3(0, 1.0, 0);
  655. };
  656. Vector3.TransformCoordinates = function (vector, transformation) {
  657. var result = Vector3.Zero();
  658. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  659. return result;
  660. };
  661. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  662. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  663. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  664. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  665. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  666. result.x = x / w;
  667. result.y = y / w;
  668. result.z = z / w;
  669. };
  670. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  671. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  672. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  673. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  674. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  675. result.x = rx / rw;
  676. result.y = ry / rw;
  677. result.z = rz / rw;
  678. };
  679. Vector3.TransformNormal = function (vector, transformation) {
  680. var result = Vector3.Zero();
  681. Vector3.TransformNormalToRef(vector, transformation, result);
  682. return result;
  683. };
  684. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  685. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  686. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  687. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  688. };
  689. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  690. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  691. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  692. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  693. };
  694. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  695. var squared = amount * amount;
  696. var cubed = amount * squared;
  697. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  698. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  699. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  700. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  701. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  702. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  703. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  704. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  705. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  706. return new Vector3(x, y, z);
  707. };
  708. Vector3.Clamp = function (value, min, max) {
  709. var x = value.x;
  710. x = (x > max.x) ? max.x : x;
  711. x = (x < min.x) ? min.x : x;
  712. var y = value.y;
  713. y = (y > max.y) ? max.y : y;
  714. y = (y < min.y) ? min.y : y;
  715. var z = value.z;
  716. z = (z > max.z) ? max.z : z;
  717. z = (z < min.z) ? min.z : z;
  718. return new Vector3(x, y, z);
  719. };
  720. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  721. var squared = amount * amount;
  722. var cubed = amount * squared;
  723. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  724. var part2 = (-2.0 * cubed) + (3.0 * squared);
  725. var part3 = (cubed - (2.0 * squared)) + amount;
  726. var part4 = cubed - squared;
  727. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  728. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  729. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  730. return new Vector3(x, y, z);
  731. };
  732. Vector3.Lerp = function (start, end, amount) {
  733. var x = start.x + ((end.x - start.x) * amount);
  734. var y = start.y + ((end.y - start.y) * amount);
  735. var z = start.z + ((end.z - start.z) * amount);
  736. return new Vector3(x, y, z);
  737. };
  738. Vector3.Dot = function (left, right) {
  739. return (left.x * right.x + left.y * right.y + left.z * right.z);
  740. };
  741. Vector3.Cross = function (left, right) {
  742. var result = Vector3.Zero();
  743. Vector3.CrossToRef(left, right, result);
  744. return result;
  745. };
  746. Vector3.CrossToRef = function (left, right, result) {
  747. result.x = left.y * right.z - left.z * right.y;
  748. result.y = left.z * right.x - left.x * right.z;
  749. result.z = left.x * right.y - left.y * right.x;
  750. };
  751. Vector3.Normalize = function (vector) {
  752. var result = Vector3.Zero();
  753. Vector3.NormalizeToRef(vector, result);
  754. return result;
  755. };
  756. Vector3.NormalizeToRef = function (vector, result) {
  757. result.copyFrom(vector);
  758. result.normalize();
  759. };
  760. Vector3.Project = function (vector, world, transform, viewport) {
  761. var cw = viewport.width;
  762. var ch = viewport.height;
  763. var cx = viewport.x;
  764. var cy = viewport.y;
  765. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 1, 0, cx + cw / 2.0, ch / 2.0 + cy, 0, 1);
  766. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  767. return Vector3.TransformCoordinates(vector, finalMatrix);
  768. };
  769. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  770. var matrix = world.multiply(transform);
  771. matrix.invert();
  772. source.x = source.x / viewportWidth * 2 - 1;
  773. source.y = -(source.y / viewportHeight * 2 - 1);
  774. var vector = Vector3.TransformCoordinates(source, matrix);
  775. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  776. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  777. vector = vector.scale(1.0 / num);
  778. }
  779. return vector;
  780. };
  781. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  782. var matrix = world.multiply(view).multiply(projection);
  783. matrix.invert();
  784. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), source.z);
  785. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  786. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  787. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  788. vector = vector.scale(1.0 / num);
  789. }
  790. return vector;
  791. };
  792. Vector3.Minimize = function (left, right) {
  793. var min = left.clone();
  794. min.MinimizeInPlace(right);
  795. return min;
  796. };
  797. Vector3.Maximize = function (left, right) {
  798. var max = left.clone();
  799. max.MaximizeInPlace(right);
  800. return max;
  801. };
  802. Vector3.Distance = function (value1, value2) {
  803. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  804. };
  805. Vector3.DistanceSquared = function (value1, value2) {
  806. var x = value1.x - value2.x;
  807. var y = value1.y - value2.y;
  808. var z = value1.z - value2.z;
  809. return (x * x) + (y * y) + (z * z);
  810. };
  811. Vector3.Center = function (value1, value2) {
  812. var center = value1.add(value2);
  813. center.scaleInPlace(0.5);
  814. return center;
  815. };
  816. /**
  817. * Given three orthogonal left-handed oriented Vector3 axis in space (target system),
  818. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  819. * to something in order to rotate it from its local system to the given target system.
  820. */
  821. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  822. var rotation = Vector3.Zero();
  823. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  824. return rotation;
  825. };
  826. /**
  827. * The same than RotationFromAxis but updates the passed ref Vector3 parameter.
  828. */
  829. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  830. var u = Vector3.Normalize(axis1);
  831. var w = Vector3.Normalize(axis3);
  832. // world axis
  833. var X = Axis.X;
  834. var Y = Axis.Y;
  835. // equation unknowns and vars
  836. var yaw = 0.0;
  837. var pitch = 0.0;
  838. var roll = 0.0;
  839. var x = 0.0;
  840. var y = 0.0;
  841. var z = 0.0;
  842. var t = 0.0;
  843. var sign = -1.0;
  844. var nbRevert = 0;
  845. var cross;
  846. var dot = 0.0;
  847. // step 1 : rotation around w
  848. // Rv3(u) = u1, and u1 belongs to plane xOz
  849. // Rv3(w) = w1 = w invariant
  850. var u1;
  851. var v1;
  852. if (BABYLON.Tools.WithinEpsilon(w.z, 0, BABYLON.Engine.Epsilon)) {
  853. z = 1.0;
  854. }
  855. else if (BABYLON.Tools.WithinEpsilon(w.x, 0, BABYLON.Engine.Epsilon)) {
  856. x = 1.0;
  857. }
  858. else {
  859. t = w.z / w.x;
  860. x = -t * Math.sqrt(1 / (1 + t * t));
  861. z = Math.sqrt(1 / (1 + t * t));
  862. }
  863. u1 = new Vector3(x, y, z);
  864. u1.normalize();
  865. v1 = Vector3.Cross(w, u1); // v1 image of v through rotation around w
  866. v1.normalize();
  867. cross = Vector3.Cross(u, u1); // returns same direction as w (=local z) if positive angle : cross(source, image)
  868. cross.normalize();
  869. if (Vector3.Dot(w, cross) < 0) {
  870. sign = 1.0;
  871. }
  872. dot = Vector3.Dot(u, u1);
  873. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  874. roll = Math.acos(dot) * sign;
  875. if (Vector3.Dot(u1, X) < 0) {
  876. roll = Math.PI + roll;
  877. u1 = u1.scaleInPlace(-1);
  878. v1 = v1.scaleInPlace(-1);
  879. nbRevert++;
  880. }
  881. // step 2 : rotate around u1
  882. // Ru1(w1) = Ru1(w) = w2, and w2 belongs to plane xOz
  883. // u1 is yet in xOz and invariant by Ru1, so after this step u1 and w2 will be in xOz
  884. var w2;
  885. var v2;
  886. x = 0.0;
  887. y = 0.0;
  888. z = 0.0;
  889. sign = -1;
  890. if (BABYLON.Tools.WithinEpsilon(w.z, 0, BABYLON.Engine.Epsilon)) {
  891. x = 1.0;
  892. }
  893. else {
  894. t = u1.z / u1.x;
  895. x = -t * Math.sqrt(1 / (1 + t * t));
  896. z = Math.sqrt(1 / (1 + t * t));
  897. }
  898. w2 = new Vector3(x, y, z);
  899. w2.normalize();
  900. v2 = Vector3.Cross(w2, u1); // v2 image of v1 through rotation around u1
  901. v2.normalize();
  902. cross = Vector3.Cross(w, w2); // returns same direction as u1 (=local x) if positive angle : cross(source, image)
  903. cross.normalize();
  904. if (Vector3.Dot(u1, cross) < 0) {
  905. sign = 1.0;
  906. }
  907. dot = Vector3.Dot(w, w2);
  908. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  909. pitch = Math.acos(dot) * sign;
  910. if (Vector3.Dot(v2, Y) < 0) {
  911. pitch = Math.PI + pitch;
  912. v2 = v2.scaleInPlace(-1);
  913. w2 = w2.scaleInPlace(-1);
  914. nbRevert++;
  915. }
  916. // step 3 : rotate around v2
  917. // Rv2(u1) = X, same as Rv2(w2) = Z, with X=(1,0,0) and Z=(0,0,1)
  918. sign = -1;
  919. cross = Vector3.Cross(X, u1); // returns same direction as Y if positive angle : cross(source, image)
  920. cross.normalize();
  921. if (Vector3.Dot(cross, Y) < 0) {
  922. sign = 1.0;
  923. }
  924. dot = Vector3.Dot(u1, X);
  925. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  926. yaw = -Math.acos(dot) * sign; // negative : plane zOx oriented clockwise
  927. if (dot < 0 && nbRevert < 2) {
  928. yaw = Math.PI + yaw;
  929. }
  930. ref.x = pitch;
  931. ref.y = yaw;
  932. ref.z = roll;
  933. };
  934. return Vector3;
  935. })();
  936. BABYLON.Vector3 = Vector3;
  937. //Vector4 class created for EulerAngle class conversion to Quaternion
  938. var Vector4 = (function () {
  939. function Vector4(x, y, z, w) {
  940. this.x = x;
  941. this.y = y;
  942. this.z = z;
  943. this.w = w;
  944. }
  945. Vector4.prototype.toString = function () {
  946. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  947. };
  948. // Operators
  949. Vector4.prototype.asArray = function () {
  950. var result = [];
  951. this.toArray(result, 0);
  952. return result;
  953. };
  954. Vector4.prototype.toArray = function (array, index) {
  955. if (index === undefined) {
  956. index = 0;
  957. }
  958. array[index] = this.x;
  959. array[index + 1] = this.y;
  960. array[index + 2] = this.z;
  961. array[index + 3] = this.w;
  962. return this;
  963. };
  964. Vector4.prototype.addInPlace = function (otherVector) {
  965. this.x += otherVector.x;
  966. this.y += otherVector.y;
  967. this.z += otherVector.z;
  968. this.w += otherVector.w;
  969. return this;
  970. };
  971. Vector4.prototype.add = function (otherVector) {
  972. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  973. };
  974. Vector4.prototype.addToRef = function (otherVector, result) {
  975. result.x = this.x + otherVector.x;
  976. result.y = this.y + otherVector.y;
  977. result.z = this.z + otherVector.z;
  978. result.w = this.w + otherVector.w;
  979. return this;
  980. };
  981. Vector4.prototype.subtractInPlace = function (otherVector) {
  982. this.x -= otherVector.x;
  983. this.y -= otherVector.y;
  984. this.z -= otherVector.z;
  985. this.w -= otherVector.w;
  986. return this;
  987. };
  988. Vector4.prototype.subtract = function (otherVector) {
  989. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  990. };
  991. Vector4.prototype.subtractToRef = function (otherVector, result) {
  992. result.x = this.x - otherVector.x;
  993. result.y = this.y - otherVector.y;
  994. result.z = this.z - otherVector.z;
  995. result.w = this.w - otherVector.w;
  996. return this;
  997. };
  998. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  999. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1000. };
  1001. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1002. result.x = this.x - x;
  1003. result.y = this.y - y;
  1004. result.z = this.z - z;
  1005. result.w = this.w - w;
  1006. return this;
  1007. };
  1008. Vector4.prototype.negate = function () {
  1009. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1010. };
  1011. Vector4.prototype.scaleInPlace = function (scale) {
  1012. this.x *= scale;
  1013. this.y *= scale;
  1014. this.z *= scale;
  1015. this.w *= scale;
  1016. return this;
  1017. };
  1018. Vector4.prototype.scale = function (scale) {
  1019. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1020. };
  1021. Vector4.prototype.scaleToRef = function (scale, result) {
  1022. result.x = this.x * scale;
  1023. result.y = this.y * scale;
  1024. result.z = this.z * scale;
  1025. result.w = this.w * scale;
  1026. };
  1027. Vector4.prototype.equals = function (otherVector) {
  1028. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1029. };
  1030. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1031. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  1032. return otherVector
  1033. && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1034. && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1035. && BABYLON.Tools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1036. && BABYLON.Tools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1037. };
  1038. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1039. return this.x === x && this.y === y && this.z === z && this.w === w;
  1040. };
  1041. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1042. this.x *= otherVector.x;
  1043. this.y *= otherVector.y;
  1044. this.z *= otherVector.z;
  1045. this.w *= otherVector.w;
  1046. return this;
  1047. };
  1048. Vector4.prototype.multiply = function (otherVector) {
  1049. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1050. };
  1051. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1052. result.x = this.x * otherVector.x;
  1053. result.y = this.y * otherVector.y;
  1054. result.z = this.z * otherVector.z;
  1055. result.w = this.w * otherVector.w;
  1056. return this;
  1057. };
  1058. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1059. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1060. };
  1061. Vector4.prototype.divide = function (otherVector) {
  1062. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1063. };
  1064. Vector4.prototype.divideToRef = function (otherVector, result) {
  1065. result.x = this.x / otherVector.x;
  1066. result.y = this.y / otherVector.y;
  1067. result.z = this.z / otherVector.z;
  1068. result.w = this.w / otherVector.w;
  1069. return this;
  1070. };
  1071. Vector4.prototype.MinimizeInPlace = function (other) {
  1072. if (other.x < this.x)
  1073. this.x = other.x;
  1074. if (other.y < this.y)
  1075. this.y = other.y;
  1076. if (other.z < this.z)
  1077. this.z = other.z;
  1078. if (other.w < this.w)
  1079. this.w = other.w;
  1080. return this;
  1081. };
  1082. Vector4.prototype.MaximizeInPlace = function (other) {
  1083. if (other.x > this.x)
  1084. this.x = other.x;
  1085. if (other.y > this.y)
  1086. this.y = other.y;
  1087. if (other.z > this.z)
  1088. this.z = other.z;
  1089. if (other.w > this.w)
  1090. this.w = other.w;
  1091. return this;
  1092. };
  1093. // Properties
  1094. Vector4.prototype.length = function () {
  1095. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1096. };
  1097. Vector4.prototype.lengthSquared = function () {
  1098. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1099. };
  1100. // Methods
  1101. Vector4.prototype.normalize = function () {
  1102. var len = this.length();
  1103. if (len === 0)
  1104. return this;
  1105. var num = 1.0 / len;
  1106. this.x *= num;
  1107. this.y *= num;
  1108. this.z *= num;
  1109. this.w *= num;
  1110. return this;
  1111. };
  1112. Vector4.prototype.clone = function () {
  1113. return new Vector4(this.x, this.y, this.z, this.w);
  1114. };
  1115. Vector4.prototype.copyFrom = function (source) {
  1116. this.x = source.x;
  1117. this.y = source.y;
  1118. this.z = source.z;
  1119. this.w = source.w;
  1120. return this;
  1121. };
  1122. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1123. this.x = x;
  1124. this.y = y;
  1125. this.z = z;
  1126. this.w = w;
  1127. return this;
  1128. };
  1129. // Statics
  1130. Vector4.FromArray = function (array, offset) {
  1131. if (!offset) {
  1132. offset = 0;
  1133. }
  1134. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1135. };
  1136. Vector4.FromArrayToRef = function (array, offset, result) {
  1137. result.x = array[offset];
  1138. result.y = array[offset + 1];
  1139. result.z = array[offset + 2];
  1140. result.w = array[offset + 3];
  1141. };
  1142. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1143. result.x = array[offset];
  1144. result.y = array[offset + 1];
  1145. result.z = array[offset + 2];
  1146. result.w = array[offset + 3];
  1147. };
  1148. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1149. result.x = x;
  1150. result.y = y;
  1151. result.z = z;
  1152. result.w = w;
  1153. };
  1154. Vector4.Zero = function () {
  1155. return new Vector4(0, 0, 0, 0);
  1156. };
  1157. Vector4.Normalize = function (vector) {
  1158. var result = Vector4.Zero();
  1159. Vector4.NormalizeToRef(vector, result);
  1160. return result;
  1161. };
  1162. Vector4.NormalizeToRef = function (vector, result) {
  1163. result.copyFrom(vector);
  1164. result.normalize();
  1165. };
  1166. Vector4.Minimize = function (left, right) {
  1167. var min = left.clone();
  1168. min.MinimizeInPlace(right);
  1169. return min;
  1170. };
  1171. Vector4.Maximize = function (left, right) {
  1172. var max = left.clone();
  1173. max.MaximizeInPlace(right);
  1174. return max;
  1175. };
  1176. Vector4.Distance = function (value1, value2) {
  1177. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1178. };
  1179. Vector4.DistanceSquared = function (value1, value2) {
  1180. var x = value1.x - value2.x;
  1181. var y = value1.y - value2.y;
  1182. var z = value1.z - value2.z;
  1183. var w = value1.w - value2.w;
  1184. return (x * x) + (y * y) + (z * z) + (w * w);
  1185. };
  1186. Vector4.Center = function (value1, value2) {
  1187. var center = value1.add(value2);
  1188. center.scaleInPlace(0.5);
  1189. return center;
  1190. };
  1191. return Vector4;
  1192. })();
  1193. BABYLON.Vector4 = Vector4;
  1194. var Quaternion = (function () {
  1195. function Quaternion(x, y, z, w) {
  1196. if (x === void 0) { x = 0; }
  1197. if (y === void 0) { y = 0; }
  1198. if (z === void 0) { z = 0; }
  1199. if (w === void 0) { w = 1; }
  1200. this.x = x;
  1201. this.y = y;
  1202. this.z = z;
  1203. this.w = w;
  1204. }
  1205. Quaternion.prototype.toString = function () {
  1206. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1207. };
  1208. Quaternion.prototype.asArray = function () {
  1209. return [this.x, this.y, this.z, this.w];
  1210. };
  1211. Quaternion.prototype.equals = function (otherQuaternion) {
  1212. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1213. };
  1214. Quaternion.prototype.clone = function () {
  1215. return new Quaternion(this.x, this.y, this.z, this.w);
  1216. };
  1217. Quaternion.prototype.copyFrom = function (other) {
  1218. this.x = other.x;
  1219. this.y = other.y;
  1220. this.z = other.z;
  1221. this.w = other.w;
  1222. return this;
  1223. };
  1224. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1225. this.x = x;
  1226. this.y = y;
  1227. this.z = z;
  1228. this.w = w;
  1229. return this;
  1230. };
  1231. Quaternion.prototype.add = function (other) {
  1232. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1233. };
  1234. Quaternion.prototype.subtract = function (other) {
  1235. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1236. };
  1237. Quaternion.prototype.scale = function (value) {
  1238. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1239. };
  1240. Quaternion.prototype.multiply = function (q1) {
  1241. var result = new Quaternion(0, 0, 0, 1.0);
  1242. this.multiplyToRef(q1, result);
  1243. return result;
  1244. };
  1245. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1246. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1247. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1248. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1249. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1250. result.copyFromFloats(x, y, z, w);
  1251. return this;
  1252. };
  1253. Quaternion.prototype.multiplyInPlace = function (q1) {
  1254. this.multiplyToRef(q1, this);
  1255. return this;
  1256. };
  1257. Quaternion.prototype.length = function () {
  1258. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1259. };
  1260. Quaternion.prototype.normalize = function () {
  1261. var length = 1.0 / this.length();
  1262. this.x *= length;
  1263. this.y *= length;
  1264. this.z *= length;
  1265. this.w *= length;
  1266. return this;
  1267. };
  1268. Quaternion.prototype.toEulerAngles = function () {
  1269. var result = Vector3.Zero();
  1270. this.toEulerAnglesToRef(result);
  1271. return result;
  1272. };
  1273. Quaternion.prototype.toEulerAnglesToRef = function (result) {
  1274. //result is an EulerAngles in the in the z-x-z convention
  1275. var qx = this.x;
  1276. var qy = this.y;
  1277. var qz = this.z;
  1278. var qw = this.w;
  1279. var qxy = qx * qy;
  1280. var qxz = qx * qz;
  1281. var qwy = qw * qy;
  1282. var qwz = qw * qz;
  1283. var qwx = qw * qx;
  1284. var qyz = qy * qz;
  1285. var sqx = qx * qx;
  1286. var sqy = qy * qy;
  1287. var determinant = sqx + sqy;
  1288. if (determinant !== 0.000 && determinant !== 1.000) {
  1289. result.x = Math.atan2(qxz + qwy, qwx - qyz);
  1290. result.y = Math.acos(1 - 2 * determinant);
  1291. result.z = Math.atan2(qxz - qwy, qwx + qyz);
  1292. }
  1293. else {
  1294. if (determinant === 0.0) {
  1295. result.x = 0.0;
  1296. result.y = 0.0;
  1297. result.z = Math.atan2(qxy - qwz, 0.5 - sqy - qz * qz); //actually, degeneracy gives us choice with x+z=Math.atan2(qxy-qwz,0.5-sqy-qz*qz)
  1298. }
  1299. else {
  1300. result.x = Math.atan2(qxy - qwz, 0.5 - sqy - qz * qz); //actually, degeneracy gives us choice with x-z=Math.atan2(qxy-qwz,0.5-sqy-qz*qz)
  1301. result.y = Math.PI;
  1302. result.z = 0.0;
  1303. }
  1304. }
  1305. return this;
  1306. };
  1307. Quaternion.prototype.toRotationMatrix = function (result) {
  1308. var xx = this.x * this.x;
  1309. var yy = this.y * this.y;
  1310. var zz = this.z * this.z;
  1311. var xy = this.x * this.y;
  1312. var zw = this.z * this.w;
  1313. var zx = this.z * this.x;
  1314. var yw = this.y * this.w;
  1315. var yz = this.y * this.z;
  1316. var xw = this.x * this.w;
  1317. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1318. result.m[1] = 2.0 * (xy + zw);
  1319. result.m[2] = 2.0 * (zx - yw);
  1320. result.m[3] = 0;
  1321. result.m[4] = 2.0 * (xy - zw);
  1322. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1323. result.m[6] = 2.0 * (yz + xw);
  1324. result.m[7] = 0;
  1325. result.m[8] = 2.0 * (zx + yw);
  1326. result.m[9] = 2.0 * (yz - xw);
  1327. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1328. result.m[11] = 0;
  1329. result.m[12] = 0;
  1330. result.m[13] = 0;
  1331. result.m[14] = 0;
  1332. result.m[15] = 1.0;
  1333. return this;
  1334. };
  1335. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1336. Quaternion.FromRotationMatrixToRef(matrix, this);
  1337. return this;
  1338. };
  1339. // Statics
  1340. Quaternion.FromRotationMatrix = function (matrix) {
  1341. var result = new Quaternion();
  1342. Quaternion.FromRotationMatrixToRef(matrix, result);
  1343. return result;
  1344. };
  1345. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1346. var data = matrix.m;
  1347. var m11 = data[0], m12 = data[4], m13 = data[8];
  1348. var m21 = data[1], m22 = data[5], m23 = data[9];
  1349. var m31 = data[2], m32 = data[6], m33 = data[10];
  1350. var trace = m11 + m22 + m33;
  1351. var s;
  1352. if (trace > 0) {
  1353. s = 0.5 / Math.sqrt(trace + 1.0);
  1354. result.w = 0.25 / s;
  1355. result.x = (m32 - m23) * s;
  1356. result.y = (m13 - m31) * s;
  1357. result.z = (m21 - m12) * s;
  1358. }
  1359. else if (m11 > m22 && m11 > m33) {
  1360. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1361. result.w = (m32 - m23) / s;
  1362. result.x = 0.25 * s;
  1363. result.y = (m12 + m21) / s;
  1364. result.z = (m13 + m31) / s;
  1365. }
  1366. else if (m22 > m33) {
  1367. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1368. result.w = (m13 - m31) / s;
  1369. result.x = (m12 + m21) / s;
  1370. result.y = 0.25 * s;
  1371. result.z = (m23 + m32) / s;
  1372. }
  1373. else {
  1374. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1375. result.w = (m21 - m12) / s;
  1376. result.x = (m13 + m31) / s;
  1377. result.y = (m23 + m32) / s;
  1378. result.z = 0.25 * s;
  1379. }
  1380. };
  1381. Quaternion.Inverse = function (q) {
  1382. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1383. };
  1384. Quaternion.Identity = function () {
  1385. return new Quaternion(0, 0, 0, 1);
  1386. };
  1387. Quaternion.RotationAxis = function (axis, angle) {
  1388. var result = new Quaternion();
  1389. var sin = Math.sin(angle / 2);
  1390. axis.normalize();
  1391. result.w = Math.cos(angle / 2);
  1392. result.x = axis.x * sin;
  1393. result.y = axis.y * sin;
  1394. result.z = axis.z * sin;
  1395. return result;
  1396. };
  1397. Quaternion.FromArray = function (array, offset) {
  1398. if (!offset) {
  1399. offset = 0;
  1400. }
  1401. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1402. };
  1403. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1404. var result = new Quaternion();
  1405. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1406. return result;
  1407. };
  1408. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1409. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1410. var halfRoll = roll * 0.5;
  1411. var halfPitch = pitch * 0.5;
  1412. var halfYaw = yaw * 0.5;
  1413. var sinRoll = Math.sin(halfRoll);
  1414. var cosRoll = Math.cos(halfRoll);
  1415. var sinPitch = Math.sin(halfPitch);
  1416. var cosPitch = Math.cos(halfPitch);
  1417. var sinYaw = Math.sin(halfYaw);
  1418. var cosYaw = Math.cos(halfYaw);
  1419. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1420. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1421. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1422. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1423. };
  1424. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1425. var result = new Quaternion();
  1426. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1427. return result;
  1428. };
  1429. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1430. // Produces a quaternion from Euler angles in the z-x-z orientation
  1431. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1432. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1433. var halfBeta = beta * 0.5;
  1434. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1435. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1436. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1437. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1438. };
  1439. Quaternion.Slerp = function (left, right, amount) {
  1440. var num2;
  1441. var num3;
  1442. var num = amount;
  1443. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1444. var flag = false;
  1445. if (num4 < 0) {
  1446. flag = true;
  1447. num4 = -num4;
  1448. }
  1449. if (num4 > 0.999999) {
  1450. num3 = 1 - num;
  1451. num2 = flag ? -num : num;
  1452. }
  1453. else {
  1454. var num5 = Math.acos(num4);
  1455. var num6 = (1.0 / Math.sin(num5));
  1456. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1457. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1458. }
  1459. return new Quaternion((num3 * left.x) + (num2 * right.x), (num3 * left.y) + (num2 * right.y), (num3 * left.z) + (num2 * right.z), (num3 * left.w) + (num2 * right.w));
  1460. };
  1461. return Quaternion;
  1462. })();
  1463. BABYLON.Quaternion = Quaternion;
  1464. var Matrix = (function () {
  1465. function Matrix() {
  1466. this.m = new Float32Array(16);
  1467. }
  1468. // Properties
  1469. Matrix.prototype.isIdentity = function () {
  1470. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1471. return false;
  1472. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  1473. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  1474. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  1475. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1476. return false;
  1477. return true;
  1478. };
  1479. Matrix.prototype.determinant = function () {
  1480. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1481. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1482. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1483. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1484. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1485. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1486. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  1487. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  1488. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1489. };
  1490. // Methods
  1491. Matrix.prototype.toArray = function () {
  1492. return this.m;
  1493. };
  1494. Matrix.prototype.asArray = function () {
  1495. return this.toArray();
  1496. };
  1497. Matrix.prototype.invert = function () {
  1498. this.invertToRef(this);
  1499. return this;
  1500. };
  1501. Matrix.prototype.reset = function () {
  1502. for (var index = 0; index < 16; index++) {
  1503. this.m[index] = 0;
  1504. }
  1505. return this;
  1506. };
  1507. Matrix.prototype.add = function (other) {
  1508. var result = new Matrix();
  1509. this.addToRef(other, result);
  1510. return result;
  1511. };
  1512. Matrix.prototype.addToRef = function (other, result) {
  1513. for (var index = 0; index < 16; index++) {
  1514. result.m[index] = this.m[index] + other.m[index];
  1515. }
  1516. return this;
  1517. };
  1518. Matrix.prototype.addToSelf = function (other) {
  1519. for (var index = 0; index < 16; index++) {
  1520. this.m[index] += other.m[index];
  1521. }
  1522. return this;
  1523. };
  1524. Matrix.prototype.invertToRef = function (other) {
  1525. var l1 = this.m[0];
  1526. var l2 = this.m[1];
  1527. var l3 = this.m[2];
  1528. var l4 = this.m[3];
  1529. var l5 = this.m[4];
  1530. var l6 = this.m[5];
  1531. var l7 = this.m[6];
  1532. var l8 = this.m[7];
  1533. var l9 = this.m[8];
  1534. var l10 = this.m[9];
  1535. var l11 = this.m[10];
  1536. var l12 = this.m[11];
  1537. var l13 = this.m[12];
  1538. var l14 = this.m[13];
  1539. var l15 = this.m[14];
  1540. var l16 = this.m[15];
  1541. var l17 = (l11 * l16) - (l12 * l15);
  1542. var l18 = (l10 * l16) - (l12 * l14);
  1543. var l19 = (l10 * l15) - (l11 * l14);
  1544. var l20 = (l9 * l16) - (l12 * l13);
  1545. var l21 = (l9 * l15) - (l11 * l13);
  1546. var l22 = (l9 * l14) - (l10 * l13);
  1547. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1548. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1549. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1550. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1551. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1552. var l28 = (l7 * l16) - (l8 * l15);
  1553. var l29 = (l6 * l16) - (l8 * l14);
  1554. var l30 = (l6 * l15) - (l7 * l14);
  1555. var l31 = (l5 * l16) - (l8 * l13);
  1556. var l32 = (l5 * l15) - (l7 * l13);
  1557. var l33 = (l5 * l14) - (l6 * l13);
  1558. var l34 = (l7 * l12) - (l8 * l11);
  1559. var l35 = (l6 * l12) - (l8 * l10);
  1560. var l36 = (l6 * l11) - (l7 * l10);
  1561. var l37 = (l5 * l12) - (l8 * l9);
  1562. var l38 = (l5 * l11) - (l7 * l9);
  1563. var l39 = (l5 * l10) - (l6 * l9);
  1564. other.m[0] = l23 * l27;
  1565. other.m[4] = l24 * l27;
  1566. other.m[8] = l25 * l27;
  1567. other.m[12] = l26 * l27;
  1568. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1569. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1570. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1571. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1572. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1573. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1574. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1575. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1576. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1577. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1578. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1579. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1580. return this;
  1581. };
  1582. Matrix.prototype.setTranslation = function (vector3) {
  1583. this.m[12] = vector3.x;
  1584. this.m[13] = vector3.y;
  1585. this.m[14] = vector3.z;
  1586. return this;
  1587. };
  1588. Matrix.prototype.multiply = function (other) {
  1589. var result = new Matrix();
  1590. this.multiplyToRef(other, result);
  1591. return result;
  1592. };
  1593. Matrix.prototype.copyFrom = function (other) {
  1594. for (var index = 0; index < 16; index++) {
  1595. this.m[index] = other.m[index];
  1596. }
  1597. return this;
  1598. };
  1599. Matrix.prototype.copyToArray = function (array, offset) {
  1600. if (offset === void 0) { offset = 0; }
  1601. for (var index = 0; index < 16; index++) {
  1602. array[offset + index] = this.m[index];
  1603. }
  1604. return this;
  1605. };
  1606. Matrix.prototype.multiplyToRef = function (other, result) {
  1607. this.multiplyToArray(other, result.m, 0);
  1608. return this;
  1609. };
  1610. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1611. var tm0 = this.m[0];
  1612. var tm1 = this.m[1];
  1613. var tm2 = this.m[2];
  1614. var tm3 = this.m[3];
  1615. var tm4 = this.m[4];
  1616. var tm5 = this.m[5];
  1617. var tm6 = this.m[6];
  1618. var tm7 = this.m[7];
  1619. var tm8 = this.m[8];
  1620. var tm9 = this.m[9];
  1621. var tm10 = this.m[10];
  1622. var tm11 = this.m[11];
  1623. var tm12 = this.m[12];
  1624. var tm13 = this.m[13];
  1625. var tm14 = this.m[14];
  1626. var tm15 = this.m[15];
  1627. var om0 = other.m[0];
  1628. var om1 = other.m[1];
  1629. var om2 = other.m[2];
  1630. var om3 = other.m[3];
  1631. var om4 = other.m[4];
  1632. var om5 = other.m[5];
  1633. var om6 = other.m[6];
  1634. var om7 = other.m[7];
  1635. var om8 = other.m[8];
  1636. var om9 = other.m[9];
  1637. var om10 = other.m[10];
  1638. var om11 = other.m[11];
  1639. var om12 = other.m[12];
  1640. var om13 = other.m[13];
  1641. var om14 = other.m[14];
  1642. var om15 = other.m[15];
  1643. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1644. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1645. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1646. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1647. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1648. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1649. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1650. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1651. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1652. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1653. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1654. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1655. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1656. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1657. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1658. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1659. return this;
  1660. };
  1661. Matrix.prototype.equals = function (value) {
  1662. return value &&
  1663. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  1664. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  1665. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  1666. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1667. };
  1668. Matrix.prototype.clone = function () {
  1669. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  1670. };
  1671. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1672. translation.x = this.m[12];
  1673. translation.y = this.m[13];
  1674. translation.z = this.m[14];
  1675. var xs = BABYLON.Tools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1676. var ys = BABYLON.Tools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1677. var zs = BABYLON.Tools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1678. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1679. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1680. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1681. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1682. rotation.x = 0;
  1683. rotation.y = 0;
  1684. rotation.z = 0;
  1685. rotation.w = 1;
  1686. return false;
  1687. }
  1688. var rotationMatrix = Matrix.FromValues(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1);
  1689. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1690. return true;
  1691. };
  1692. // Statics
  1693. Matrix.FromArray = function (array, offset) {
  1694. var result = new Matrix();
  1695. if (!offset) {
  1696. offset = 0;
  1697. }
  1698. Matrix.FromArrayToRef(array, offset, result);
  1699. return result;
  1700. };
  1701. Matrix.FromArrayToRef = function (array, offset, result) {
  1702. for (var index = 0; index < 16; index++) {
  1703. result.m[index] = array[index + offset];
  1704. }
  1705. };
  1706. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  1707. for (var index = 0; index < 16; index++) {
  1708. result.m[index] = array[index + offset] * scale;
  1709. }
  1710. };
  1711. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1712. result.m[0] = initialM11;
  1713. result.m[1] = initialM12;
  1714. result.m[2] = initialM13;
  1715. result.m[3] = initialM14;
  1716. result.m[4] = initialM21;
  1717. result.m[5] = initialM22;
  1718. result.m[6] = initialM23;
  1719. result.m[7] = initialM24;
  1720. result.m[8] = initialM31;
  1721. result.m[9] = initialM32;
  1722. result.m[10] = initialM33;
  1723. result.m[11] = initialM34;
  1724. result.m[12] = initialM41;
  1725. result.m[13] = initialM42;
  1726. result.m[14] = initialM43;
  1727. result.m[15] = initialM44;
  1728. };
  1729. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1730. var result = new Matrix();
  1731. result.m[0] = initialM11;
  1732. result.m[1] = initialM12;
  1733. result.m[2] = initialM13;
  1734. result.m[3] = initialM14;
  1735. result.m[4] = initialM21;
  1736. result.m[5] = initialM22;
  1737. result.m[6] = initialM23;
  1738. result.m[7] = initialM24;
  1739. result.m[8] = initialM31;
  1740. result.m[9] = initialM32;
  1741. result.m[10] = initialM33;
  1742. result.m[11] = initialM34;
  1743. result.m[12] = initialM41;
  1744. result.m[13] = initialM42;
  1745. result.m[14] = initialM43;
  1746. result.m[15] = initialM44;
  1747. return result;
  1748. };
  1749. Matrix.Compose = function (scale, rotation, translation) {
  1750. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1751. var rotationMatrix = Matrix.Identity();
  1752. rotation.toRotationMatrix(rotationMatrix);
  1753. result = result.multiply(rotationMatrix);
  1754. result.setTranslation(translation);
  1755. return result;
  1756. };
  1757. Matrix.Identity = function () {
  1758. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1759. };
  1760. Matrix.IdentityToRef = function (result) {
  1761. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1762. };
  1763. Matrix.Zero = function () {
  1764. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1765. };
  1766. Matrix.RotationX = function (angle) {
  1767. var result = new Matrix();
  1768. Matrix.RotationXToRef(angle, result);
  1769. return result;
  1770. };
  1771. Matrix.Invert = function (source) {
  1772. var result = new Matrix();
  1773. source.invertToRef(result);
  1774. return result;
  1775. };
  1776. Matrix.RotationXToRef = function (angle, result) {
  1777. var s = Math.sin(angle);
  1778. var c = Math.cos(angle);
  1779. result.m[0] = 1.0;
  1780. result.m[15] = 1.0;
  1781. result.m[5] = c;
  1782. result.m[10] = c;
  1783. result.m[9] = -s;
  1784. result.m[6] = s;
  1785. result.m[1] = 0;
  1786. result.m[2] = 0;
  1787. result.m[3] = 0;
  1788. result.m[4] = 0;
  1789. result.m[7] = 0;
  1790. result.m[8] = 0;
  1791. result.m[11] = 0;
  1792. result.m[12] = 0;
  1793. result.m[13] = 0;
  1794. result.m[14] = 0;
  1795. };
  1796. Matrix.RotationY = function (angle) {
  1797. var result = new Matrix();
  1798. Matrix.RotationYToRef(angle, result);
  1799. return result;
  1800. };
  1801. Matrix.RotationYToRef = function (angle, result) {
  1802. var s = Math.sin(angle);
  1803. var c = Math.cos(angle);
  1804. result.m[5] = 1.0;
  1805. result.m[15] = 1.0;
  1806. result.m[0] = c;
  1807. result.m[2] = -s;
  1808. result.m[8] = s;
  1809. result.m[10] = c;
  1810. result.m[1] = 0;
  1811. result.m[3] = 0;
  1812. result.m[4] = 0;
  1813. result.m[6] = 0;
  1814. result.m[7] = 0;
  1815. result.m[9] = 0;
  1816. result.m[11] = 0;
  1817. result.m[12] = 0;
  1818. result.m[13] = 0;
  1819. result.m[14] = 0;
  1820. };
  1821. Matrix.RotationZ = function (angle) {
  1822. var result = new Matrix();
  1823. Matrix.RotationZToRef(angle, result);
  1824. return result;
  1825. };
  1826. Matrix.RotationZToRef = function (angle, result) {
  1827. var s = Math.sin(angle);
  1828. var c = Math.cos(angle);
  1829. result.m[10] = 1.0;
  1830. result.m[15] = 1.0;
  1831. result.m[0] = c;
  1832. result.m[1] = s;
  1833. result.m[4] = -s;
  1834. result.m[5] = c;
  1835. result.m[2] = 0;
  1836. result.m[3] = 0;
  1837. result.m[6] = 0;
  1838. result.m[7] = 0;
  1839. result.m[8] = 0;
  1840. result.m[9] = 0;
  1841. result.m[11] = 0;
  1842. result.m[12] = 0;
  1843. result.m[13] = 0;
  1844. result.m[14] = 0;
  1845. };
  1846. Matrix.RotationAxis = function (axis, angle) {
  1847. var result = Matrix.Zero();
  1848. Matrix.RotationAxisToRef(axis, angle, result);
  1849. return result;
  1850. };
  1851. Matrix.RotationAxisToRef = function (axis, angle, result) {
  1852. var s = Math.sin(-angle);
  1853. var c = Math.cos(-angle);
  1854. var c1 = 1 - c;
  1855. axis.normalize();
  1856. result.m[0] = (axis.x * axis.x) * c1 + c;
  1857. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1858. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1859. result.m[3] = 0.0;
  1860. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1861. result.m[5] = (axis.y * axis.y) * c1 + c;
  1862. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1863. result.m[7] = 0.0;
  1864. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1865. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1866. result.m[10] = (axis.z * axis.z) * c1 + c;
  1867. result.m[11] = 0.0;
  1868. result.m[15] = 1.0;
  1869. };
  1870. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1871. var result = new Matrix();
  1872. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1873. return result;
  1874. };
  1875. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1876. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1877. this._tempQuaternion.toRotationMatrix(result);
  1878. };
  1879. Matrix.Scaling = function (x, y, z) {
  1880. var result = Matrix.Zero();
  1881. Matrix.ScalingToRef(x, y, z, result);
  1882. return result;
  1883. };
  1884. Matrix.ScalingToRef = function (x, y, z, result) {
  1885. result.m[0] = x;
  1886. result.m[1] = 0;
  1887. result.m[2] = 0;
  1888. result.m[3] = 0;
  1889. result.m[4] = 0;
  1890. result.m[5] = y;
  1891. result.m[6] = 0;
  1892. result.m[7] = 0;
  1893. result.m[8] = 0;
  1894. result.m[9] = 0;
  1895. result.m[10] = z;
  1896. result.m[11] = 0;
  1897. result.m[12] = 0;
  1898. result.m[13] = 0;
  1899. result.m[14] = 0;
  1900. result.m[15] = 1.0;
  1901. };
  1902. Matrix.Translation = function (x, y, z) {
  1903. var result = Matrix.Identity();
  1904. Matrix.TranslationToRef(x, y, z, result);
  1905. return result;
  1906. };
  1907. Matrix.TranslationToRef = function (x, y, z, result) {
  1908. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1909. };
  1910. Matrix.LookAtLH = function (eye, target, up) {
  1911. var result = Matrix.Zero();
  1912. Matrix.LookAtLHToRef(eye, target, up, result);
  1913. return result;
  1914. };
  1915. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1916. // Z axis
  1917. target.subtractToRef(eye, this._zAxis);
  1918. this._zAxis.normalize();
  1919. // X axis
  1920. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1921. if (this._xAxis.lengthSquared() === 0) {
  1922. this._xAxis.x = 1.0;
  1923. }
  1924. else {
  1925. this._xAxis.normalize();
  1926. }
  1927. // Y axis
  1928. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1929. this._yAxis.normalize();
  1930. // Eye angles
  1931. var ex = -Vector3.Dot(this._xAxis, eye);
  1932. var ey = -Vector3.Dot(this._yAxis, eye);
  1933. var ez = -Vector3.Dot(this._zAxis, eye);
  1934. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  1935. };
  1936. Matrix.OrthoLH = function (width, height, znear, zfar) {
  1937. var matrix = Matrix.Zero();
  1938. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  1939. return matrix;
  1940. };
  1941. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  1942. var hw = 2.0 / width;
  1943. var hh = 2.0 / height;
  1944. var id = 1.0 / (zfar - znear);
  1945. var nid = znear / (znear - zfar);
  1946. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  1947. };
  1948. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  1949. var matrix = Matrix.Zero();
  1950. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  1951. return matrix;
  1952. };
  1953. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  1954. result.m[0] = 2.0 / (right - left);
  1955. result.m[1] = result.m[2] = result.m[3] = 0;
  1956. result.m[5] = 2.0 / (top - bottom);
  1957. result.m[4] = result.m[6] = result.m[7] = 0;
  1958. result.m[10] = -1.0 / (znear - zfar);
  1959. result.m[8] = result.m[9] = result.m[11] = 0;
  1960. result.m[12] = (left + right) / (left - right);
  1961. result.m[13] = (top + bottom) / (bottom - top);
  1962. result.m[14] = znear / (znear - zfar);
  1963. result.m[15] = 1.0;
  1964. };
  1965. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  1966. var matrix = Matrix.Zero();
  1967. matrix.m[0] = (2.0 * znear) / width;
  1968. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  1969. matrix.m[5] = (2.0 * znear) / height;
  1970. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  1971. matrix.m[10] = -zfar / (znear - zfar);
  1972. matrix.m[8] = matrix.m[9] = 0.0;
  1973. matrix.m[11] = 1.0;
  1974. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  1975. matrix.m[14] = (znear * zfar) / (znear - zfar);
  1976. return matrix;
  1977. };
  1978. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  1979. var matrix = Matrix.Zero();
  1980. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  1981. return matrix;
  1982. };
  1983. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, fovMode) {
  1984. if (fovMode === void 0) { fovMode = BABYLON.Camera.FOVMODE_VERTICAL_FIXED; }
  1985. var tan = 1.0 / (Math.tan(fov * 0.5));
  1986. var v_fixed = (fovMode === BABYLON.Camera.FOVMODE_VERTICAL_FIXED);
  1987. if (v_fixed) {
  1988. result.m[0] = tan / aspect;
  1989. }
  1990. else {
  1991. result.m[0] = tan;
  1992. }
  1993. result.m[1] = result.m[2] = result.m[3] = 0.0;
  1994. if (v_fixed) {
  1995. result.m[5] = tan;
  1996. }
  1997. else {
  1998. result.m[5] = tan * aspect;
  1999. }
  2000. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2001. result.m[8] = result.m[9] = 0.0;
  2002. result.m[10] = -zfar / (znear - zfar);
  2003. result.m[11] = 1.0;
  2004. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2005. result.m[14] = (znear * zfar) / (znear - zfar);
  2006. };
  2007. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2008. var cw = viewport.width;
  2009. var ch = viewport.height;
  2010. var cx = viewport.x;
  2011. var cy = viewport.y;
  2012. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, zmax - zmin, 0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  2013. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2014. };
  2015. Matrix.GetAsMatrix2x2 = function (matrix) {
  2016. return new Float32Array([
  2017. matrix.m[0], matrix.m[1],
  2018. matrix.m[4], matrix.m[5]
  2019. ]);
  2020. };
  2021. Matrix.GetAsMatrix3x3 = function (matrix) {
  2022. return new Float32Array([
  2023. matrix.m[0], matrix.m[1], matrix.m[2],
  2024. matrix.m[4], matrix.m[5], matrix.m[6],
  2025. matrix.m[8], matrix.m[9], matrix.m[10]
  2026. ]);
  2027. };
  2028. Matrix.Transpose = function (matrix) {
  2029. var result = new Matrix();
  2030. result.m[0] = matrix.m[0];
  2031. result.m[1] = matrix.m[4];
  2032. result.m[2] = matrix.m[8];
  2033. result.m[3] = matrix.m[12];
  2034. result.m[4] = matrix.m[1];
  2035. result.m[5] = matrix.m[5];
  2036. result.m[6] = matrix.m[9];
  2037. result.m[7] = matrix.m[13];
  2038. result.m[8] = matrix.m[2];
  2039. result.m[9] = matrix.m[6];
  2040. result.m[10] = matrix.m[10];
  2041. result.m[11] = matrix.m[14];
  2042. result.m[12] = matrix.m[3];
  2043. result.m[13] = matrix.m[7];
  2044. result.m[14] = matrix.m[11];
  2045. result.m[15] = matrix.m[15];
  2046. return result;
  2047. };
  2048. Matrix.Reflection = function (plane) {
  2049. var matrix = new Matrix();
  2050. Matrix.ReflectionToRef(plane, matrix);
  2051. return matrix;
  2052. };
  2053. Matrix.ReflectionToRef = function (plane, result) {
  2054. plane.normalize();
  2055. var x = plane.normal.x;
  2056. var y = plane.normal.y;
  2057. var z = plane.normal.z;
  2058. var temp = -2 * x;
  2059. var temp2 = -2 * y;
  2060. var temp3 = -2 * z;
  2061. result.m[0] = (temp * x) + 1;
  2062. result.m[1] = temp2 * x;
  2063. result.m[2] = temp3 * x;
  2064. result.m[3] = 0.0;
  2065. result.m[4] = temp * y;
  2066. result.m[5] = (temp2 * y) + 1;
  2067. result.m[6] = temp3 * y;
  2068. result.m[7] = 0.0;
  2069. result.m[8] = temp * z;
  2070. result.m[9] = temp2 * z;
  2071. result.m[10] = (temp3 * z) + 1;
  2072. result.m[11] = 0.0;
  2073. result.m[12] = temp * plane.d;
  2074. result.m[13] = temp2 * plane.d;
  2075. result.m[14] = temp3 * plane.d;
  2076. result.m[15] = 1.0;
  2077. };
  2078. Matrix._tempQuaternion = new Quaternion();
  2079. Matrix._xAxis = Vector3.Zero();
  2080. Matrix._yAxis = Vector3.Zero();
  2081. Matrix._zAxis = Vector3.Zero();
  2082. return Matrix;
  2083. })();
  2084. BABYLON.Matrix = Matrix;
  2085. var Plane = (function () {
  2086. function Plane(a, b, c, d) {
  2087. this.normal = new Vector3(a, b, c);
  2088. this.d = d;
  2089. }
  2090. Plane.prototype.asArray = function () {
  2091. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2092. };
  2093. // Methods
  2094. Plane.prototype.clone = function () {
  2095. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2096. };
  2097. Plane.prototype.normalize = function () {
  2098. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2099. var magnitude = 0;
  2100. if (norm !== 0) {
  2101. magnitude = 1.0 / norm;
  2102. }
  2103. this.normal.x *= magnitude;
  2104. this.normal.y *= magnitude;
  2105. this.normal.z *= magnitude;
  2106. this.d *= magnitude;
  2107. return this;
  2108. };
  2109. Plane.prototype.transform = function (transformation) {
  2110. var transposedMatrix = Matrix.Transpose(transformation);
  2111. var x = this.normal.x;
  2112. var y = this.normal.y;
  2113. var z = this.normal.z;
  2114. var d = this.d;
  2115. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2116. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2117. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2118. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2119. return new Plane(normalX, normalY, normalZ, finalD);
  2120. };
  2121. Plane.prototype.dotCoordinate = function (point) {
  2122. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2123. };
  2124. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2125. var x1 = point2.x - point1.x;
  2126. var y1 = point2.y - point1.y;
  2127. var z1 = point2.z - point1.z;
  2128. var x2 = point3.x - point1.x;
  2129. var y2 = point3.y - point1.y;
  2130. var z2 = point3.z - point1.z;
  2131. var yz = (y1 * z2) - (z1 * y2);
  2132. var xz = (z1 * x2) - (x1 * z2);
  2133. var xy = (x1 * y2) - (y1 * x2);
  2134. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2135. var invPyth;
  2136. if (pyth !== 0) {
  2137. invPyth = 1.0 / pyth;
  2138. }
  2139. else {
  2140. invPyth = 0;
  2141. }
  2142. this.normal.x = yz * invPyth;
  2143. this.normal.y = xz * invPyth;
  2144. this.normal.z = xy * invPyth;
  2145. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2146. return this;
  2147. };
  2148. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2149. var dot = Vector3.Dot(this.normal, direction);
  2150. return (dot <= epsilon);
  2151. };
  2152. Plane.prototype.signedDistanceTo = function (point) {
  2153. return Vector3.Dot(point, this.normal) + this.d;
  2154. };
  2155. // Statics
  2156. Plane.FromArray = function (array) {
  2157. return new Plane(array[0], array[1], array[2], array[3]);
  2158. };
  2159. Plane.FromPoints = function (point1, point2, point3) {
  2160. var result = new Plane(0, 0, 0, 0);
  2161. result.copyFromPoints(point1, point2, point3);
  2162. return result;
  2163. };
  2164. Plane.FromPositionAndNormal = function (origin, normal) {
  2165. var result = new Plane(0, 0, 0, 0);
  2166. normal.normalize();
  2167. result.normal = normal;
  2168. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2169. return result;
  2170. };
  2171. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2172. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2173. return Vector3.Dot(point, normal) + d;
  2174. };
  2175. return Plane;
  2176. })();
  2177. BABYLON.Plane = Plane;
  2178. var Viewport = (function () {
  2179. function Viewport(x, y, width, height) {
  2180. this.x = x;
  2181. this.y = y;
  2182. this.width = width;
  2183. this.height = height;
  2184. }
  2185. Viewport.prototype.toGlobal = function (engine) {
  2186. var width = engine.getRenderWidth();
  2187. var height = engine.getRenderHeight();
  2188. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  2189. };
  2190. return Viewport;
  2191. })();
  2192. BABYLON.Viewport = Viewport;
  2193. var Frustum = (function () {
  2194. function Frustum() {
  2195. }
  2196. Frustum.GetPlanes = function (transform) {
  2197. var frustumPlanes = [];
  2198. for (var index = 0; index < 6; index++) {
  2199. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2200. }
  2201. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2202. return frustumPlanes;
  2203. };
  2204. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2205. // Near
  2206. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2207. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2208. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  2209. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2210. frustumPlanes[0].normalize();
  2211. // Far
  2212. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2213. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2214. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2215. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2216. frustumPlanes[1].normalize();
  2217. // Left
  2218. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2219. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2220. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2221. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2222. frustumPlanes[2].normalize();
  2223. // Right
  2224. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2225. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2226. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2227. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2228. frustumPlanes[3].normalize();
  2229. // Top
  2230. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2231. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2232. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2233. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2234. frustumPlanes[4].normalize();
  2235. // Bottom
  2236. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2237. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2238. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2239. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2240. frustumPlanes[5].normalize();
  2241. };
  2242. return Frustum;
  2243. })();
  2244. BABYLON.Frustum = Frustum;
  2245. var Ray = (function () {
  2246. function Ray(origin, direction, length) {
  2247. if (length === void 0) { length = Number.MAX_VALUE; }
  2248. this.origin = origin;
  2249. this.direction = direction;
  2250. this.length = length;
  2251. }
  2252. // Methods
  2253. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  2254. var d = 0.0;
  2255. var maxValue = Number.MAX_VALUE;
  2256. var inv;
  2257. var min;
  2258. var max;
  2259. var temp;
  2260. if (Math.abs(this.direction.x) < 0.0000001) {
  2261. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  2262. return false;
  2263. }
  2264. }
  2265. else {
  2266. inv = 1.0 / this.direction.x;
  2267. min = (minimum.x - this.origin.x) * inv;
  2268. max = (maximum.x - this.origin.x) * inv;
  2269. if (max === -Infinity) {
  2270. max = Infinity;
  2271. }
  2272. if (min > max) {
  2273. temp = min;
  2274. min = max;
  2275. max = temp;
  2276. }
  2277. d = Math.max(min, d);
  2278. maxValue = Math.min(max, maxValue);
  2279. if (d > maxValue) {
  2280. return false;
  2281. }
  2282. }
  2283. if (Math.abs(this.direction.y) < 0.0000001) {
  2284. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  2285. return false;
  2286. }
  2287. }
  2288. else {
  2289. inv = 1.0 / this.direction.y;
  2290. min = (minimum.y - this.origin.y) * inv;
  2291. max = (maximum.y - this.origin.y) * inv;
  2292. if (max === -Infinity) {
  2293. max = Infinity;
  2294. }
  2295. if (min > max) {
  2296. temp = min;
  2297. min = max;
  2298. max = temp;
  2299. }
  2300. d = Math.max(min, d);
  2301. maxValue = Math.min(max, maxValue);
  2302. if (d > maxValue) {
  2303. return false;
  2304. }
  2305. }
  2306. if (Math.abs(this.direction.z) < 0.0000001) {
  2307. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  2308. return false;
  2309. }
  2310. }
  2311. else {
  2312. inv = 1.0 / this.direction.z;
  2313. min = (minimum.z - this.origin.z) * inv;
  2314. max = (maximum.z - this.origin.z) * inv;
  2315. if (max === -Infinity) {
  2316. max = Infinity;
  2317. }
  2318. if (min > max) {
  2319. temp = min;
  2320. min = max;
  2321. max = temp;
  2322. }
  2323. d = Math.max(min, d);
  2324. maxValue = Math.min(max, maxValue);
  2325. if (d > maxValue) {
  2326. return false;
  2327. }
  2328. }
  2329. return true;
  2330. };
  2331. Ray.prototype.intersectsBox = function (box) {
  2332. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  2333. };
  2334. Ray.prototype.intersectsSphere = function (sphere) {
  2335. var x = sphere.center.x - this.origin.x;
  2336. var y = sphere.center.y - this.origin.y;
  2337. var z = sphere.center.z - this.origin.z;
  2338. var pyth = (x * x) + (y * y) + (z * z);
  2339. var rr = sphere.radius * sphere.radius;
  2340. if (pyth <= rr) {
  2341. return true;
  2342. }
  2343. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  2344. if (dot < 0.0) {
  2345. return false;
  2346. }
  2347. var temp = pyth - (dot * dot);
  2348. return temp <= rr;
  2349. };
  2350. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  2351. if (!this._edge1) {
  2352. this._edge1 = Vector3.Zero();
  2353. this._edge2 = Vector3.Zero();
  2354. this._pvec = Vector3.Zero();
  2355. this._tvec = Vector3.Zero();
  2356. this._qvec = Vector3.Zero();
  2357. }
  2358. vertex1.subtractToRef(vertex0, this._edge1);
  2359. vertex2.subtractToRef(vertex0, this._edge2);
  2360. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  2361. var det = Vector3.Dot(this._edge1, this._pvec);
  2362. if (det === 0) {
  2363. return null;
  2364. }
  2365. var invdet = 1 / det;
  2366. this.origin.subtractToRef(vertex0, this._tvec);
  2367. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  2368. if (bu < 0 || bu > 1.0) {
  2369. return null;
  2370. }
  2371. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  2372. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  2373. if (bv < 0 || bu + bv > 1.0) {
  2374. return null;
  2375. }
  2376. //check if the distance is longer than the predefined length.
  2377. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  2378. if (distance > this.length) {
  2379. return null;
  2380. }
  2381. return new BABYLON.IntersectionInfo(bu, bv, distance);
  2382. };
  2383. // Statics
  2384. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  2385. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2386. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2387. var direction = end.subtract(start);
  2388. direction.normalize();
  2389. return new Ray(start, direction);
  2390. };
  2391. /**
  2392. * Function will create a new transformed ray starting from origin and ending at the end point. Ray's length will be set, and ray will be
  2393. * transformed to the given world matrix.
  2394. * @param origin The origin point
  2395. * @param end The end point
  2396. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2397. */
  2398. Ray.CreateNewFromTo = function (origin, end, world) {
  2399. if (world === void 0) { world = Matrix.Identity(); }
  2400. var direction = end.subtract(origin);
  2401. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2402. direction.normalize();
  2403. return Ray.Transform(new Ray(origin, direction, length), world);
  2404. };
  2405. Ray.Transform = function (ray, matrix) {
  2406. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2407. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2408. return new Ray(newOrigin, newDirection, ray.length);
  2409. };
  2410. return Ray;
  2411. })();
  2412. BABYLON.Ray = Ray;
  2413. (function (Space) {
  2414. Space[Space["LOCAL"] = 0] = "LOCAL";
  2415. Space[Space["WORLD"] = 1] = "WORLD";
  2416. })(BABYLON.Space || (BABYLON.Space = {}));
  2417. var Space = BABYLON.Space;
  2418. var Axis = (function () {
  2419. function Axis() {
  2420. }
  2421. Axis.X = new Vector3(1, 0, 0);
  2422. Axis.Y = new Vector3(0, 1, 0);
  2423. Axis.Z = new Vector3(0, 0, 1);
  2424. return Axis;
  2425. })();
  2426. BABYLON.Axis = Axis;
  2427. ;
  2428. var BezierCurve = (function () {
  2429. function BezierCurve() {
  2430. }
  2431. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2432. // Extract X (which is equal to time here)
  2433. var f0 = 1 - 3 * x2 + 3 * x1;
  2434. var f1 = 3 * x2 - 6 * x1;
  2435. var f2 = 3 * x1;
  2436. var refinedT = t;
  2437. for (var i = 0; i < 5; i++) {
  2438. var refinedT2 = refinedT * refinedT;
  2439. var refinedT3 = refinedT2 * refinedT;
  2440. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2441. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2442. refinedT -= (x - t) * slope;
  2443. refinedT = Math.min(1, Math.max(0, refinedT));
  2444. }
  2445. // Resolve cubic bezier for the given x
  2446. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2447. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2448. Math.pow(refinedT, 3);
  2449. };
  2450. return BezierCurve;
  2451. })();
  2452. BABYLON.BezierCurve = BezierCurve;
  2453. (function (Orientation) {
  2454. Orientation[Orientation["CW"] = 0] = "CW";
  2455. Orientation[Orientation["CCW"] = 1] = "CCW";
  2456. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2457. var Orientation = BABYLON.Orientation;
  2458. var Angle = (function () {
  2459. function Angle(radians) {
  2460. var _this = this;
  2461. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2462. this.radians = function () { return _this._radians; };
  2463. this._radians = radians;
  2464. if (this._radians < 0)
  2465. this._radians += (2 * Math.PI);
  2466. }
  2467. Angle.BetweenTwoPoints = function (a, b) {
  2468. var delta = b.subtract(a);
  2469. var theta = Math.atan2(delta.y, delta.x);
  2470. return new Angle(theta);
  2471. };
  2472. Angle.FromRadians = function (radians) {
  2473. return new Angle(radians);
  2474. };
  2475. Angle.FromDegrees = function (degrees) {
  2476. return new Angle(degrees * Math.PI / 180);
  2477. };
  2478. return Angle;
  2479. })();
  2480. BABYLON.Angle = Angle;
  2481. var Arc2 = (function () {
  2482. function Arc2(startPoint, midPoint, endPoint) {
  2483. this.startPoint = startPoint;
  2484. this.midPoint = midPoint;
  2485. this.endPoint = endPoint;
  2486. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2487. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2488. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2489. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2490. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  2491. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2492. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2493. var a1 = this.startAngle.degrees();
  2494. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2495. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2496. // angles correction
  2497. if (a2 - a1 > +180.0)
  2498. a2 -= 360.0;
  2499. if (a2 - a1 < -180.0)
  2500. a2 += 360.0;
  2501. if (a3 - a2 > +180.0)
  2502. a3 -= 360.0;
  2503. if (a3 - a2 < -180.0)
  2504. a3 += 360.0;
  2505. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2506. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2507. }
  2508. return Arc2;
  2509. })();
  2510. BABYLON.Arc2 = Arc2;
  2511. var PathCursor = (function () {
  2512. function PathCursor(path) {
  2513. this.path = path;
  2514. this._onchange = new Array();
  2515. this.value = 0;
  2516. this.animations = new Array();
  2517. }
  2518. PathCursor.prototype.getPoint = function () {
  2519. var point = this.path.getPointAtLengthPosition(this.value);
  2520. return new Vector3(point.x, 0, point.y);
  2521. };
  2522. PathCursor.prototype.moveAhead = function (step) {
  2523. if (step === void 0) { step = 0.002; }
  2524. this.move(step);
  2525. return this;
  2526. };
  2527. PathCursor.prototype.moveBack = function (step) {
  2528. if (step === void 0) { step = 0.002; }
  2529. this.move(-step);
  2530. return this;
  2531. };
  2532. PathCursor.prototype.move = function (step) {
  2533. if (Math.abs(step) > 1) {
  2534. throw "step size should be less than 1.";
  2535. }
  2536. this.value += step;
  2537. this.ensureLimits();
  2538. this.raiseOnChange();
  2539. return this;
  2540. };
  2541. PathCursor.prototype.ensureLimits = function () {
  2542. while (this.value > 1) {
  2543. this.value -= 1;
  2544. }
  2545. while (this.value < 0) {
  2546. this.value += 1;
  2547. }
  2548. return this;
  2549. };
  2550. // used by animation engine
  2551. PathCursor.prototype.markAsDirty = function (propertyName) {
  2552. this.ensureLimits();
  2553. this.raiseOnChange();
  2554. return this;
  2555. };
  2556. PathCursor.prototype.raiseOnChange = function () {
  2557. var _this = this;
  2558. this._onchange.forEach(function (f) { return f(_this); });
  2559. return this;
  2560. };
  2561. PathCursor.prototype.onchange = function (f) {
  2562. this._onchange.push(f);
  2563. return this;
  2564. };
  2565. return PathCursor;
  2566. })();
  2567. BABYLON.PathCursor = PathCursor;
  2568. var Path2 = (function () {
  2569. function Path2(x, y) {
  2570. this._points = new Array();
  2571. this._length = 0;
  2572. this.closed = false;
  2573. this._points.push(new Vector2(x, y));
  2574. }
  2575. Path2.prototype.addLineTo = function (x, y) {
  2576. if (closed) {
  2577. BABYLON.Tools.Error("cannot add lines to closed paths");
  2578. return this;
  2579. }
  2580. var newPoint = new Vector2(x, y);
  2581. var previousPoint = this._points[this._points.length - 1];
  2582. this._points.push(newPoint);
  2583. this._length += newPoint.subtract(previousPoint).length();
  2584. return this;
  2585. };
  2586. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2587. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2588. if (closed) {
  2589. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2590. return this;
  2591. }
  2592. var startPoint = this._points[this._points.length - 1];
  2593. var midPoint = new Vector2(midX, midY);
  2594. var endPoint = new Vector2(endX, endY);
  2595. var arc = new Arc2(startPoint, midPoint, endPoint);
  2596. var increment = arc.angle.radians() / numberOfSegments;
  2597. if (arc.orientation === Orientation.CW)
  2598. increment *= -1;
  2599. var currentAngle = arc.startAngle.radians() + increment;
  2600. for (var i = 0; i < numberOfSegments; i++) {
  2601. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2602. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2603. this.addLineTo(x, y);
  2604. currentAngle += increment;
  2605. }
  2606. return this;
  2607. };
  2608. Path2.prototype.close = function () {
  2609. this.closed = true;
  2610. return this;
  2611. };
  2612. Path2.prototype.length = function () {
  2613. var result = this._length;
  2614. if (!this.closed) {
  2615. var lastPoint = this._points[this._points.length - 1];
  2616. var firstPoint = this._points[0];
  2617. result += (firstPoint.subtract(lastPoint).length());
  2618. }
  2619. return result;
  2620. };
  2621. Path2.prototype.getPoints = function () {
  2622. return this._points;
  2623. };
  2624. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2625. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2626. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2627. return Vector2.Zero();
  2628. }
  2629. var lengthPosition = normalizedLengthPosition * this.length();
  2630. var previousOffset = 0;
  2631. for (var i = 0; i < this._points.length; i++) {
  2632. var j = (i + 1) % this._points.length;
  2633. var a = this._points[i];
  2634. var b = this._points[j];
  2635. var bToA = b.subtract(a);
  2636. var nextOffset = (bToA.length() + previousOffset);
  2637. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2638. var dir = bToA.normalize();
  2639. var localOffset = lengthPosition - previousOffset;
  2640. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2641. }
  2642. previousOffset = nextOffset;
  2643. }
  2644. BABYLON.Tools.Error("internal error");
  2645. return Vector2.Zero();
  2646. };
  2647. Path2.StartingAt = function (x, y) {
  2648. return new Path2(x, y);
  2649. };
  2650. return Path2;
  2651. })();
  2652. BABYLON.Path2 = Path2;
  2653. var Path3D = (function () {
  2654. /**
  2655. * new Path3D(path, normal, raw)
  2656. * path : an array of Vector3, the curve axis of the Path3D
  2657. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  2658. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  2659. */
  2660. function Path3D(path, firstNormal, raw) {
  2661. this.path = path;
  2662. this._curve = new Array();
  2663. this._distances = new Array();
  2664. this._tangents = new Array();
  2665. this._normals = new Array();
  2666. this._binormals = new Array();
  2667. for (var p = 0; p < path.length; p++) {
  2668. this._curve[p] = path[p].clone(); // hard copy
  2669. }
  2670. this._raw = raw || false;
  2671. this._compute(firstNormal);
  2672. }
  2673. Path3D.prototype.getCurve = function () {
  2674. return this._curve;
  2675. };
  2676. Path3D.prototype.getTangents = function () {
  2677. return this._tangents;
  2678. };
  2679. Path3D.prototype.getNormals = function () {
  2680. return this._normals;
  2681. };
  2682. Path3D.prototype.getBinormals = function () {
  2683. return this._binormals;
  2684. };
  2685. Path3D.prototype.getDistances = function () {
  2686. return this._distances;
  2687. };
  2688. Path3D.prototype.update = function (path, firstNormal) {
  2689. for (var p = 0; p < path.length; p++) {
  2690. this._curve[p].x = path[p].x;
  2691. this._curve[p].y = path[p].y;
  2692. this._curve[p].z = path[p].z;
  2693. }
  2694. this._compute(firstNormal);
  2695. return this;
  2696. };
  2697. // private function compute() : computes tangents, normals and binormals
  2698. Path3D.prototype._compute = function (firstNormal) {
  2699. var l = this._curve.length;
  2700. // first and last tangents
  2701. this._tangents[0] = this._getFirstNonNullVector(0);
  2702. if (!this._raw) {
  2703. this._tangents[0].normalize();
  2704. }
  2705. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2706. if (!this._raw) {
  2707. this._tangents[l - 1].normalize();
  2708. }
  2709. // normals and binormals at first point : arbitrary vector with _normalVector()
  2710. var tg0 = this._tangents[0];
  2711. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2712. this._normals[0] = pp0;
  2713. if (!this._raw) {
  2714. this._normals[0].normalize();
  2715. }
  2716. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2717. if (!this._raw) {
  2718. this._binormals[0].normalize();
  2719. }
  2720. this._distances[0] = 0;
  2721. // normals and binormals : next points
  2722. var prev; // previous vector (segment)
  2723. var cur; // current vector (segment)
  2724. var curTang; // current tangent
  2725. // previous normal
  2726. var prevBinor; // previous binormal
  2727. for (var i = 1; i < l; i++) {
  2728. // tangents
  2729. prev = this._getLastNonNullVector(i);
  2730. if (i < l - 1) {
  2731. cur = this._getFirstNonNullVector(i);
  2732. this._tangents[i] = prev.add(cur);
  2733. this._tangents[i].normalize();
  2734. }
  2735. this._distances[i] = this._distances[i - 1] + prev.length();
  2736. // normals and binormals
  2737. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2738. curTang = this._tangents[i];
  2739. prevBinor = this._binormals[i - 1];
  2740. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2741. if (!this._raw) {
  2742. this._normals[i].normalize();
  2743. }
  2744. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2745. if (!this._raw) {
  2746. this._binormals[i].normalize();
  2747. }
  2748. }
  2749. };
  2750. // private function getFirstNonNullVector(index)
  2751. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  2752. Path3D.prototype._getFirstNonNullVector = function (index) {
  2753. var i = 1;
  2754. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  2755. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  2756. i++;
  2757. nNVector = this._curve[index + i].subtract(this._curve[index]);
  2758. }
  2759. return nNVector;
  2760. };
  2761. // private function getLastNonNullVector(index)
  2762. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  2763. Path3D.prototype._getLastNonNullVector = function (index) {
  2764. var i = 1;
  2765. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  2766. while (nLVector.length() === 0 && index > i + 1) {
  2767. i++;
  2768. nLVector = this._curve[index].subtract(this._curve[index - i]);
  2769. }
  2770. return nLVector;
  2771. };
  2772. // private function normalVector(v0, vt, va) :
  2773. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2774. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  2775. Path3D.prototype._normalVector = function (v0, vt, va) {
  2776. var normal0;
  2777. if (va === undefined || va === null) {
  2778. var point;
  2779. if (!BABYLON.Tools.WithinEpsilon(vt.y, 1, BABYLON.Engine.Epsilon)) {
  2780. point = new Vector3(0, -1, 0);
  2781. }
  2782. else if (!BABYLON.Tools.WithinEpsilon(vt.x, 1, BABYLON.Engine.Epsilon)) {
  2783. point = new Vector3(1, 0, 0);
  2784. }
  2785. else if (!BABYLON.Tools.WithinEpsilon(vt.z, 1, BABYLON.Engine.Epsilon)) {
  2786. point = new Vector3(0, 0, 1);
  2787. }
  2788. normal0 = Vector3.Cross(vt, point);
  2789. }
  2790. else {
  2791. normal0 = Vector3.Cross(vt, va);
  2792. Vector3.CrossToRef(normal0, vt, normal0);
  2793. }
  2794. normal0.normalize();
  2795. return normal0;
  2796. };
  2797. return Path3D;
  2798. })();
  2799. BABYLON.Path3D = Path3D;
  2800. var Curve3 = (function () {
  2801. function Curve3(points) {
  2802. this._length = 0;
  2803. this._points = points;
  2804. this._length = this._computeLength(points);
  2805. }
  2806. // QuadraticBezier(origin_V3, control_V3, destination_V3, nbPoints)
  2807. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2808. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2809. var bez = new Array();
  2810. var equation = function (t, val0, val1, val2) {
  2811. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  2812. return res;
  2813. };
  2814. for (var i = 0; i <= nbPoints; i++) {
  2815. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));
  2816. }
  2817. return new Curve3(bez);
  2818. };
  2819. // CubicBezier(origin_V3, control1_V3, control2_V3, destination_V3, nbPoints)
  2820. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  2821. nbPoints = nbPoints > 3 ? nbPoints : 4;
  2822. var bez = new Array();
  2823. var equation = function (t, val0, val1, val2, val3) {
  2824. var res = (1 - t) * (1 - t) * (1 - t) * val0 + 3 * t * (1 - t) * (1 - t) * val1 + 3 * t * t * (1 - t) * val2 + t * t * t * val3;
  2825. return res;
  2826. };
  2827. for (var i = 0; i <= nbPoints; i++) {
  2828. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));
  2829. }
  2830. return new Curve3(bez);
  2831. };
  2832. // HermiteSpline(origin_V3, originTangent_V3, destination_V3, destinationTangent_V3, nbPoints)
  2833. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  2834. var hermite = new Array();
  2835. var step = 1 / nbPoints;
  2836. for (var i = 0; i <= nbPoints; i++) {
  2837. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  2838. }
  2839. return new Curve3(hermite);
  2840. };
  2841. Curve3.prototype.getPoints = function () {
  2842. return this._points;
  2843. };
  2844. Curve3.prototype.length = function () {
  2845. return this._length;
  2846. };
  2847. Curve3.prototype.continue = function (curve) {
  2848. var lastPoint = this._points[this._points.length - 1];
  2849. var continuedPoints = this._points.slice();
  2850. var curvePoints = curve.getPoints();
  2851. for (var i = 1; i < curvePoints.length; i++) {
  2852. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  2853. }
  2854. var continuedCurve = new Curve3(continuedPoints);
  2855. return continuedCurve;
  2856. };
  2857. Curve3.prototype._computeLength = function (path) {
  2858. var l = 0;
  2859. for (var i = 1; i < path.length; i++) {
  2860. l += (path[i].subtract(path[i - 1])).length();
  2861. }
  2862. return l;
  2863. };
  2864. return Curve3;
  2865. })();
  2866. BABYLON.Curve3 = Curve3;
  2867. // Vertex formats
  2868. var PositionNormalVertex = (function () {
  2869. function PositionNormalVertex(position, normal) {
  2870. if (position === void 0) { position = Vector3.Zero(); }
  2871. if (normal === void 0) { normal = Vector3.Up(); }
  2872. this.position = position;
  2873. this.normal = normal;
  2874. }
  2875. PositionNormalVertex.prototype.clone = function () {
  2876. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  2877. };
  2878. return PositionNormalVertex;
  2879. })();
  2880. BABYLON.PositionNormalVertex = PositionNormalVertex;
  2881. var PositionNormalTextureVertex = (function () {
  2882. function PositionNormalTextureVertex(position, normal, uv) {
  2883. if (position === void 0) { position = Vector3.Zero(); }
  2884. if (normal === void 0) { normal = Vector3.Up(); }
  2885. if (uv === void 0) { uv = Vector2.Zero(); }
  2886. this.position = position;
  2887. this.normal = normal;
  2888. this.uv = uv;
  2889. }
  2890. PositionNormalTextureVertex.prototype.clone = function () {
  2891. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  2892. };
  2893. return PositionNormalTextureVertex;
  2894. })();
  2895. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  2896. })(BABYLON || (BABYLON = {}));
  2897. var BABYLON;
  2898. (function (BABYLON) {
  2899. var Database = (function () {
  2900. function Database(urlToScene, callbackManifestChecked) {
  2901. // Handling various flavors of prefixed version of IndexedDB
  2902. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  2903. this.callbackManifestChecked = callbackManifestChecked;
  2904. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  2905. this.db = null;
  2906. this.enableSceneOffline = false;
  2907. this.enableTexturesOffline = false;
  2908. this.manifestVersionFound = 0;
  2909. this.mustUpdateRessources = false;
  2910. this.hasReachedQuota = false;
  2911. if (!Database.IDBStorageEnabled) {
  2912. this.callbackManifestChecked(true);
  2913. }
  2914. else {
  2915. this.checkManifestFile();
  2916. }
  2917. }
  2918. Database.prototype.checkManifestFile = function () {
  2919. var _this = this;
  2920. function noManifestFile() {
  2921. that.enableSceneOffline = false;
  2922. that.enableTexturesOffline = false;
  2923. that.callbackManifestChecked(false);
  2924. }
  2925. var that = this;
  2926. var manifestURL = this.currentSceneUrl + ".manifest";
  2927. var xhr = new XMLHttpRequest();
  2928. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  2929. xhr.open("GET", manifestURLTimeStamped, true);
  2930. xhr.addEventListener("load", function () {
  2931. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  2932. try {
  2933. var manifestFile = JSON.parse(xhr.response);
  2934. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  2935. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  2936. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  2937. _this.manifestVersionFound = manifestFile.version;
  2938. }
  2939. if (_this.callbackManifestChecked) {
  2940. _this.callbackManifestChecked(true);
  2941. }
  2942. }
  2943. catch (ex) {
  2944. noManifestFile();
  2945. }
  2946. }
  2947. else {
  2948. noManifestFile();
  2949. }
  2950. }, false);
  2951. xhr.addEventListener("error", function (event) {
  2952. noManifestFile();
  2953. }, false);
  2954. try {
  2955. xhr.send();
  2956. }
  2957. catch (ex) {
  2958. BABYLON.Tools.Error("Error on XHR send request.");
  2959. that.callbackManifestChecked(false);
  2960. }
  2961. };
  2962. Database.prototype.openAsync = function (successCallback, errorCallback) {
  2963. var _this = this;
  2964. function handleError() {
  2965. that.isSupported = false;
  2966. if (errorCallback)
  2967. errorCallback();
  2968. }
  2969. var that = this;
  2970. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  2971. // Your browser doesn't support IndexedDB
  2972. this.isSupported = false;
  2973. if (errorCallback)
  2974. errorCallback();
  2975. }
  2976. else {
  2977. // If the DB hasn't been opened or created yet
  2978. if (!this.db) {
  2979. this.hasReachedQuota = false;
  2980. this.isSupported = true;
  2981. var request = this.idbFactory.open("babylonjs", 1);
  2982. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  2983. request.onerror = function (event) {
  2984. handleError();
  2985. };
  2986. // executes when a version change transaction cannot complete due to other active transactions
  2987. request.onblocked = function (event) {
  2988. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  2989. handleError();
  2990. };
  2991. // DB has been opened successfully
  2992. request.onsuccess = function (event) {
  2993. _this.db = request.result;
  2994. successCallback();
  2995. };
  2996. // Initialization of the DB. Creating Scenes & Textures stores
  2997. request.onupgradeneeded = function (event) {
  2998. _this.db = (event.target).result;
  2999. try {
  3000. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3001. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3002. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3003. }
  3004. catch (ex) {
  3005. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3006. handleError();
  3007. }
  3008. };
  3009. }
  3010. else {
  3011. if (successCallback)
  3012. successCallback();
  3013. }
  3014. }
  3015. };
  3016. Database.prototype.loadImageFromDB = function (url, image) {
  3017. var _this = this;
  3018. var completeURL = Database.ReturnFullUrlLocation(url);
  3019. var saveAndLoadImage = function () {
  3020. if (!_this.hasReachedQuota && _this.db !== null) {
  3021. // the texture is not yet in the DB, let's try to save it
  3022. _this._saveImageIntoDBAsync(completeURL, image);
  3023. }
  3024. else {
  3025. image.src = url;
  3026. }
  3027. };
  3028. if (!this.mustUpdateRessources) {
  3029. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3030. }
  3031. else {
  3032. saveAndLoadImage();
  3033. }
  3034. };
  3035. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3036. if (this.isSupported && this.db !== null) {
  3037. var texture;
  3038. var transaction = this.db.transaction(["textures"]);
  3039. transaction.onabort = function (event) {
  3040. image.src = url;
  3041. };
  3042. transaction.oncomplete = function (event) {
  3043. var blobTextureURL;
  3044. if (texture) {
  3045. var URL = window.URL || window.webkitURL;
  3046. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3047. image.onerror = function () {
  3048. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3049. image.src = url;
  3050. };
  3051. image.src = blobTextureURL;
  3052. }
  3053. else {
  3054. notInDBCallback();
  3055. }
  3056. };
  3057. var getRequest = transaction.objectStore("textures").get(url);
  3058. getRequest.onsuccess = function (event) {
  3059. texture = (event.target).result;
  3060. };
  3061. getRequest.onerror = function (event) {
  3062. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3063. image.src = url;
  3064. };
  3065. }
  3066. else {
  3067. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3068. image.src = url;
  3069. }
  3070. };
  3071. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3072. var _this = this;
  3073. if (this.isSupported) {
  3074. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3075. var generateBlobUrl = function () {
  3076. var blobTextureURL;
  3077. if (blob) {
  3078. var URL = window.URL || window.webkitURL;
  3079. try {
  3080. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3081. }
  3082. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3083. catch (ex) {
  3084. blobTextureURL = URL.createObjectURL(blob);
  3085. }
  3086. }
  3087. image.src = blobTextureURL;
  3088. };
  3089. if (Database.IsUASupportingBlobStorage) {
  3090. var xhr = new XMLHttpRequest(), blob;
  3091. xhr.open("GET", url, true);
  3092. xhr.responseType = "blob";
  3093. xhr.addEventListener("load", function () {
  3094. if (xhr.status === 200) {
  3095. // Blob as response (XHR2)
  3096. blob = xhr.response;
  3097. var transaction = _this.db.transaction(["textures"], "readwrite");
  3098. // the transaction could abort because of a QuotaExceededError error
  3099. transaction.onabort = function (event) {
  3100. try {
  3101. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3102. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3103. this.hasReachedQuota = true;
  3104. }
  3105. }
  3106. catch (ex) { }
  3107. generateBlobUrl();
  3108. };
  3109. transaction.oncomplete = function (event) {
  3110. generateBlobUrl();
  3111. };
  3112. var newTexture = { textureUrl: url, data: blob };
  3113. try {
  3114. // Put the blob into the dabase
  3115. var addRequest = transaction.objectStore("textures").put(newTexture);
  3116. addRequest.onsuccess = function (event) {
  3117. };
  3118. addRequest.onerror = function (event) {
  3119. generateBlobUrl();
  3120. };
  3121. }
  3122. catch (ex) {
  3123. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3124. if (ex.code === 25) {
  3125. Database.IsUASupportingBlobStorage = false;
  3126. }
  3127. image.src = url;
  3128. }
  3129. }
  3130. else {
  3131. image.src = url;
  3132. }
  3133. }, false);
  3134. xhr.addEventListener("error", function (event) {
  3135. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3136. image.src = url;
  3137. }, false);
  3138. xhr.send();
  3139. }
  3140. else {
  3141. image.src = url;
  3142. }
  3143. }
  3144. else {
  3145. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3146. image.src = url;
  3147. }
  3148. };
  3149. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3150. var _this = this;
  3151. var updateVersion = function (event) {
  3152. // the version is not yet in the DB or we need to update it
  3153. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3154. };
  3155. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3156. };
  3157. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3158. var _this = this;
  3159. if (this.isSupported) {
  3160. var version;
  3161. try {
  3162. var transaction = this.db.transaction(["versions"]);
  3163. transaction.oncomplete = function (event) {
  3164. if (version) {
  3165. // If the version in the JSON file is > than the version in DB
  3166. if (_this.manifestVersionFound > version.data) {
  3167. _this.mustUpdateRessources = true;
  3168. updateInDBCallback();
  3169. }
  3170. else {
  3171. callback(version.data);
  3172. }
  3173. }
  3174. else {
  3175. _this.mustUpdateRessources = true;
  3176. updateInDBCallback();
  3177. }
  3178. };
  3179. transaction.onabort = function (event) {
  3180. callback(-1);
  3181. };
  3182. var getRequest = transaction.objectStore("versions").get(url);
  3183. getRequest.onsuccess = function (event) {
  3184. version = (event.target).result;
  3185. };
  3186. getRequest.onerror = function (event) {
  3187. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3188. callback(-1);
  3189. };
  3190. }
  3191. catch (ex) {
  3192. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3193. callback(-1);
  3194. }
  3195. }
  3196. else {
  3197. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3198. callback(-1);
  3199. }
  3200. };
  3201. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3202. var _this = this;
  3203. if (this.isSupported && !this.hasReachedQuota) {
  3204. try {
  3205. // Open a transaction to the database
  3206. var transaction = this.db.transaction(["versions"], "readwrite");
  3207. // the transaction could abort because of a QuotaExceededError error
  3208. transaction.onabort = function (event) {
  3209. try {
  3210. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3211. _this.hasReachedQuota = true;
  3212. }
  3213. }
  3214. catch (ex) { }
  3215. callback(-1);
  3216. };
  3217. transaction.oncomplete = function (event) {
  3218. callback(_this.manifestVersionFound);
  3219. };
  3220. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3221. // Put the scene into the database
  3222. var addRequest = transaction.objectStore("versions").put(newVersion);
  3223. addRequest.onsuccess = function (event) {
  3224. };
  3225. addRequest.onerror = function (event) {
  3226. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3227. };
  3228. }
  3229. catch (ex) {
  3230. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3231. callback(-1);
  3232. }
  3233. }
  3234. else {
  3235. callback(-1);
  3236. }
  3237. };
  3238. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3239. var _this = this;
  3240. var completeUrl = Database.ReturnFullUrlLocation(url);
  3241. var saveAndLoadFile = function (event) {
  3242. // the scene is not yet in the DB, let's try to save it
  3243. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3244. };
  3245. this._checkVersionFromDB(completeUrl, function (version) {
  3246. if (version !== -1) {
  3247. if (!_this.mustUpdateRessources) {
  3248. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3249. }
  3250. else {
  3251. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3252. }
  3253. }
  3254. else {
  3255. errorCallback();
  3256. }
  3257. });
  3258. };
  3259. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3260. if (this.isSupported) {
  3261. var targetStore;
  3262. if (url.indexOf(".babylon") !== -1) {
  3263. targetStore = "scenes";
  3264. }
  3265. else {
  3266. targetStore = "textures";
  3267. }
  3268. var file;
  3269. var transaction = this.db.transaction([targetStore]);
  3270. transaction.oncomplete = function (event) {
  3271. if (file) {
  3272. callback(file.data);
  3273. }
  3274. else {
  3275. notInDBCallback();
  3276. }
  3277. };
  3278. transaction.onabort = function (event) {
  3279. notInDBCallback();
  3280. };
  3281. var getRequest = transaction.objectStore(targetStore).get(url);
  3282. getRequest.onsuccess = function (event) {
  3283. file = (event.target).result;
  3284. };
  3285. getRequest.onerror = function (event) {
  3286. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3287. notInDBCallback();
  3288. };
  3289. }
  3290. else {
  3291. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3292. callback();
  3293. }
  3294. };
  3295. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3296. var _this = this;
  3297. if (this.isSupported) {
  3298. var targetStore;
  3299. if (url.indexOf(".babylon") !== -1) {
  3300. targetStore = "scenes";
  3301. }
  3302. else {
  3303. targetStore = "textures";
  3304. }
  3305. // Create XHR
  3306. var xhr = new XMLHttpRequest(), fileData;
  3307. xhr.open("GET", url, true);
  3308. if (useArrayBuffer) {
  3309. xhr.responseType = "arraybuffer";
  3310. }
  3311. xhr.onprogress = progressCallback;
  3312. xhr.addEventListener("load", function () {
  3313. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  3314. // Blob as response (XHR2)
  3315. //fileData = xhr.responseText;
  3316. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  3317. if (!_this.hasReachedQuota) {
  3318. // Open a transaction to the database
  3319. var transaction = _this.db.transaction([targetStore], "readwrite");
  3320. // the transaction could abort because of a QuotaExceededError error
  3321. transaction.onabort = function (event) {
  3322. try {
  3323. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3324. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3325. this.hasReachedQuota = true;
  3326. }
  3327. }
  3328. catch (ex) { }
  3329. callback(fileData);
  3330. };
  3331. transaction.oncomplete = function (event) {
  3332. callback(fileData);
  3333. };
  3334. var newFile;
  3335. if (targetStore === "scenes") {
  3336. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  3337. }
  3338. else {
  3339. newFile = { textureUrl: url, data: fileData };
  3340. }
  3341. try {
  3342. // Put the scene into the database
  3343. var addRequest = transaction.objectStore(targetStore).put(newFile);
  3344. addRequest.onsuccess = function (event) {
  3345. };
  3346. addRequest.onerror = function (event) {
  3347. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  3348. };
  3349. }
  3350. catch (ex) {
  3351. callback(fileData);
  3352. }
  3353. }
  3354. else {
  3355. callback(fileData);
  3356. }
  3357. }
  3358. else {
  3359. callback();
  3360. }
  3361. }, false);
  3362. xhr.addEventListener("error", function (event) {
  3363. BABYLON.Tools.Error("error on XHR request.");
  3364. callback();
  3365. }, false);
  3366. xhr.send();
  3367. }
  3368. else {
  3369. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3370. callback();
  3371. }
  3372. };
  3373. Database.IsUASupportingBlobStorage = true;
  3374. Database.IDBStorageEnabled = true;
  3375. Database.parseURL = function (url) {
  3376. var a = document.createElement('a');
  3377. a.href = url;
  3378. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  3379. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  3380. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  3381. return absLocation;
  3382. };
  3383. Database.ReturnFullUrlLocation = function (url) {
  3384. if (url.indexOf("http:/") === -1) {
  3385. return (Database.parseURL(window.location.href) + url);
  3386. }
  3387. else {
  3388. return url;
  3389. }
  3390. };
  3391. return Database;
  3392. })();
  3393. BABYLON.Database = Database;
  3394. })(BABYLON || (BABYLON = {}));
  3395. var BABYLON;
  3396. (function (BABYLON) {
  3397. var Internals;
  3398. (function (Internals) {
  3399. /*
  3400. * Based on jsTGALoader - Javascript loader for TGA file
  3401. * By Vincent Thibault
  3402. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  3403. */
  3404. var TGATools = (function () {
  3405. function TGATools() {
  3406. }
  3407. TGATools.GetTGAHeader = function (data) {
  3408. var offset = 0;
  3409. var header = {
  3410. id_length: data[offset++],
  3411. colormap_type: data[offset++],
  3412. image_type: data[offset++],
  3413. colormap_index: data[offset++] | data[offset++] << 8,
  3414. colormap_length: data[offset++] | data[offset++] << 8,
  3415. colormap_size: data[offset++],
  3416. origin: [
  3417. data[offset++] | data[offset++] << 8,
  3418. data[offset++] | data[offset++] << 8
  3419. ],
  3420. width: data[offset++] | data[offset++] << 8,
  3421. height: data[offset++] | data[offset++] << 8,
  3422. pixel_size: data[offset++],
  3423. flags: data[offset++]
  3424. };
  3425. return header;
  3426. };
  3427. TGATools.UploadContent = function (gl, data) {
  3428. // Not enough data to contain header ?
  3429. if (data.length < 19) {
  3430. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  3431. return;
  3432. }
  3433. // Read Header
  3434. var offset = 18;
  3435. var header = TGATools.GetTGAHeader(data);
  3436. // Assume it's a valid Targa file.
  3437. if (header.id_length + offset > data.length) {
  3438. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  3439. return;
  3440. }
  3441. // Skip not needed data
  3442. offset += header.id_length;
  3443. var use_rle = false;
  3444. var use_pal = false;
  3445. var use_rgb = false;
  3446. var use_grey = false;
  3447. // Get some informations.
  3448. switch (header.image_type) {
  3449. case TGATools._TYPE_RLE_INDEXED:
  3450. use_rle = true;
  3451. case TGATools._TYPE_INDEXED:
  3452. use_pal = true;
  3453. break;
  3454. case TGATools._TYPE_RLE_RGB:
  3455. use_rle = true;
  3456. case TGATools._TYPE_RGB:
  3457. use_rgb = true;
  3458. break;
  3459. case TGATools._TYPE_RLE_GREY:
  3460. use_rle = true;
  3461. case TGATools._TYPE_GREY:
  3462. use_grey = true;
  3463. break;
  3464. }
  3465. var pixel_data;
  3466. var numAlphaBits = header.flags & 0xf;
  3467. var pixel_size = header.pixel_size >> 3;
  3468. var pixel_total = header.width * header.height * pixel_size;
  3469. // Read palettes
  3470. var palettes;
  3471. if (use_pal) {
  3472. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  3473. }
  3474. // Read LRE
  3475. if (use_rle) {
  3476. pixel_data = new Uint8Array(pixel_total);
  3477. var c, count, i;
  3478. var localOffset = 0;
  3479. var pixels = new Uint8Array(pixel_size);
  3480. while (offset < pixel_total && localOffset < pixel_total) {
  3481. c = data[offset++];
  3482. count = (c & 0x7f) + 1;
  3483. // RLE pixels
  3484. if (c & 0x80) {
  3485. // Bind pixel tmp array
  3486. for (i = 0; i < pixel_size; ++i) {
  3487. pixels[i] = data[offset++];
  3488. }
  3489. // Copy pixel array
  3490. for (i = 0; i < count; ++i) {
  3491. pixel_data.set(pixels, localOffset + i * pixel_size);
  3492. }
  3493. localOffset += pixel_size * count;
  3494. }
  3495. else {
  3496. count *= pixel_size;
  3497. for (i = 0; i < count; ++i) {
  3498. pixel_data[localOffset + i] = data[offset++];
  3499. }
  3500. localOffset += count;
  3501. }
  3502. }
  3503. }
  3504. else {
  3505. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  3506. }
  3507. // Load to texture
  3508. var x_start, y_start, x_step, y_step, y_end, x_end;
  3509. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  3510. default:
  3511. case TGATools._ORIGIN_UL:
  3512. x_start = 0;
  3513. x_step = 1;
  3514. x_end = header.width;
  3515. y_start = 0;
  3516. y_step = 1;
  3517. y_end = header.height;
  3518. break;
  3519. case TGATools._ORIGIN_BL:
  3520. x_start = 0;
  3521. x_step = 1;
  3522. x_end = header.width;
  3523. y_start = header.height - 1;
  3524. y_step = -1;
  3525. y_end = -1;
  3526. break;
  3527. case TGATools._ORIGIN_UR:
  3528. x_start = header.width - 1;
  3529. x_step = -1;
  3530. x_end = -1;
  3531. y_start = 0;
  3532. y_step = 1;
  3533. y_end = header.height;
  3534. break;
  3535. case TGATools._ORIGIN_BR:
  3536. x_start = header.width - 1;
  3537. x_step = -1;
  3538. x_end = -1;
  3539. y_start = header.height - 1;
  3540. y_step = -1;
  3541. y_end = -1;
  3542. break;
  3543. }
  3544. // Load the specify method
  3545. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  3546. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  3547. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  3548. };
  3549. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3550. var image = pixel_data, colormap = palettes;
  3551. var width = header.width, height = header.height;
  3552. var color, i = 0, x, y;
  3553. var imageData = new Uint8Array(width * height * 4);
  3554. for (y = y_start; y !== y_end; y += y_step) {
  3555. for (x = x_start; x !== x_end; x += x_step, i++) {
  3556. color = image[i];
  3557. imageData[(x + width * y) * 4 + 3] = 255;
  3558. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  3559. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  3560. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  3561. }
  3562. }
  3563. return imageData;
  3564. };
  3565. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3566. var image = pixel_data;
  3567. var width = header.width, height = header.height;
  3568. var color, i = 0, x, y;
  3569. var imageData = new Uint8Array(width * height * 4);
  3570. for (y = y_start; y !== y_end; y += y_step) {
  3571. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3572. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  3573. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  3574. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  3575. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  3576. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  3577. }
  3578. }
  3579. return imageData;
  3580. };
  3581. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3582. var image = pixel_data;
  3583. var width = header.width, height = header.height;
  3584. var i = 0, x, y;
  3585. var imageData = new Uint8Array(width * height * 4);
  3586. for (y = y_start; y !== y_end; y += y_step) {
  3587. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  3588. imageData[(x + width * y) * 4 + 3] = 255;
  3589. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3590. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3591. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3592. }
  3593. }
  3594. return imageData;
  3595. };
  3596. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3597. var image = pixel_data;
  3598. var width = header.width, height = header.height;
  3599. var i = 0, x, y;
  3600. var imageData = new Uint8Array(width * height * 4);
  3601. for (y = y_start; y !== y_end; y += y_step) {
  3602. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  3603. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3604. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3605. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3606. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  3607. }
  3608. }
  3609. return imageData;
  3610. };
  3611. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3612. var image = pixel_data;
  3613. var width = header.width, height = header.height;
  3614. var color, i = 0, x, y;
  3615. var imageData = new Uint8Array(width * height * 4);
  3616. for (y = y_start; y !== y_end; y += y_step) {
  3617. for (x = x_start; x !== x_end; x += x_step, i++) {
  3618. color = image[i];
  3619. imageData[(x + width * y) * 4 + 0] = color;
  3620. imageData[(x + width * y) * 4 + 1] = color;
  3621. imageData[(x + width * y) * 4 + 2] = color;
  3622. imageData[(x + width * y) * 4 + 3] = 255;
  3623. }
  3624. }
  3625. return imageData;
  3626. };
  3627. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3628. var image = pixel_data;
  3629. var width = header.width, height = header.height;
  3630. var i = 0, x, y;
  3631. var imageData = new Uint8Array(width * height * 4);
  3632. for (y = y_start; y !== y_end; y += y_step) {
  3633. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3634. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  3635. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  3636. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3637. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  3638. }
  3639. }
  3640. return imageData;
  3641. };
  3642. TGATools._TYPE_NO_DATA = 0;
  3643. TGATools._TYPE_INDEXED = 1;
  3644. TGATools._TYPE_RGB = 2;
  3645. TGATools._TYPE_GREY = 3;
  3646. TGATools._TYPE_RLE_INDEXED = 9;
  3647. TGATools._TYPE_RLE_RGB = 10;
  3648. TGATools._TYPE_RLE_GREY = 11;
  3649. TGATools._ORIGIN_MASK = 0x30;
  3650. TGATools._ORIGIN_SHIFT = 0x04;
  3651. TGATools._ORIGIN_BL = 0x00;
  3652. TGATools._ORIGIN_BR = 0x01;
  3653. TGATools._ORIGIN_UL = 0x02;
  3654. TGATools._ORIGIN_UR = 0x03;
  3655. return TGATools;
  3656. })();
  3657. Internals.TGATools = TGATools;
  3658. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  3659. })(BABYLON || (BABYLON = {}));
  3660. var BABYLON;
  3661. (function (BABYLON) {
  3662. var SmartArray = (function () {
  3663. function SmartArray(capacity) {
  3664. this.length = 0;
  3665. this._duplicateId = 0;
  3666. this.data = new Array(capacity);
  3667. this._id = SmartArray._GlobalId++;
  3668. }
  3669. SmartArray.prototype.push = function (value) {
  3670. this.data[this.length++] = value;
  3671. if (this.length > this.data.length) {
  3672. this.data.length *= 2;
  3673. }
  3674. if (!value.__smartArrayFlags) {
  3675. value.__smartArrayFlags = {};
  3676. }
  3677. value.__smartArrayFlags[this._id] = this._duplicateId;
  3678. };
  3679. SmartArray.prototype.pushNoDuplicate = function (value) {
  3680. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  3681. return;
  3682. }
  3683. this.push(value);
  3684. };
  3685. SmartArray.prototype.sort = function (compareFn) {
  3686. this.data.sort(compareFn);
  3687. };
  3688. SmartArray.prototype.reset = function () {
  3689. this.length = 0;
  3690. this._duplicateId++;
  3691. };
  3692. SmartArray.prototype.concat = function (array) {
  3693. if (array.length === 0) {
  3694. return;
  3695. }
  3696. if (this.length + array.length > this.data.length) {
  3697. this.data.length = (this.length + array.length) * 2;
  3698. }
  3699. for (var index = 0; index < array.length; index++) {
  3700. this.data[this.length++] = (array.data || array)[index];
  3701. }
  3702. };
  3703. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  3704. if (array.length === 0) {
  3705. return;
  3706. }
  3707. if (this.length + array.length > this.data.length) {
  3708. this.data.length = (this.length + array.length) * 2;
  3709. }
  3710. for (var index = 0; index < array.length; index++) {
  3711. var item = (array.data || array)[index];
  3712. this.pushNoDuplicate(item);
  3713. }
  3714. };
  3715. SmartArray.prototype.indexOf = function (value) {
  3716. var position = this.data.indexOf(value);
  3717. if (position >= this.length) {
  3718. return -1;
  3719. }
  3720. return position;
  3721. };
  3722. // Statics
  3723. SmartArray._GlobalId = 0;
  3724. return SmartArray;
  3725. })();
  3726. BABYLON.SmartArray = SmartArray;
  3727. })(BABYLON || (BABYLON = {}));
  3728. var BABYLON;
  3729. (function (BABYLON) {
  3730. var SmartCollection = (function () {
  3731. function SmartCollection(capacity) {
  3732. if (capacity === void 0) { capacity = 10; }
  3733. this.count = 0;
  3734. this._initialCapacity = capacity;
  3735. this.items = {};
  3736. this._keys = new Array(this._initialCapacity);
  3737. }
  3738. SmartCollection.prototype.add = function (key, item) {
  3739. if (this.items[key] != undefined) {
  3740. return -1;
  3741. }
  3742. this.items[key] = item;
  3743. //literal keys are always strings, but we keep source type of key in _keys array
  3744. this._keys[this.count++] = key;
  3745. if (this.count > this._keys.length) {
  3746. this._keys.length *= 2;
  3747. }
  3748. return this.count;
  3749. };
  3750. SmartCollection.prototype.remove = function (key) {
  3751. if (this.items[key] == undefined) {
  3752. return -1;
  3753. }
  3754. return this.removeItemOfIndex(this.indexOf(key));
  3755. };
  3756. SmartCollection.prototype.removeItemOfIndex = function (index) {
  3757. if (index < this.count && index > -1) {
  3758. delete this.items[this._keys[index]];
  3759. //here, shifting by hand is better optimised than .splice
  3760. while (index < this.count) {
  3761. this._keys[index] = this._keys[index + 1];
  3762. index++;
  3763. }
  3764. }
  3765. else {
  3766. return -1;
  3767. }
  3768. return --this.count;
  3769. };
  3770. SmartCollection.prototype.indexOf = function (key) {
  3771. for (var i = 0; i !== this.count; i++) {
  3772. if (this._keys[i] === key) {
  3773. return i;
  3774. }
  3775. }
  3776. return -1;
  3777. };
  3778. SmartCollection.prototype.item = function (key) {
  3779. return this.items[key];
  3780. };
  3781. SmartCollection.prototype.getAllKeys = function () {
  3782. if (this.count > 0) {
  3783. var keys = new Array(this.count);
  3784. for (var i = 0; i < this.count; i++) {
  3785. keys[i] = this._keys[i];
  3786. }
  3787. return keys;
  3788. }
  3789. else {
  3790. return undefined;
  3791. }
  3792. };
  3793. SmartCollection.prototype.getKeyByIndex = function (index) {
  3794. if (index < this.count && index > -1) {
  3795. return this._keys[index];
  3796. }
  3797. else {
  3798. return undefined;
  3799. }
  3800. };
  3801. SmartCollection.prototype.getItemByIndex = function (index) {
  3802. if (index < this.count && index > -1) {
  3803. return this.items[this._keys[index]];
  3804. }
  3805. else {
  3806. return undefined;
  3807. }
  3808. };
  3809. SmartCollection.prototype.empty = function () {
  3810. if (this.count > 0) {
  3811. this.count = 0;
  3812. this.items = {};
  3813. this._keys = new Array(this._initialCapacity);
  3814. }
  3815. };
  3816. SmartCollection.prototype.forEach = function (block) {
  3817. var key;
  3818. for (key in this.items) {
  3819. if (this.items.hasOwnProperty(key)) {
  3820. block(this.items[key]);
  3821. }
  3822. }
  3823. };
  3824. return SmartCollection;
  3825. })();
  3826. BABYLON.SmartCollection = SmartCollection;
  3827. })(BABYLON || (BABYLON = {}));
  3828. var BABYLON;
  3829. (function (BABYLON) {
  3830. // Screenshots
  3831. var screenshotCanvas;
  3832. var cloneValue = function (source, destinationObject) {
  3833. if (!source)
  3834. return null;
  3835. if (source instanceof BABYLON.Mesh) {
  3836. return null;
  3837. }
  3838. if (source instanceof BABYLON.SubMesh) {
  3839. return source.clone(destinationObject);
  3840. }
  3841. else if (source.clone) {
  3842. return source.clone();
  3843. }
  3844. return null;
  3845. };
  3846. var Tools = (function () {
  3847. function Tools() {
  3848. }
  3849. Tools.ToHex = function (i) {
  3850. var str = i.toString(16);
  3851. if (i <= 15) {
  3852. return ("0" + str).toUpperCase();
  3853. }
  3854. return str.toUpperCase();
  3855. };
  3856. Tools.SetImmediate = function (action) {
  3857. if (window.setImmediate) {
  3858. window.setImmediate(action);
  3859. }
  3860. else {
  3861. setTimeout(action, 1);
  3862. }
  3863. };
  3864. Tools.IsExponentOfTwo = function (value) {
  3865. var count = 1;
  3866. do {
  3867. count *= 2;
  3868. } while (count < value);
  3869. return count === value;
  3870. };
  3871. Tools.GetExponentOfTwo = function (value, max) {
  3872. var count = 1;
  3873. do {
  3874. count *= 2;
  3875. } while (count < value);
  3876. if (count > max)
  3877. count = max;
  3878. return count;
  3879. };
  3880. Tools.GetFilename = function (path) {
  3881. var index = path.lastIndexOf("/");
  3882. if (index < 0)
  3883. return path;
  3884. return path.substring(index + 1);
  3885. };
  3886. Tools.GetDOMTextContent = function (element) {
  3887. var result = "";
  3888. var child = element.firstChild;
  3889. while (child) {
  3890. if (child.nodeType === 3) {
  3891. result += child.textContent;
  3892. }
  3893. child = child.nextSibling;
  3894. }
  3895. return result;
  3896. };
  3897. Tools.ToDegrees = function (angle) {
  3898. return angle * 180 / Math.PI;
  3899. };
  3900. Tools.ToRadians = function (angle) {
  3901. return angle * Math.PI / 180;
  3902. };
  3903. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  3904. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  3905. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  3906. for (var index = indexStart; index < indexStart + indexCount; index++) {
  3907. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  3908. minimum = BABYLON.Vector3.Minimize(current, minimum);
  3909. maximum = BABYLON.Vector3.Maximize(current, maximum);
  3910. }
  3911. return {
  3912. minimum: minimum,
  3913. maximum: maximum
  3914. };
  3915. };
  3916. Tools.ExtractMinAndMax = function (positions, start, count) {
  3917. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  3918. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  3919. for (var index = start; index < start + count; index++) {
  3920. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  3921. minimum = BABYLON.Vector3.Minimize(current, minimum);
  3922. maximum = BABYLON.Vector3.Maximize(current, maximum);
  3923. }
  3924. return {
  3925. minimum: minimum,
  3926. maximum: maximum
  3927. };
  3928. };
  3929. Tools.MakeArray = function (obj, allowsNullUndefined) {
  3930. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  3931. return undefined;
  3932. return Array.isArray(obj) ? obj : [obj];
  3933. };
  3934. // Misc.
  3935. Tools.GetPointerPrefix = function () {
  3936. var eventPrefix = "pointer";
  3937. // Check if hand.js is referenced or if the browser natively supports pointer events
  3938. if (!navigator.pointerEnabled) {
  3939. eventPrefix = "mouse";
  3940. }
  3941. return eventPrefix;
  3942. };
  3943. Tools.QueueNewFrame = function (func) {
  3944. if (window.requestAnimationFrame)
  3945. window.requestAnimationFrame(func);
  3946. else if (window.msRequestAnimationFrame)
  3947. window.msRequestAnimationFrame(func);
  3948. else if (window.webkitRequestAnimationFrame)
  3949. window.webkitRequestAnimationFrame(func);
  3950. else if (window.mozRequestAnimationFrame)
  3951. window.mozRequestAnimationFrame(func);
  3952. else if (window.oRequestAnimationFrame)
  3953. window.oRequestAnimationFrame(func);
  3954. else {
  3955. window.setTimeout(func, 16);
  3956. }
  3957. };
  3958. Tools.RequestFullscreen = function (element) {
  3959. if (element.requestFullscreen)
  3960. element.requestFullscreen();
  3961. else if (element.msRequestFullscreen)
  3962. element.msRequestFullscreen();
  3963. else if (element.webkitRequestFullscreen)
  3964. element.webkitRequestFullscreen();
  3965. else if (element.mozRequestFullScreen)
  3966. element.mozRequestFullScreen();
  3967. };
  3968. Tools.ExitFullscreen = function () {
  3969. if (document.exitFullscreen) {
  3970. document.exitFullscreen();
  3971. }
  3972. else if (document.mozCancelFullScreen) {
  3973. document.mozCancelFullScreen();
  3974. }
  3975. else if (document.webkitCancelFullScreen) {
  3976. document.webkitCancelFullScreen();
  3977. }
  3978. else if (document.msCancelFullScreen) {
  3979. document.msCancelFullScreen();
  3980. }
  3981. };
  3982. // External files
  3983. Tools.CleanUrl = function (url) {
  3984. url = url.replace(/#/mg, "%23");
  3985. return url;
  3986. };
  3987. Tools.LoadImage = function (url, onload, onerror, database) {
  3988. url = Tools.CleanUrl(url);
  3989. var img = new Image();
  3990. if (url.substr(0, 5) !== "data:")
  3991. img.crossOrigin = 'anonymous';
  3992. img.onload = function () {
  3993. onload(img);
  3994. };
  3995. img.onerror = function (err) {
  3996. Tools.Error("Error while trying to load texture: " + url);
  3997. 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";
  3998. onload(img);
  3999. };
  4000. var noIndexedDB = function () {
  4001. img.src = url;
  4002. };
  4003. var loadFromIndexedDB = function () {
  4004. database.loadImageFromDB(url, img);
  4005. };
  4006. //ANY database to do!
  4007. if (database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4008. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4009. }
  4010. else {
  4011. if (url.indexOf("file:") === -1) {
  4012. noIndexedDB();
  4013. }
  4014. else {
  4015. try {
  4016. var textureName = url.substring(5);
  4017. var blobURL;
  4018. try {
  4019. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4020. }
  4021. catch (ex) {
  4022. // Chrome doesn't support oneTimeOnly parameter
  4023. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4024. }
  4025. img.src = blobURL;
  4026. }
  4027. catch (e) {
  4028. img.src = null;
  4029. }
  4030. }
  4031. }
  4032. return img;
  4033. };
  4034. //ANY
  4035. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4036. url = Tools.CleanUrl(url);
  4037. var noIndexedDB = function () {
  4038. var request = new XMLHttpRequest();
  4039. var loadUrl = Tools.BaseUrl + url;
  4040. request.open('GET', loadUrl, true);
  4041. if (useArrayBuffer) {
  4042. request.responseType = "arraybuffer";
  4043. }
  4044. request.onprogress = progressCallBack;
  4045. request.onreadystatechange = function () {
  4046. if (request.readyState === 4) {
  4047. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  4048. callback(!useArrayBuffer ? request.responseText : request.response);
  4049. }
  4050. else {
  4051. if (onError) {
  4052. onError();
  4053. }
  4054. else {
  4055. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4056. }
  4057. }
  4058. }
  4059. };
  4060. request.send(null);
  4061. };
  4062. var loadFromIndexedDB = function () {
  4063. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4064. };
  4065. if (url.indexOf("file:") !== -1) {
  4066. var fileName = url.substring(5);
  4067. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  4068. }
  4069. else {
  4070. // Caching all files
  4071. if (database && database.enableSceneOffline) {
  4072. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4073. }
  4074. else {
  4075. noIndexedDB();
  4076. }
  4077. }
  4078. };
  4079. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4080. var reader = new FileReader();
  4081. reader.onload = function (e) {
  4082. //target doesn't have result from ts 1.3
  4083. callback(e.target['result']);
  4084. };
  4085. reader.onprogress = progressCallback;
  4086. reader.readAsDataURL(fileToLoad);
  4087. };
  4088. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4089. var reader = new FileReader();
  4090. reader.onerror = function (e) {
  4091. Tools.Log("Error while reading file: " + fileToLoad.name);
  4092. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  4093. };
  4094. reader.onload = function (e) {
  4095. //target doesn't have result from ts 1.3
  4096. callback(e.target['result']);
  4097. };
  4098. reader.onprogress = progressCallBack;
  4099. if (!useArrayBuffer) {
  4100. // Asynchronous read
  4101. reader.readAsText(fileToLoad);
  4102. }
  4103. else {
  4104. reader.readAsArrayBuffer(fileToLoad);
  4105. }
  4106. };
  4107. //returns a downloadable url to a file content.
  4108. Tools.FileAsURL = function (content) {
  4109. var fileBlob = new Blob([content]);
  4110. var url = window.URL || window.webkitURL;
  4111. var link = url.createObjectURL(fileBlob);
  4112. return link;
  4113. };
  4114. // Misc.
  4115. Tools.Clamp = function (value, min, max) {
  4116. if (min === void 0) { min = 0; }
  4117. if (max === void 0) { max = 1; }
  4118. return Math.min(max, Math.max(min, value));
  4119. };
  4120. // Returns -1 when value is a negative number and
  4121. // +1 when value is a positive number.
  4122. Tools.Sign = function (value) {
  4123. value = +value; // convert to a number
  4124. if (value === 0 || isNaN(value))
  4125. return value;
  4126. return value > 0 ? 1 : -1;
  4127. };
  4128. Tools.Format = function (value, decimals) {
  4129. if (decimals === void 0) { decimals = 2; }
  4130. return value.toFixed(decimals);
  4131. };
  4132. Tools.CheckExtends = function (v, min, max) {
  4133. if (v.x < min.x)
  4134. min.x = v.x;
  4135. if (v.y < min.y)
  4136. min.y = v.y;
  4137. if (v.z < min.z)
  4138. min.z = v.z;
  4139. if (v.x > max.x)
  4140. max.x = v.x;
  4141. if (v.y > max.y)
  4142. max.y = v.y;
  4143. if (v.z > max.z)
  4144. max.z = v.z;
  4145. };
  4146. Tools.WithinEpsilon = function (a, b, epsilon) {
  4147. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4148. var num = a - b;
  4149. return -epsilon <= num && num <= epsilon;
  4150. };
  4151. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4152. for (var prop in source) {
  4153. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4154. continue;
  4155. }
  4156. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4157. continue;
  4158. }
  4159. var sourceValue = source[prop];
  4160. var typeOfSourceValue = typeof sourceValue;
  4161. if (typeOfSourceValue === "function") {
  4162. continue;
  4163. }
  4164. if (typeOfSourceValue === "object") {
  4165. if (sourceValue instanceof Array) {
  4166. destination[prop] = [];
  4167. if (sourceValue.length > 0) {
  4168. if (typeof sourceValue[0] == "object") {
  4169. for (var index = 0; index < sourceValue.length; index++) {
  4170. var clonedValue = cloneValue(sourceValue[index], destination);
  4171. if (destination[prop].indexOf(clonedValue) === -1) {
  4172. destination[prop].push(clonedValue);
  4173. }
  4174. }
  4175. }
  4176. else {
  4177. destination[prop] = sourceValue.slice(0);
  4178. }
  4179. }
  4180. }
  4181. else {
  4182. destination[prop] = cloneValue(sourceValue, destination);
  4183. }
  4184. }
  4185. else {
  4186. destination[prop] = sourceValue;
  4187. }
  4188. }
  4189. };
  4190. Tools.IsEmpty = function (obj) {
  4191. for (var i in obj) {
  4192. return false;
  4193. }
  4194. return true;
  4195. };
  4196. Tools.RegisterTopRootEvents = function (events) {
  4197. for (var index = 0; index < events.length; index++) {
  4198. var event = events[index];
  4199. window.addEventListener(event.name, event.handler, false);
  4200. try {
  4201. if (window.parent) {
  4202. window.parent.addEventListener(event.name, event.handler, false);
  4203. }
  4204. }
  4205. catch (e) {
  4206. }
  4207. }
  4208. };
  4209. Tools.UnregisterTopRootEvents = function (events) {
  4210. for (var index = 0; index < events.length; index++) {
  4211. var event = events[index];
  4212. window.removeEventListener(event.name, event.handler);
  4213. try {
  4214. if (window.parent) {
  4215. window.parent.removeEventListener(event.name, event.handler);
  4216. }
  4217. }
  4218. catch (e) {
  4219. }
  4220. }
  4221. };
  4222. Tools.DumpFramebuffer = function (width, height, engine, successCallback) {
  4223. // Read the contents of the framebuffer
  4224. var numberOfChannelsByLine = width * 4;
  4225. var halfHeight = height / 2;
  4226. //Reading datas from WebGL
  4227. var data = engine.readPixels(0, 0, width, height);
  4228. //To flip image on Y axis.
  4229. for (var i = 0; i < halfHeight; i++) {
  4230. for (var j = 0; j < numberOfChannelsByLine; j++) {
  4231. var currentCell = j + i * numberOfChannelsByLine;
  4232. var targetLine = height - i - 1;
  4233. var targetCell = j + targetLine * numberOfChannelsByLine;
  4234. var temp = data[currentCell];
  4235. data[currentCell] = data[targetCell];
  4236. data[targetCell] = temp;
  4237. }
  4238. }
  4239. // Create a 2D canvas to store the result
  4240. if (!screenshotCanvas) {
  4241. screenshotCanvas = document.createElement('canvas');
  4242. }
  4243. screenshotCanvas.width = width;
  4244. screenshotCanvas.height = height;
  4245. var context = screenshotCanvas.getContext('2d');
  4246. // Copy the pixels to a 2D canvas
  4247. var imageData = context.createImageData(width, height);
  4248. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  4249. var castData = imageData.data;
  4250. castData.set(data);
  4251. context.putImageData(imageData, 0, 0);
  4252. var base64Image = screenshotCanvas.toDataURL();
  4253. if (successCallback) {
  4254. successCallback(base64Image);
  4255. }
  4256. else {
  4257. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  4258. if (("download" in document.createElement("a"))) {
  4259. var a = window.document.createElement("a");
  4260. a.href = base64Image;
  4261. var date = new Date();
  4262. var stringDate = date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  4263. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  4264. window.document.body.appendChild(a);
  4265. a.addEventListener("click", function () {
  4266. a.parentElement.removeChild(a);
  4267. });
  4268. a.click();
  4269. }
  4270. else {
  4271. var newWindow = window.open("");
  4272. var img = newWindow.document.createElement("img");
  4273. img.src = base64Image;
  4274. newWindow.document.body.appendChild(img);
  4275. }
  4276. }
  4277. };
  4278. Tools.CreateScreenshot = function (engine, camera, size, successCallback) {
  4279. var width;
  4280. var height;
  4281. //If a precision value is specified
  4282. if (size.precision) {
  4283. width = Math.round(engine.getRenderWidth() * size.precision);
  4284. height = Math.round(width / engine.getAspectRatio(camera));
  4285. size = { width: width, height: height };
  4286. }
  4287. else if (size.width && size.height) {
  4288. width = size.width;
  4289. height = size.height;
  4290. }
  4291. else if (size.width && !size.height) {
  4292. width = size.width;
  4293. height = Math.round(width / engine.getAspectRatio(camera));
  4294. size = { width: width, height: height };
  4295. }
  4296. else if (size.height && !size.width) {
  4297. height = size.height;
  4298. width = Math.round(height * engine.getAspectRatio(camera));
  4299. size = { width: width, height: height };
  4300. }
  4301. else if (!isNaN(size)) {
  4302. height = size;
  4303. width = size;
  4304. }
  4305. else {
  4306. Tools.Error("Invalid 'size' parameter !");
  4307. return;
  4308. }
  4309. var scene = camera.getScene();
  4310. var previousCamera = null;
  4311. if (scene.activeCamera !== camera) {
  4312. previousCamera = scene.activeCamera;
  4313. scene.activeCamera = camera;
  4314. }
  4315. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  4316. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  4317. texture.renderList = scene.meshes;
  4318. texture.onAfterRender = function () {
  4319. Tools.DumpFramebuffer(width, height, engine, successCallback);
  4320. };
  4321. scene.incrementRenderId();
  4322. texture.render(true);
  4323. texture.dispose();
  4324. if (previousCamera) {
  4325. scene.activeCamera = previousCamera;
  4326. }
  4327. };
  4328. // XHR response validator for local file scenario
  4329. Tools.ValidateXHRData = function (xhr, dataType) {
  4330. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  4331. if (dataType === void 0) { dataType = 7; }
  4332. try {
  4333. if (dataType & 1) {
  4334. if (xhr.responseText && xhr.responseText.length > 0) {
  4335. return true;
  4336. }
  4337. else if (dataType === 1) {
  4338. return false;
  4339. }
  4340. }
  4341. if (dataType & 2) {
  4342. // Check header width and height since there is no "TGA" magic number
  4343. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  4344. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  4345. return true;
  4346. }
  4347. else if (dataType === 2) {
  4348. return false;
  4349. }
  4350. }
  4351. if (dataType & 4) {
  4352. // Check for the "DDS" magic number
  4353. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  4354. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  4355. return true;
  4356. }
  4357. else {
  4358. return false;
  4359. }
  4360. }
  4361. }
  4362. catch (e) {
  4363. }
  4364. return false;
  4365. };
  4366. Object.defineProperty(Tools, "NoneLogLevel", {
  4367. get: function () {
  4368. return Tools._NoneLogLevel;
  4369. },
  4370. enumerable: true,
  4371. configurable: true
  4372. });
  4373. Object.defineProperty(Tools, "MessageLogLevel", {
  4374. get: function () {
  4375. return Tools._MessageLogLevel;
  4376. },
  4377. enumerable: true,
  4378. configurable: true
  4379. });
  4380. Object.defineProperty(Tools, "WarningLogLevel", {
  4381. get: function () {
  4382. return Tools._WarningLogLevel;
  4383. },
  4384. enumerable: true,
  4385. configurable: true
  4386. });
  4387. Object.defineProperty(Tools, "ErrorLogLevel", {
  4388. get: function () {
  4389. return Tools._ErrorLogLevel;
  4390. },
  4391. enumerable: true,
  4392. configurable: true
  4393. });
  4394. Object.defineProperty(Tools, "AllLogLevel", {
  4395. get: function () {
  4396. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  4397. },
  4398. enumerable: true,
  4399. configurable: true
  4400. });
  4401. Tools._AddLogEntry = function (entry) {
  4402. Tools._LogCache = entry + Tools._LogCache;
  4403. if (Tools.OnNewCacheEntry) {
  4404. Tools.OnNewCacheEntry(entry);
  4405. }
  4406. };
  4407. Tools._FormatMessage = function (message) {
  4408. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  4409. var date = new Date();
  4410. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  4411. };
  4412. Tools._LogDisabled = function (message) {
  4413. // nothing to do
  4414. };
  4415. Tools._LogEnabled = function (message) {
  4416. var formattedMessage = Tools._FormatMessage(message);
  4417. console.log("BJS - " + formattedMessage);
  4418. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  4419. Tools._AddLogEntry(entry);
  4420. };
  4421. Tools._WarnDisabled = function (message) {
  4422. // nothing to do
  4423. };
  4424. Tools._WarnEnabled = function (message) {
  4425. var formattedMessage = Tools._FormatMessage(message);
  4426. console.warn("BJS - " + formattedMessage);
  4427. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  4428. Tools._AddLogEntry(entry);
  4429. };
  4430. Tools._ErrorDisabled = function (message) {
  4431. // nothing to do
  4432. };
  4433. Tools._ErrorEnabled = function (message) {
  4434. Tools.errorsCount++;
  4435. var formattedMessage = Tools._FormatMessage(message);
  4436. console.error("BJS - " + formattedMessage);
  4437. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  4438. Tools._AddLogEntry(entry);
  4439. };
  4440. Object.defineProperty(Tools, "LogCache", {
  4441. get: function () {
  4442. return Tools._LogCache;
  4443. },
  4444. enumerable: true,
  4445. configurable: true
  4446. });
  4447. Tools.ClearLogCache = function () {
  4448. Tools._LogCache = "";
  4449. Tools.errorsCount = 0;
  4450. };
  4451. Object.defineProperty(Tools, "LogLevels", {
  4452. set: function (level) {
  4453. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  4454. Tools.Log = Tools._LogEnabled;
  4455. }
  4456. else {
  4457. Tools.Log = Tools._LogDisabled;
  4458. }
  4459. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  4460. Tools.Warn = Tools._WarnEnabled;
  4461. }
  4462. else {
  4463. Tools.Warn = Tools._WarnDisabled;
  4464. }
  4465. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  4466. Tools.Error = Tools._ErrorEnabled;
  4467. }
  4468. else {
  4469. Tools.Error = Tools._ErrorDisabled;
  4470. }
  4471. },
  4472. enumerable: true,
  4473. configurable: true
  4474. });
  4475. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  4476. get: function () {
  4477. return Tools._PerformanceNoneLogLevel;
  4478. },
  4479. enumerable: true,
  4480. configurable: true
  4481. });
  4482. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  4483. get: function () {
  4484. return Tools._PerformanceUserMarkLogLevel;
  4485. },
  4486. enumerable: true,
  4487. configurable: true
  4488. });
  4489. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  4490. get: function () {
  4491. return Tools._PerformanceConsoleLogLevel;
  4492. },
  4493. enumerable: true,
  4494. configurable: true
  4495. });
  4496. Object.defineProperty(Tools, "PerformanceLogLevel", {
  4497. set: function (level) {
  4498. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  4499. Tools.StartPerformanceCounter = Tools._StartUserMark;
  4500. Tools.EndPerformanceCounter = Tools._EndUserMark;
  4501. return;
  4502. }
  4503. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  4504. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  4505. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  4506. return;
  4507. }
  4508. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4509. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4510. },
  4511. enumerable: true,
  4512. configurable: true
  4513. });
  4514. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  4515. };
  4516. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  4517. };
  4518. Tools._StartUserMark = function (counterName, condition) {
  4519. if (condition === void 0) { condition = true; }
  4520. if (!condition || !Tools._performance.mark) {
  4521. return;
  4522. }
  4523. Tools._performance.mark(counterName + "-Begin");
  4524. };
  4525. Tools._EndUserMark = function (counterName, condition) {
  4526. if (condition === void 0) { condition = true; }
  4527. if (!condition || !Tools._performance.mark) {
  4528. return;
  4529. }
  4530. Tools._performance.mark(counterName + "-End");
  4531. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  4532. };
  4533. Tools._StartPerformanceConsole = function (counterName, condition) {
  4534. if (condition === void 0) { condition = true; }
  4535. if (!condition) {
  4536. return;
  4537. }
  4538. Tools._StartUserMark(counterName, condition);
  4539. if (console.time) {
  4540. console.time(counterName);
  4541. }
  4542. };
  4543. Tools._EndPerformanceConsole = function (counterName, condition) {
  4544. if (condition === void 0) { condition = true; }
  4545. if (!condition) {
  4546. return;
  4547. }
  4548. Tools._EndUserMark(counterName, condition);
  4549. if (console.time) {
  4550. console.timeEnd(counterName);
  4551. }
  4552. };
  4553. Object.defineProperty(Tools, "Now", {
  4554. get: function () {
  4555. if (window.performance && window.performance.now) {
  4556. return window.performance.now();
  4557. }
  4558. return new Date().getTime();
  4559. },
  4560. enumerable: true,
  4561. configurable: true
  4562. });
  4563. Tools.BaseUrl = "";
  4564. // Logs
  4565. Tools._NoneLogLevel = 0;
  4566. Tools._MessageLogLevel = 1;
  4567. Tools._WarningLogLevel = 2;
  4568. Tools._ErrorLogLevel = 4;
  4569. Tools._LogCache = "";
  4570. Tools.errorsCount = 0;
  4571. Tools.Log = Tools._LogEnabled;
  4572. Tools.Warn = Tools._WarnEnabled;
  4573. Tools.Error = Tools._ErrorEnabled;
  4574. // Performances
  4575. Tools._PerformanceNoneLogLevel = 0;
  4576. Tools._PerformanceUserMarkLogLevel = 1;
  4577. Tools._PerformanceConsoleLogLevel = 2;
  4578. Tools._performance = window.performance;
  4579. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4580. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4581. return Tools;
  4582. })();
  4583. BABYLON.Tools = Tools;
  4584. /**
  4585. * An implementation of a loop for asynchronous functions.
  4586. */
  4587. var AsyncLoop = (function () {
  4588. /**
  4589. * Constroctor.
  4590. * @param iterations the number of iterations.
  4591. * @param _fn the function to run each iteration
  4592. * @param _successCallback the callback that will be called upon succesful execution
  4593. * @param offset starting offset.
  4594. */
  4595. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  4596. if (offset === void 0) { offset = 0; }
  4597. this.iterations = iterations;
  4598. this._fn = _fn;
  4599. this._successCallback = _successCallback;
  4600. this.index = offset - 1;
  4601. this._done = false;
  4602. }
  4603. /**
  4604. * Execute the next iteration. Must be called after the last iteration was finished.
  4605. */
  4606. AsyncLoop.prototype.executeNext = function () {
  4607. if (!this._done) {
  4608. if (this.index + 1 < this.iterations) {
  4609. ++this.index;
  4610. this._fn(this);
  4611. }
  4612. else {
  4613. this.breakLoop();
  4614. }
  4615. }
  4616. };
  4617. /**
  4618. * Break the loop and run the success callback.
  4619. */
  4620. AsyncLoop.prototype.breakLoop = function () {
  4621. this._done = true;
  4622. this._successCallback();
  4623. };
  4624. /**
  4625. * Helper function
  4626. */
  4627. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  4628. if (offset === void 0) { offset = 0; }
  4629. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  4630. loop.executeNext();
  4631. return loop;
  4632. };
  4633. /**
  4634. * A for-loop that will run a given number of iterations synchronous and the rest async.
  4635. * @param iterations total number of iterations
  4636. * @param syncedIterations number of synchronous iterations in each async iteration.
  4637. * @param fn the function to call each iteration.
  4638. * @param callback a success call back that will be called when iterating stops.
  4639. * @param breakFunction a break condition (optional)
  4640. * @param timeout timeout settings for the setTimeout function. default - 0.
  4641. * @constructor
  4642. */
  4643. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  4644. if (timeout === void 0) { timeout = 0; }
  4645. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  4646. if (breakFunction && breakFunction())
  4647. loop.breakLoop();
  4648. else {
  4649. setTimeout(function () {
  4650. for (var i = 0; i < syncedIterations; ++i) {
  4651. var iteration = (loop.index * syncedIterations) + i;
  4652. if (iteration >= iterations)
  4653. break;
  4654. fn(iteration);
  4655. if (breakFunction && breakFunction()) {
  4656. loop.breakLoop();
  4657. break;
  4658. }
  4659. }
  4660. loop.executeNext();
  4661. }, timeout);
  4662. }
  4663. }, callback);
  4664. };
  4665. return AsyncLoop;
  4666. })();
  4667. BABYLON.AsyncLoop = AsyncLoop;
  4668. })(BABYLON || (BABYLON = {}));
  4669. var BABYLON;
  4670. (function (BABYLON) {
  4671. var _DepthCullingState = (function () {
  4672. function _DepthCullingState() {
  4673. this._isDepthTestDirty = false;
  4674. this._isDepthMaskDirty = false;
  4675. this._isDepthFuncDirty = false;
  4676. this._isCullFaceDirty = false;
  4677. this._isCullDirty = false;
  4678. this._isZOffsetDirty = false;
  4679. }
  4680. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  4681. get: function () {
  4682. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  4683. },
  4684. enumerable: true,
  4685. configurable: true
  4686. });
  4687. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  4688. get: function () {
  4689. return this._zOffset;
  4690. },
  4691. set: function (value) {
  4692. if (this._zOffset === value) {
  4693. return;
  4694. }
  4695. this._zOffset = value;
  4696. this._isZOffsetDirty = true;
  4697. },
  4698. enumerable: true,
  4699. configurable: true
  4700. });
  4701. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  4702. get: function () {
  4703. return this._cullFace;
  4704. },
  4705. set: function (value) {
  4706. if (this._cullFace === value) {
  4707. return;
  4708. }
  4709. this._cullFace = value;
  4710. this._isCullFaceDirty = true;
  4711. },
  4712. enumerable: true,
  4713. configurable: true
  4714. });
  4715. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  4716. get: function () {
  4717. return this._cull;
  4718. },
  4719. set: function (value) {
  4720. if (this._cull === value) {
  4721. return;
  4722. }
  4723. this._cull = value;
  4724. this._isCullDirty = true;
  4725. },
  4726. enumerable: true,
  4727. configurable: true
  4728. });
  4729. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  4730. get: function () {
  4731. return this._depthFunc;
  4732. },
  4733. set: function (value) {
  4734. if (this._depthFunc === value) {
  4735. return;
  4736. }
  4737. this._depthFunc = value;
  4738. this._isDepthFuncDirty = true;
  4739. },
  4740. enumerable: true,
  4741. configurable: true
  4742. });
  4743. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  4744. get: function () {
  4745. return this._depthMask;
  4746. },
  4747. set: function (value) {
  4748. if (this._depthMask === value) {
  4749. return;
  4750. }
  4751. this._depthMask = value;
  4752. this._isDepthMaskDirty = true;
  4753. },
  4754. enumerable: true,
  4755. configurable: true
  4756. });
  4757. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  4758. get: function () {
  4759. return this._depthTest;
  4760. },
  4761. set: function (value) {
  4762. if (this._depthTest === value) {
  4763. return;
  4764. }
  4765. this._depthTest = value;
  4766. this._isDepthTestDirty = true;
  4767. },
  4768. enumerable: true,
  4769. configurable: true
  4770. });
  4771. _DepthCullingState.prototype.reset = function () {
  4772. this._depthMask = true;
  4773. this._depthTest = true;
  4774. this._depthFunc = null;
  4775. this._cull = null;
  4776. this._cullFace = null;
  4777. this._zOffset = 0;
  4778. this._isDepthTestDirty = true;
  4779. this._isDepthMaskDirty = true;
  4780. this._isDepthFuncDirty = false;
  4781. this._isCullFaceDirty = false;
  4782. this._isCullDirty = false;
  4783. this._isZOffsetDirty = false;
  4784. };
  4785. _DepthCullingState.prototype.apply = function (gl) {
  4786. if (!this.isDirty) {
  4787. return;
  4788. }
  4789. // Cull
  4790. if (this._isCullDirty) {
  4791. if (this.cull) {
  4792. gl.enable(gl.CULL_FACE);
  4793. }
  4794. else {
  4795. gl.disable(gl.CULL_FACE);
  4796. }
  4797. this._isCullDirty = false;
  4798. }
  4799. // Cull face
  4800. if (this._isCullFaceDirty) {
  4801. gl.cullFace(this.cullFace);
  4802. this._isCullFaceDirty = false;
  4803. }
  4804. // Depth mask
  4805. if (this._isDepthMaskDirty) {
  4806. gl.depthMask(this.depthMask);
  4807. this._isDepthMaskDirty = false;
  4808. }
  4809. // Depth test
  4810. if (this._isDepthTestDirty) {
  4811. if (this.depthTest) {
  4812. gl.enable(gl.DEPTH_TEST);
  4813. }
  4814. else {
  4815. gl.disable(gl.DEPTH_TEST);
  4816. }
  4817. this._isDepthTestDirty = false;
  4818. }
  4819. // Depth func
  4820. if (this._isDepthFuncDirty) {
  4821. gl.depthFunc(this.depthFunc);
  4822. this._isDepthFuncDirty = false;
  4823. }
  4824. // zOffset
  4825. if (this._isZOffsetDirty) {
  4826. if (this.zOffset) {
  4827. gl.enable(gl.POLYGON_OFFSET_FILL);
  4828. gl.polygonOffset(this.zOffset, 0);
  4829. }
  4830. else {
  4831. gl.disable(gl.POLYGON_OFFSET_FILL);
  4832. }
  4833. this._isZOffsetDirty = false;
  4834. }
  4835. };
  4836. return _DepthCullingState;
  4837. })();
  4838. BABYLON._DepthCullingState = _DepthCullingState;
  4839. var _AlphaState = (function () {
  4840. function _AlphaState() {
  4841. this._isAlphaBlendDirty = false;
  4842. this._isBlendFunctionParametersDirty = false;
  4843. this._alphaBlend = false;
  4844. this._blendFunctionParameters = new Array(4);
  4845. }
  4846. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  4847. get: function () {
  4848. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  4849. },
  4850. enumerable: true,
  4851. configurable: true
  4852. });
  4853. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  4854. get: function () {
  4855. return this._alphaBlend;
  4856. },
  4857. set: function (value) {
  4858. if (this._alphaBlend === value) {
  4859. return;
  4860. }
  4861. this._alphaBlend = value;
  4862. this._isAlphaBlendDirty = true;
  4863. },
  4864. enumerable: true,
  4865. configurable: true
  4866. });
  4867. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  4868. if (this._blendFunctionParameters[0] === value0 &&
  4869. this._blendFunctionParameters[1] === value1 &&
  4870. this._blendFunctionParameters[2] === value2 &&
  4871. this._blendFunctionParameters[3] === value3) {
  4872. return;
  4873. }
  4874. this._blendFunctionParameters[0] = value0;
  4875. this._blendFunctionParameters[1] = value1;
  4876. this._blendFunctionParameters[2] = value2;
  4877. this._blendFunctionParameters[3] = value3;
  4878. this._isBlendFunctionParametersDirty = true;
  4879. };
  4880. _AlphaState.prototype.reset = function () {
  4881. this._alphaBlend = false;
  4882. this._blendFunctionParameters[0] = null;
  4883. this._blendFunctionParameters[1] = null;
  4884. this._blendFunctionParameters[2] = null;
  4885. this._blendFunctionParameters[3] = null;
  4886. this._isAlphaBlendDirty = true;
  4887. this._isBlendFunctionParametersDirty = false;
  4888. };
  4889. _AlphaState.prototype.apply = function (gl) {
  4890. if (!this.isDirty) {
  4891. return;
  4892. }
  4893. // Alpha blend
  4894. if (this._isAlphaBlendDirty) {
  4895. if (this._alphaBlend) {
  4896. gl.enable(gl.BLEND);
  4897. }
  4898. else {
  4899. gl.disable(gl.BLEND);
  4900. }
  4901. this._isAlphaBlendDirty = false;
  4902. }
  4903. // Alpha function
  4904. if (this._isBlendFunctionParametersDirty) {
  4905. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  4906. this._isBlendFunctionParametersDirty = false;
  4907. }
  4908. };
  4909. return _AlphaState;
  4910. })();
  4911. BABYLON._AlphaState = _AlphaState;
  4912. var compileShader = function (gl, source, type, defines) {
  4913. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  4914. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  4915. gl.compileShader(shader);
  4916. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  4917. throw new Error(gl.getShaderInfoLog(shader));
  4918. }
  4919. return shader;
  4920. };
  4921. var getWebGLTextureType = function (gl, type) {
  4922. var textureType = gl.UNSIGNED_BYTE;
  4923. if (type === Engine.TEXTURETYPE_FLOAT)
  4924. textureType = gl.FLOAT;
  4925. return textureType;
  4926. };
  4927. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  4928. var magFilter = gl.NEAREST;
  4929. var minFilter = gl.NEAREST;
  4930. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  4931. magFilter = gl.LINEAR;
  4932. if (generateMipMaps) {
  4933. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  4934. }
  4935. else {
  4936. minFilter = gl.LINEAR;
  4937. }
  4938. }
  4939. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  4940. magFilter = gl.LINEAR;
  4941. if (generateMipMaps) {
  4942. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  4943. }
  4944. else {
  4945. minFilter = gl.LINEAR;
  4946. }
  4947. }
  4948. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  4949. magFilter = gl.NEAREST;
  4950. if (generateMipMaps) {
  4951. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  4952. }
  4953. else {
  4954. minFilter = gl.NEAREST;
  4955. }
  4956. }
  4957. return {
  4958. min: minFilter,
  4959. mag: magFilter
  4960. };
  4961. };
  4962. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  4963. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  4964. var engine = scene.getEngine();
  4965. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  4966. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  4967. gl.bindTexture(gl.TEXTURE_2D, texture);
  4968. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  4969. texture._baseWidth = width;
  4970. texture._baseHeight = height;
  4971. texture._width = potWidth;
  4972. texture._height = potHeight;
  4973. texture.isReady = true;
  4974. processFunction(potWidth, potHeight);
  4975. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  4976. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  4977. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  4978. if (!noMipmap && !isCompressed) {
  4979. gl.generateMipmap(gl.TEXTURE_2D);
  4980. }
  4981. gl.bindTexture(gl.TEXTURE_2D, null);
  4982. engine.resetTextureCache();
  4983. scene._removePendingData(texture);
  4984. };
  4985. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  4986. var onload = function () {
  4987. loadedImages[index] = img;
  4988. loadedImages._internalCount++;
  4989. scene._removePendingData(img);
  4990. if (loadedImages._internalCount === 6) {
  4991. onfinish(loadedImages);
  4992. }
  4993. };
  4994. var onerror = function () {
  4995. scene._removePendingData(img);
  4996. };
  4997. var img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  4998. scene._addPendingData(img);
  4999. };
  5000. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  5001. var loadedImages = [];
  5002. loadedImages._internalCount = 0;
  5003. for (var index = 0; index < 6; index++) {
  5004. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  5005. }
  5006. };
  5007. var EngineCapabilities = (function () {
  5008. function EngineCapabilities() {
  5009. }
  5010. return EngineCapabilities;
  5011. })();
  5012. BABYLON.EngineCapabilities = EngineCapabilities;
  5013. /**
  5014. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  5015. */
  5016. var Engine = (function () {
  5017. /**
  5018. * @constructor
  5019. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  5020. * @param {boolean} [antialias] - enable antialias
  5021. * @param options - further options to be sent to the getContext function
  5022. */
  5023. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  5024. var _this = this;
  5025. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = true; }
  5026. // Public members
  5027. this.isFullscreen = false;
  5028. this.isPointerLock = false;
  5029. this.cullBackFaces = true;
  5030. this.renderEvenInBackground = true;
  5031. // To enable/disable IDB support and avoid XHR on .manifest
  5032. this.enableOfflineSupport = true;
  5033. this.scenes = new Array();
  5034. this._windowIsBackground = false;
  5035. this._drawCalls = 0;
  5036. this._renderingQueueLaunched = false;
  5037. this._activeRenderLoops = [];
  5038. // FPS
  5039. this.fpsRange = 60;
  5040. this.previousFramesDuration = [];
  5041. this.fps = 60;
  5042. this.deltaTime = 0;
  5043. // States
  5044. this._depthCullingState = new _DepthCullingState();
  5045. this._alphaState = new _AlphaState();
  5046. this._alphaMode = Engine.ALPHA_DISABLE;
  5047. // Cache
  5048. this._loadedTexturesCache = new Array();
  5049. this._maxTextureChannels = 16;
  5050. this._activeTexturesCache = new Array(this._maxTextureChannels);
  5051. this._compiledEffects = {};
  5052. this._uintIndicesCurrentlySet = false;
  5053. this._renderingCanvas = canvas;
  5054. options = options || {};
  5055. options.antialias = antialias;
  5056. if (options.preserveDrawingBuffer === undefined) {
  5057. options.preserveDrawingBuffer = false;
  5058. }
  5059. // GL
  5060. try {
  5061. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  5062. }
  5063. catch (e) {
  5064. throw new Error("WebGL not supported");
  5065. }
  5066. if (!this._gl) {
  5067. throw new Error("WebGL not supported");
  5068. }
  5069. this._onBlur = function () {
  5070. _this._windowIsBackground = true;
  5071. };
  5072. this._onFocus = function () {
  5073. _this._windowIsBackground = false;
  5074. };
  5075. window.addEventListener("blur", this._onBlur);
  5076. window.addEventListener("focus", this._onFocus);
  5077. // Viewport
  5078. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / (window.devicePixelRatio || 1.0) : 1.0;
  5079. this.resize();
  5080. // Caps
  5081. this._caps = new EngineCapabilities();
  5082. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  5083. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  5084. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  5085. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  5086. // Infos
  5087. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  5088. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  5089. if (rendererInfo != null) {
  5090. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  5091. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  5092. }
  5093. if (!this._glVendor) {
  5094. this._glVendor = "Unknown vendor";
  5095. }
  5096. if (!this._glRenderer) {
  5097. this._glRenderer = "Unknown renderer";
  5098. }
  5099. // Extensions
  5100. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  5101. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  5102. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  5103. 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');
  5104. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  5105. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  5106. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  5107. this._caps.highPrecisionShaderSupported = true;
  5108. if (this._gl.getShaderPrecisionFormat) {
  5109. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  5110. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  5111. }
  5112. // Depth buffer
  5113. this.setDepthBuffer(true);
  5114. this.setDepthFunctionToLessOrEqual();
  5115. this.setDepthWrite(true);
  5116. // Fullscreen
  5117. this._onFullscreenChange = function () {
  5118. if (document.fullscreen !== undefined) {
  5119. _this.isFullscreen = document.fullscreen;
  5120. }
  5121. else if (document.mozFullScreen !== undefined) {
  5122. _this.isFullscreen = document.mozFullScreen;
  5123. }
  5124. else if (document.webkitIsFullScreen !== undefined) {
  5125. _this.isFullscreen = document.webkitIsFullScreen;
  5126. }
  5127. else if (document.msIsFullScreen !== undefined) {
  5128. _this.isFullscreen = document.msIsFullScreen;
  5129. }
  5130. // Pointer lock
  5131. if (_this.isFullscreen && _this._pointerLockRequested) {
  5132. canvas.requestPointerLock = canvas.requestPointerLock ||
  5133. canvas.msRequestPointerLock ||
  5134. canvas.mozRequestPointerLock ||
  5135. canvas.webkitRequestPointerLock;
  5136. if (canvas.requestPointerLock) {
  5137. canvas.requestPointerLock();
  5138. }
  5139. }
  5140. };
  5141. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  5142. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  5143. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  5144. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  5145. // Pointer lock
  5146. this._onPointerLockChange = function () {
  5147. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  5148. document.webkitPointerLockElement === canvas ||
  5149. document.msPointerLockElement === canvas ||
  5150. document.pointerLockElement === canvas);
  5151. };
  5152. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  5153. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  5154. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  5155. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  5156. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  5157. Engine.audioEngine = new BABYLON.AudioEngine();
  5158. }
  5159. //default loading screen
  5160. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  5161. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  5162. }
  5163. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  5164. get: function () {
  5165. return Engine._ALPHA_DISABLE;
  5166. },
  5167. enumerable: true,
  5168. configurable: true
  5169. });
  5170. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  5171. get: function () {
  5172. return Engine._ALPHA_ONEONE;
  5173. },
  5174. enumerable: true,
  5175. configurable: true
  5176. });
  5177. Object.defineProperty(Engine, "ALPHA_ADD", {
  5178. get: function () {
  5179. return Engine._ALPHA_ADD;
  5180. },
  5181. enumerable: true,
  5182. configurable: true
  5183. });
  5184. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  5185. get: function () {
  5186. return Engine._ALPHA_COMBINE;
  5187. },
  5188. enumerable: true,
  5189. configurable: true
  5190. });
  5191. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  5192. get: function () {
  5193. return Engine._ALPHA_SUBTRACT;
  5194. },
  5195. enumerable: true,
  5196. configurable: true
  5197. });
  5198. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  5199. get: function () {
  5200. return Engine._ALPHA_MULTIPLY;
  5201. },
  5202. enumerable: true,
  5203. configurable: true
  5204. });
  5205. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  5206. get: function () {
  5207. return Engine._ALPHA_MAXIMIZED;
  5208. },
  5209. enumerable: true,
  5210. configurable: true
  5211. });
  5212. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  5213. get: function () {
  5214. return Engine._DELAYLOADSTATE_NONE;
  5215. },
  5216. enumerable: true,
  5217. configurable: true
  5218. });
  5219. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  5220. get: function () {
  5221. return Engine._DELAYLOADSTATE_LOADED;
  5222. },
  5223. enumerable: true,
  5224. configurable: true
  5225. });
  5226. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  5227. get: function () {
  5228. return Engine._DELAYLOADSTATE_LOADING;
  5229. },
  5230. enumerable: true,
  5231. configurable: true
  5232. });
  5233. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  5234. get: function () {
  5235. return Engine._DELAYLOADSTATE_NOTLOADED;
  5236. },
  5237. enumerable: true,
  5238. configurable: true
  5239. });
  5240. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  5241. get: function () {
  5242. return Engine._TEXTUREFORMAT_ALPHA;
  5243. },
  5244. enumerable: true,
  5245. configurable: true
  5246. });
  5247. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  5248. get: function () {
  5249. return Engine._TEXTUREFORMAT_LUMINANCE;
  5250. },
  5251. enumerable: true,
  5252. configurable: true
  5253. });
  5254. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  5255. get: function () {
  5256. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  5257. },
  5258. enumerable: true,
  5259. configurable: true
  5260. });
  5261. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  5262. get: function () {
  5263. return Engine._TEXTUREFORMAT_RGB;
  5264. },
  5265. enumerable: true,
  5266. configurable: true
  5267. });
  5268. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  5269. get: function () {
  5270. return Engine._TEXTUREFORMAT_RGBA;
  5271. },
  5272. enumerable: true,
  5273. configurable: true
  5274. });
  5275. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  5276. get: function () {
  5277. return Engine._TEXTURETYPE_UNSIGNED_INT;
  5278. },
  5279. enumerable: true,
  5280. configurable: true
  5281. });
  5282. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  5283. get: function () {
  5284. return Engine._TEXTURETYPE_FLOAT;
  5285. },
  5286. enumerable: true,
  5287. configurable: true
  5288. });
  5289. Object.defineProperty(Engine, "Version", {
  5290. get: function () {
  5291. return "2.3.0-alpha";
  5292. },
  5293. enumerable: true,
  5294. configurable: true
  5295. });
  5296. Engine.prototype._prepareWorkingCanvas = function () {
  5297. if (this._workingCanvas) {
  5298. return;
  5299. }
  5300. this._workingCanvas = document.createElement("canvas");
  5301. this._workingContext = this._workingCanvas.getContext("2d");
  5302. };
  5303. Engine.prototype.resetTextureCache = function () {
  5304. for (var index = 0; index < this._maxTextureChannels; index++) {
  5305. this._activeTexturesCache[index] = null;
  5306. }
  5307. };
  5308. Engine.prototype.getGlInfo = function () {
  5309. return {
  5310. vendor: this._glVendor,
  5311. renderer: this._glRenderer,
  5312. version: this._glVersion
  5313. };
  5314. };
  5315. Engine.prototype.getAspectRatio = function (camera) {
  5316. var viewport = camera.viewport;
  5317. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  5318. };
  5319. Engine.prototype.getRenderWidth = function () {
  5320. if (this._currentRenderTarget) {
  5321. return this._currentRenderTarget._width;
  5322. }
  5323. return this._renderingCanvas.width;
  5324. };
  5325. Engine.prototype.getRenderHeight = function () {
  5326. if (this._currentRenderTarget) {
  5327. return this._currentRenderTarget._height;
  5328. }
  5329. return this._renderingCanvas.height;
  5330. };
  5331. Engine.prototype.getRenderingCanvas = function () {
  5332. return this._renderingCanvas;
  5333. };
  5334. Engine.prototype.getRenderingCanvasClientRect = function () {
  5335. return this._renderingCanvas.getBoundingClientRect();
  5336. };
  5337. Engine.prototype.setHardwareScalingLevel = function (level) {
  5338. this._hardwareScalingLevel = level;
  5339. this.resize();
  5340. };
  5341. Engine.prototype.getHardwareScalingLevel = function () {
  5342. return this._hardwareScalingLevel;
  5343. };
  5344. Engine.prototype.getLoadedTexturesCache = function () {
  5345. return this._loadedTexturesCache;
  5346. };
  5347. Engine.prototype.getCaps = function () {
  5348. return this._caps;
  5349. };
  5350. Object.defineProperty(Engine.prototype, "drawCalls", {
  5351. get: function () {
  5352. return this._drawCalls;
  5353. },
  5354. enumerable: true,
  5355. configurable: true
  5356. });
  5357. // Methods
  5358. Engine.prototype.resetDrawCalls = function () {
  5359. this._drawCalls = 0;
  5360. };
  5361. Engine.prototype.setDepthFunctionToGreater = function () {
  5362. this._depthCullingState.depthFunc = this._gl.GREATER;
  5363. };
  5364. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  5365. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  5366. };
  5367. Engine.prototype.setDepthFunctionToLess = function () {
  5368. this._depthCullingState.depthFunc = this._gl.LESS;
  5369. };
  5370. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  5371. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  5372. };
  5373. /**
  5374. * stop executing a render loop function and remove it from the execution array
  5375. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  5376. */
  5377. Engine.prototype.stopRenderLoop = function (renderFunction) {
  5378. if (!renderFunction) {
  5379. this._activeRenderLoops = [];
  5380. return;
  5381. }
  5382. var index = this._activeRenderLoops.indexOf(renderFunction);
  5383. if (index >= 0) {
  5384. this._activeRenderLoops.splice(index, 1);
  5385. }
  5386. };
  5387. Engine.prototype._renderLoop = function () {
  5388. var shouldRender = true;
  5389. if (!this.renderEvenInBackground && this._windowIsBackground) {
  5390. shouldRender = false;
  5391. }
  5392. if (shouldRender) {
  5393. // Start new frame
  5394. this.beginFrame();
  5395. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  5396. var renderFunction = this._activeRenderLoops[index];
  5397. renderFunction();
  5398. }
  5399. // Present
  5400. this.endFrame();
  5401. }
  5402. if (this._activeRenderLoops.length > 0) {
  5403. // Register new frame
  5404. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5405. }
  5406. else {
  5407. this._renderingQueueLaunched = false;
  5408. }
  5409. };
  5410. /**
  5411. * Register and execute a render loop. The engine can have more than one render function.
  5412. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  5413. * @example
  5414. * engine.runRenderLoop(function () {
  5415. * scene.render()
  5416. * })
  5417. */
  5418. Engine.prototype.runRenderLoop = function (renderFunction) {
  5419. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  5420. return;
  5421. }
  5422. this._activeRenderLoops.push(renderFunction);
  5423. if (!this._renderingQueueLaunched) {
  5424. this._renderingQueueLaunched = true;
  5425. this._bindedRenderFunction = this._renderLoop.bind(this);
  5426. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5427. }
  5428. };
  5429. /**
  5430. * Toggle full screen mode.
  5431. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  5432. */
  5433. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  5434. if (this.isFullscreen) {
  5435. BABYLON.Tools.ExitFullscreen();
  5436. }
  5437. else {
  5438. this._pointerLockRequested = requestPointerLock;
  5439. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  5440. }
  5441. };
  5442. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  5443. this.applyStates();
  5444. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  5445. if (this._depthCullingState.depthMask) {
  5446. this._gl.clearDepth(1.0);
  5447. }
  5448. var mode = 0;
  5449. if (backBuffer)
  5450. mode |= this._gl.COLOR_BUFFER_BIT;
  5451. if (depthStencil && this._depthCullingState.depthMask)
  5452. mode |= this._gl.DEPTH_BUFFER_BIT;
  5453. this._gl.clear(mode);
  5454. };
  5455. /**
  5456. * Set the WebGL's viewport
  5457. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  5458. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  5459. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  5460. */
  5461. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  5462. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  5463. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  5464. var x = viewport.x || 0;
  5465. var y = viewport.y || 0;
  5466. this._cachedViewport = viewport;
  5467. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  5468. };
  5469. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  5470. this._cachedViewport = null;
  5471. this._gl.viewport(x, y, width, height);
  5472. };
  5473. Engine.prototype.beginFrame = function () {
  5474. this._measureFps();
  5475. };
  5476. Engine.prototype.endFrame = function () {
  5477. //this.flushFramebuffer();
  5478. };
  5479. /**
  5480. * resize the view according to the canvas' size.
  5481. * @example
  5482. * window.addEventListener("resize", function () {
  5483. * engine.resize();
  5484. * });
  5485. */
  5486. Engine.prototype.resize = function () {
  5487. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  5488. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  5489. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  5490. };
  5491. /**
  5492. * force a specific size of the canvas
  5493. * @param {number} width - the new canvas' width
  5494. * @param {number} height - the new canvas' height
  5495. */
  5496. Engine.prototype.setSize = function (width, height) {
  5497. this._renderingCanvas.width = width;
  5498. this._renderingCanvas.height = height;
  5499. for (var index = 0; index < this.scenes.length; index++) {
  5500. var scene = this.scenes[index];
  5501. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  5502. var cam = scene.cameras[camIndex];
  5503. cam._currentRenderId = 0;
  5504. }
  5505. }
  5506. };
  5507. Engine.prototype.bindFramebuffer = function (texture, faceIndex) {
  5508. this._currentRenderTarget = texture;
  5509. var gl = this._gl;
  5510. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  5511. if (texture.isCube) {
  5512. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  5513. }
  5514. else {
  5515. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  5516. }
  5517. this._gl.viewport(0, 0, texture._width, texture._height);
  5518. this.wipeCaches();
  5519. };
  5520. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  5521. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  5522. this._currentRenderTarget = null;
  5523. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  5524. var gl = this._gl;
  5525. gl.bindTexture(gl.TEXTURE_2D, texture);
  5526. gl.generateMipmap(gl.TEXTURE_2D);
  5527. gl.bindTexture(gl.TEXTURE_2D, null);
  5528. }
  5529. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5530. };
  5531. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  5532. if (texture.generateMipMaps) {
  5533. var gl = this._gl;
  5534. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  5535. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  5536. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  5537. }
  5538. };
  5539. Engine.prototype.flushFramebuffer = function () {
  5540. this._gl.flush();
  5541. };
  5542. Engine.prototype.restoreDefaultFramebuffer = function () {
  5543. this._currentRenderTarget = null;
  5544. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5545. this.setViewport(this._cachedViewport);
  5546. this.wipeCaches();
  5547. };
  5548. // VBOs
  5549. Engine.prototype._resetVertexBufferBinding = function () {
  5550. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  5551. this._cachedVertexBuffers = null;
  5552. };
  5553. Engine.prototype.createVertexBuffer = function (vertices) {
  5554. var vbo = this._gl.createBuffer();
  5555. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5556. if (vertices instanceof Float32Array) {
  5557. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  5558. }
  5559. else {
  5560. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  5561. }
  5562. this._resetVertexBufferBinding();
  5563. vbo.references = 1;
  5564. return vbo;
  5565. };
  5566. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  5567. var vbo = this._gl.createBuffer();
  5568. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5569. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5570. this._resetVertexBufferBinding();
  5571. vbo.references = 1;
  5572. return vbo;
  5573. };
  5574. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  5575. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5576. if (offset === undefined) {
  5577. offset = 0;
  5578. }
  5579. if (vertices instanceof Float32Array) {
  5580. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  5581. }
  5582. else {
  5583. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  5584. }
  5585. this._resetVertexBufferBinding();
  5586. };
  5587. Engine.prototype._resetIndexBufferBinding = function () {
  5588. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  5589. this._cachedIndexBuffer = null;
  5590. };
  5591. Engine.prototype.createIndexBuffer = function (indices) {
  5592. var vbo = this._gl.createBuffer();
  5593. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  5594. // Check for 32 bits indices
  5595. var arrayBuffer;
  5596. var need32Bits = false;
  5597. if (this._caps.uintIndices) {
  5598. for (var index = 0; index < indices.length; index++) {
  5599. if (indices[index] > 65535) {
  5600. need32Bits = true;
  5601. break;
  5602. }
  5603. }
  5604. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  5605. }
  5606. else {
  5607. arrayBuffer = new Uint16Array(indices);
  5608. }
  5609. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  5610. this._resetIndexBufferBinding();
  5611. vbo.references = 1;
  5612. vbo.is32Bits = need32Bits;
  5613. return vbo;
  5614. };
  5615. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  5616. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  5617. this._cachedVertexBuffers = vertexBuffer;
  5618. this._cachedEffectForVertexBuffers = effect;
  5619. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5620. var offset = 0;
  5621. for (var index = 0; index < vertexDeclaration.length; index++) {
  5622. var order = effect.getAttributeLocation(index);
  5623. if (order >= 0) {
  5624. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  5625. }
  5626. offset += vertexDeclaration[index] * 4;
  5627. }
  5628. }
  5629. if (this._cachedIndexBuffer !== indexBuffer) {
  5630. this._cachedIndexBuffer = indexBuffer;
  5631. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  5632. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  5633. }
  5634. };
  5635. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  5636. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  5637. this._cachedVertexBuffers = vertexBuffers;
  5638. this._cachedEffectForVertexBuffers = effect;
  5639. var attributes = effect.getAttributesNames();
  5640. for (var index = 0; index < attributes.length; index++) {
  5641. var order = effect.getAttributeLocation(index);
  5642. if (order >= 0) {
  5643. var vertexBuffer = vertexBuffers[attributes[index]];
  5644. if (!vertexBuffer) {
  5645. continue;
  5646. }
  5647. var stride = vertexBuffer.getStrideSize();
  5648. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  5649. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  5650. }
  5651. }
  5652. }
  5653. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  5654. this._cachedIndexBuffer = indexBuffer;
  5655. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  5656. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  5657. }
  5658. };
  5659. Engine.prototype._releaseBuffer = function (buffer) {
  5660. buffer.references--;
  5661. if (buffer.references === 0) {
  5662. this._gl.deleteBuffer(buffer);
  5663. return true;
  5664. }
  5665. return false;
  5666. };
  5667. Engine.prototype.createInstancesBuffer = function (capacity) {
  5668. var buffer = this._gl.createBuffer();
  5669. buffer.capacity = capacity;
  5670. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  5671. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5672. return buffer;
  5673. };
  5674. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  5675. this._gl.deleteBuffer(buffer);
  5676. };
  5677. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  5678. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  5679. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  5680. for (var index = 0; index < 4; index++) {
  5681. var offsetLocation = offsetLocations[index];
  5682. this._gl.enableVertexAttribArray(offsetLocation);
  5683. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  5684. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  5685. }
  5686. };
  5687. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  5688. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  5689. for (var index = 0; index < 4; index++) {
  5690. var offsetLocation = offsetLocations[index];
  5691. this._gl.disableVertexAttribArray(offsetLocation);
  5692. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  5693. }
  5694. };
  5695. Engine.prototype.applyStates = function () {
  5696. this._depthCullingState.apply(this._gl);
  5697. this._alphaState.apply(this._gl);
  5698. };
  5699. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  5700. // Apply states
  5701. this.applyStates();
  5702. this._drawCalls++;
  5703. // Render
  5704. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  5705. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  5706. if (instancesCount) {
  5707. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  5708. return;
  5709. }
  5710. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  5711. };
  5712. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  5713. // Apply states
  5714. this.applyStates();
  5715. this._drawCalls++;
  5716. if (instancesCount) {
  5717. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  5718. return;
  5719. }
  5720. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  5721. };
  5722. // Shaders
  5723. Engine.prototype._releaseEffect = function (effect) {
  5724. if (this._compiledEffects[effect._key]) {
  5725. delete this._compiledEffects[effect._key];
  5726. if (effect.getProgram()) {
  5727. this._gl.deleteProgram(effect.getProgram());
  5728. }
  5729. }
  5730. };
  5731. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  5732. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  5733. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  5734. var name = vertex + "+" + fragment + "@" + defines;
  5735. if (this._compiledEffects[name]) {
  5736. return this._compiledEffects[name];
  5737. }
  5738. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  5739. effect._key = name;
  5740. this._compiledEffects[name] = effect;
  5741. return effect;
  5742. };
  5743. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  5744. if (uniformsNames === void 0) { uniformsNames = []; }
  5745. if (samplers === void 0) { samplers = []; }
  5746. if (defines === void 0) { defines = ""; }
  5747. return this.createEffect({
  5748. vertex: "particles",
  5749. fragmentElement: fragmentName
  5750. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  5751. };
  5752. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  5753. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  5754. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  5755. var shaderProgram = this._gl.createProgram();
  5756. this._gl.attachShader(shaderProgram, vertexShader);
  5757. this._gl.attachShader(shaderProgram, fragmentShader);
  5758. this._gl.linkProgram(shaderProgram);
  5759. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  5760. if (!linked) {
  5761. var error = this._gl.getProgramInfoLog(shaderProgram);
  5762. if (error) {
  5763. throw new Error(error);
  5764. }
  5765. }
  5766. this._gl.deleteShader(vertexShader);
  5767. this._gl.deleteShader(fragmentShader);
  5768. return shaderProgram;
  5769. };
  5770. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  5771. var results = [];
  5772. for (var index = 0; index < uniformsNames.length; index++) {
  5773. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  5774. }
  5775. return results;
  5776. };
  5777. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  5778. var results = [];
  5779. for (var index = 0; index < attributesNames.length; index++) {
  5780. try {
  5781. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  5782. }
  5783. catch (e) {
  5784. results.push(-1);
  5785. }
  5786. }
  5787. return results;
  5788. };
  5789. Engine.prototype.enableEffect = function (effect) {
  5790. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  5791. if (effect && effect.onBind) {
  5792. effect.onBind(effect);
  5793. }
  5794. return;
  5795. }
  5796. this._vertexAttribArrays = this._vertexAttribArrays || [];
  5797. // Use program
  5798. this._gl.useProgram(effect.getProgram());
  5799. for (var i in this._vertexAttribArrays) {
  5800. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  5801. continue;
  5802. }
  5803. this._vertexAttribArrays[i] = false;
  5804. this._gl.disableVertexAttribArray(i);
  5805. }
  5806. var attributesCount = effect.getAttributesCount();
  5807. for (var index = 0; index < attributesCount; index++) {
  5808. // Attributes
  5809. var order = effect.getAttributeLocation(index);
  5810. if (order >= 0) {
  5811. this._vertexAttribArrays[order] = true;
  5812. this._gl.enableVertexAttribArray(order);
  5813. }
  5814. }
  5815. this._currentEffect = effect;
  5816. if (effect.onBind) {
  5817. effect.onBind(effect);
  5818. }
  5819. };
  5820. Engine.prototype.setArray = function (uniform, array) {
  5821. if (!uniform)
  5822. return;
  5823. this._gl.uniform1fv(uniform, array);
  5824. };
  5825. Engine.prototype.setArray2 = function (uniform, array) {
  5826. if (!uniform || array.length % 2 !== 0)
  5827. return;
  5828. this._gl.uniform2fv(uniform, array);
  5829. };
  5830. Engine.prototype.setArray3 = function (uniform, array) {
  5831. if (!uniform || array.length % 3 !== 0)
  5832. return;
  5833. this._gl.uniform3fv(uniform, array);
  5834. };
  5835. Engine.prototype.setArray4 = function (uniform, array) {
  5836. if (!uniform || array.length % 4 !== 0)
  5837. return;
  5838. this._gl.uniform4fv(uniform, array);
  5839. };
  5840. Engine.prototype.setMatrices = function (uniform, matrices) {
  5841. if (!uniform)
  5842. return;
  5843. this._gl.uniformMatrix4fv(uniform, false, matrices);
  5844. };
  5845. Engine.prototype.setMatrix = function (uniform, matrix) {
  5846. if (!uniform)
  5847. return;
  5848. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  5849. };
  5850. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  5851. if (!uniform)
  5852. return;
  5853. this._gl.uniformMatrix3fv(uniform, false, matrix);
  5854. };
  5855. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  5856. if (!uniform)
  5857. return;
  5858. this._gl.uniformMatrix2fv(uniform, false, matrix);
  5859. };
  5860. Engine.prototype.setFloat = function (uniform, value) {
  5861. if (!uniform)
  5862. return;
  5863. this._gl.uniform1f(uniform, value);
  5864. };
  5865. Engine.prototype.setFloat2 = function (uniform, x, y) {
  5866. if (!uniform)
  5867. return;
  5868. this._gl.uniform2f(uniform, x, y);
  5869. };
  5870. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  5871. if (!uniform)
  5872. return;
  5873. this._gl.uniform3f(uniform, x, y, z);
  5874. };
  5875. Engine.prototype.setBool = function (uniform, bool) {
  5876. if (!uniform)
  5877. return;
  5878. this._gl.uniform1i(uniform, bool);
  5879. };
  5880. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  5881. if (!uniform)
  5882. return;
  5883. this._gl.uniform4f(uniform, x, y, z, w);
  5884. };
  5885. Engine.prototype.setColor3 = function (uniform, color3) {
  5886. if (!uniform)
  5887. return;
  5888. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  5889. };
  5890. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  5891. if (!uniform)
  5892. return;
  5893. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  5894. };
  5895. // States
  5896. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  5897. if (zOffset === void 0) { zOffset = 0; }
  5898. if (reverseSide === void 0) { reverseSide = false; }
  5899. // Culling
  5900. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  5901. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  5902. var cullFace = this.cullBackFaces ? showSide : hideSide;
  5903. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  5904. if (culling) {
  5905. this._depthCullingState.cullFace = cullFace;
  5906. this._depthCullingState.cull = true;
  5907. }
  5908. else {
  5909. this._depthCullingState.cull = false;
  5910. }
  5911. }
  5912. // Z offset
  5913. this._depthCullingState.zOffset = zOffset;
  5914. };
  5915. Engine.prototype.setDepthBuffer = function (enable) {
  5916. this._depthCullingState.depthTest = enable;
  5917. };
  5918. Engine.prototype.getDepthWrite = function () {
  5919. return this._depthCullingState.depthMask;
  5920. };
  5921. Engine.prototype.setDepthWrite = function (enable) {
  5922. this._depthCullingState.depthMask = enable;
  5923. };
  5924. Engine.prototype.setColorWrite = function (enable) {
  5925. this._gl.colorMask(enable, enable, enable, enable);
  5926. };
  5927. Engine.prototype.setAlphaMode = function (mode) {
  5928. if (this._alphaMode === mode) {
  5929. return;
  5930. }
  5931. switch (mode) {
  5932. case Engine.ALPHA_DISABLE:
  5933. this.setDepthWrite(true);
  5934. this._alphaState.alphaBlend = false;
  5935. break;
  5936. case Engine.ALPHA_COMBINE:
  5937. this.setDepthWrite(false);
  5938. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  5939. this._alphaState.alphaBlend = true;
  5940. break;
  5941. case Engine.ALPHA_ONEONE:
  5942. this.setDepthWrite(false);
  5943. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  5944. this._alphaState.alphaBlend = true;
  5945. break;
  5946. case Engine.ALPHA_ADD:
  5947. this.setDepthWrite(false);
  5948. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  5949. this._alphaState.alphaBlend = true;
  5950. break;
  5951. case Engine.ALPHA_SUBTRACT:
  5952. this.setDepthWrite(false);
  5953. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  5954. this._alphaState.alphaBlend = true;
  5955. break;
  5956. case Engine.ALPHA_MULTIPLY:
  5957. this.setDepthWrite(false);
  5958. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  5959. this._alphaState.alphaBlend = true;
  5960. break;
  5961. case Engine.ALPHA_MAXIMIZED:
  5962. this.setDepthWrite(false);
  5963. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  5964. this._alphaState.alphaBlend = true;
  5965. break;
  5966. }
  5967. this._alphaMode = mode;
  5968. };
  5969. Engine.prototype.getAlphaMode = function () {
  5970. return this._alphaMode;
  5971. };
  5972. Engine.prototype.setAlphaTesting = function (enable) {
  5973. this._alphaTest = enable;
  5974. };
  5975. Engine.prototype.getAlphaTesting = function () {
  5976. return this._alphaTest;
  5977. };
  5978. // Textures
  5979. Engine.prototype.wipeCaches = function () {
  5980. this.resetTextureCache();
  5981. this._currentEffect = null;
  5982. this._depthCullingState.reset();
  5983. this._alphaState.reset();
  5984. this._cachedVertexBuffers = null;
  5985. this._cachedIndexBuffer = null;
  5986. this._cachedEffectForVertexBuffers = null;
  5987. };
  5988. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  5989. var gl = this._gl;
  5990. gl.bindTexture(gl.TEXTURE_2D, texture);
  5991. var magFilter = gl.NEAREST;
  5992. var minFilter = gl.NEAREST;
  5993. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  5994. magFilter = gl.LINEAR;
  5995. minFilter = gl.LINEAR;
  5996. }
  5997. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  5998. magFilter = gl.LINEAR;
  5999. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6000. }
  6001. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  6002. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  6003. gl.bindTexture(gl.TEXTURE_2D, null);
  6004. texture.samplingMode = samplingMode;
  6005. };
  6006. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  6007. var _this = this;
  6008. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6009. if (onLoad === void 0) { onLoad = null; }
  6010. if (onError === void 0) { onError = null; }
  6011. if (buffer === void 0) { buffer = null; }
  6012. var texture = this._gl.createTexture();
  6013. var extension;
  6014. var fromData = false;
  6015. if (url.substr(0, 5) === "data:") {
  6016. fromData = true;
  6017. }
  6018. if (!fromData)
  6019. extension = url.substr(url.length - 4, 4).toLowerCase();
  6020. else {
  6021. var oldUrl = url;
  6022. fromData = oldUrl.split(':');
  6023. url = oldUrl;
  6024. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  6025. }
  6026. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6027. var isTGA = (extension === ".tga");
  6028. scene._addPendingData(texture);
  6029. texture.url = url;
  6030. texture.noMipmap = noMipmap;
  6031. texture.references = 1;
  6032. texture.samplingMode = samplingMode;
  6033. this._loadedTexturesCache.push(texture);
  6034. var onerror = function () {
  6035. scene._removePendingData(texture);
  6036. if (onError) {
  6037. onError();
  6038. }
  6039. };
  6040. var callback;
  6041. if (isTGA) {
  6042. callback = function (arrayBuffer) {
  6043. var data = new Uint8Array(arrayBuffer);
  6044. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  6045. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  6046. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  6047. if (onLoad) {
  6048. onLoad();
  6049. }
  6050. }, samplingMode);
  6051. };
  6052. if (!(fromData instanceof Array))
  6053. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  6054. callback(arrayBuffer);
  6055. }, onerror, scene.database, true);
  6056. else
  6057. callback(buffer);
  6058. }
  6059. else if (isDDS) {
  6060. callback = function (data) {
  6061. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6062. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  6063. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  6064. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  6065. if (onLoad) {
  6066. onLoad();
  6067. }
  6068. }, samplingMode);
  6069. };
  6070. if (!(fromData instanceof Array))
  6071. BABYLON.Tools.LoadFile(url, function (data) {
  6072. callback(data);
  6073. }, onerror, scene.database, true);
  6074. else
  6075. callback(buffer);
  6076. }
  6077. else {
  6078. var onload = function (img) {
  6079. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  6080. var isPot = (img.width === potWidth && img.height === potHeight);
  6081. if (!isPot) {
  6082. _this._prepareWorkingCanvas();
  6083. _this._workingCanvas.width = potWidth;
  6084. _this._workingCanvas.height = potHeight;
  6085. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6086. _this._workingContext.imageSmoothingEnabled = false;
  6087. _this._workingContext.mozImageSmoothingEnabled = false;
  6088. _this._workingContext.oImageSmoothingEnabled = false;
  6089. _this._workingContext.webkitImageSmoothingEnabled = false;
  6090. _this._workingContext.msImageSmoothingEnabled = false;
  6091. }
  6092. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  6093. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6094. _this._workingContext.imageSmoothingEnabled = true;
  6095. _this._workingContext.mozImageSmoothingEnabled = true;
  6096. _this._workingContext.oImageSmoothingEnabled = true;
  6097. _this._workingContext.webkitImageSmoothingEnabled = true;
  6098. _this._workingContext.msImageSmoothingEnabled = true;
  6099. }
  6100. }
  6101. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  6102. if (onLoad) {
  6103. onLoad();
  6104. }
  6105. }, samplingMode);
  6106. };
  6107. if (!(fromData instanceof Array))
  6108. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6109. else
  6110. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  6111. }
  6112. return texture;
  6113. };
  6114. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  6115. if (compression === void 0) { compression = null; }
  6116. var internalFormat = this._gl.RGBA;
  6117. switch (format) {
  6118. case Engine.TEXTUREFORMAT_ALPHA:
  6119. internalFormat = this._gl.ALPHA;
  6120. break;
  6121. case Engine.TEXTUREFORMAT_LUMINANCE:
  6122. internalFormat = this._gl.LUMINANCE;
  6123. break;
  6124. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  6125. internalFormat = this._gl.LUMINANCE_ALPHA;
  6126. break;
  6127. case Engine.TEXTUREFORMAT_RGB:
  6128. internalFormat = this._gl.RGB;
  6129. break;
  6130. case Engine.TEXTUREFORMAT_RGBA:
  6131. internalFormat = this._gl.RGBA;
  6132. break;
  6133. }
  6134. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6135. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6136. if (compression) {
  6137. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  6138. }
  6139. else {
  6140. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  6141. }
  6142. if (texture.generateMipMaps) {
  6143. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6144. }
  6145. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6146. this.resetTextureCache();
  6147. texture.isReady = true;
  6148. };
  6149. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  6150. if (compression === void 0) { compression = null; }
  6151. var texture = this._gl.createTexture();
  6152. texture._baseWidth = width;
  6153. texture._baseHeight = height;
  6154. texture._width = width;
  6155. texture._height = height;
  6156. texture.references = 1;
  6157. this.updateRawTexture(texture, data, format, invertY, compression);
  6158. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6159. // Filters
  6160. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  6161. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6162. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6163. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6164. texture.samplingMode = samplingMode;
  6165. this._loadedTexturesCache.push(texture);
  6166. return texture;
  6167. };
  6168. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode, forceExponantOfTwo) {
  6169. if (forceExponantOfTwo === void 0) { forceExponantOfTwo = true; }
  6170. var texture = this._gl.createTexture();
  6171. texture._baseWidth = width;
  6172. texture._baseHeight = height;
  6173. if (forceExponantOfTwo) {
  6174. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  6175. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  6176. }
  6177. this.resetTextureCache();
  6178. texture._width = width;
  6179. texture._height = height;
  6180. texture.isReady = false;
  6181. texture.generateMipMaps = generateMipMaps;
  6182. texture.references = 1;
  6183. texture.samplingMode = samplingMode;
  6184. this.updateTextureSamplingMode(samplingMode, texture);
  6185. this._loadedTexturesCache.push(texture);
  6186. return texture;
  6187. };
  6188. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  6189. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  6190. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6191. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6192. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6193. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6194. };
  6195. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  6196. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6197. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  6198. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  6199. if (texture.generateMipMaps) {
  6200. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6201. }
  6202. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6203. this.resetTextureCache();
  6204. texture.isReady = true;
  6205. };
  6206. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  6207. if (texture._isDisabled) {
  6208. return;
  6209. }
  6210. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6211. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  6212. try {
  6213. // Testing video texture support
  6214. if (this._videoTextureSupported === undefined) {
  6215. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6216. if (this._gl.getError() !== 0) {
  6217. this._videoTextureSupported = false;
  6218. }
  6219. else {
  6220. this._videoTextureSupported = true;
  6221. }
  6222. }
  6223. // Copy video through the current working canvas if video texture is not supported
  6224. if (!this._videoTextureSupported) {
  6225. if (!texture._workingCanvas) {
  6226. texture._workingCanvas = document.createElement("canvas");
  6227. texture._workingContext = texture._workingCanvas.getContext("2d");
  6228. texture._workingCanvas.width = texture._width;
  6229. texture._workingCanvas.height = texture._height;
  6230. }
  6231. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  6232. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  6233. }
  6234. else {
  6235. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6236. }
  6237. if (texture.generateMipMaps) {
  6238. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6239. }
  6240. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6241. this.resetTextureCache();
  6242. texture.isReady = true;
  6243. }
  6244. catch (ex) {
  6245. // Something unexpected
  6246. // Let's disable the texture
  6247. texture._isDisabled = true;
  6248. }
  6249. };
  6250. Engine.prototype.createRenderTargetTexture = function (size, options) {
  6251. // old version had a "generateMipMaps" arg instead of options.
  6252. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  6253. // in the same way, generateDepthBuffer is defaulted to true
  6254. var generateMipMaps = false;
  6255. var generateDepthBuffer = true;
  6256. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6257. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6258. if (options !== undefined) {
  6259. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6260. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  6261. type = options.type === undefined ? type : options.type;
  6262. if (options.samplingMode !== undefined) {
  6263. samplingMode = options.samplingMode;
  6264. }
  6265. if (type === Engine.TEXTURETYPE_FLOAT) {
  6266. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  6267. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  6268. }
  6269. }
  6270. var gl = this._gl;
  6271. var texture = gl.createTexture();
  6272. gl.bindTexture(gl.TEXTURE_2D, texture);
  6273. var width = size.width || size;
  6274. var height = size.height || size;
  6275. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6276. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  6277. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6278. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  6279. }
  6280. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6281. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6282. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6283. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6284. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  6285. var depthBuffer;
  6286. // Create the depth buffer
  6287. if (generateDepthBuffer) {
  6288. depthBuffer = gl.createRenderbuffer();
  6289. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6290. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  6291. }
  6292. // Create the framebuffer
  6293. var framebuffer = gl.createFramebuffer();
  6294. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6295. if (generateDepthBuffer) {
  6296. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6297. }
  6298. if (generateMipMaps) {
  6299. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6300. }
  6301. // Unbind
  6302. gl.bindTexture(gl.TEXTURE_2D, null);
  6303. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6304. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6305. texture._framebuffer = framebuffer;
  6306. if (generateDepthBuffer) {
  6307. texture._depthBuffer = depthBuffer;
  6308. }
  6309. texture._width = width;
  6310. texture._height = height;
  6311. texture.isReady = true;
  6312. texture.generateMipMaps = generateMipMaps;
  6313. texture.references = 1;
  6314. texture.samplingMode = samplingMode;
  6315. this.resetTextureCache();
  6316. this._loadedTexturesCache.push(texture);
  6317. return texture;
  6318. };
  6319. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  6320. var gl = this._gl;
  6321. var texture = gl.createTexture();
  6322. var generateMipMaps = true;
  6323. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6324. if (options !== undefined) {
  6325. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6326. if (options.samplingMode !== undefined) {
  6327. samplingMode = options.samplingMode;
  6328. }
  6329. }
  6330. texture.isCube = true;
  6331. texture.references = 1;
  6332. texture.generateMipMaps = generateMipMaps;
  6333. texture.references = 1;
  6334. texture.samplingMode = samplingMode;
  6335. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6336. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6337. for (var face = 0; face < 6; face++) {
  6338. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  6339. }
  6340. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  6341. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  6342. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6343. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6344. // Create the depth buffer
  6345. var depthBuffer = gl.createRenderbuffer();
  6346. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6347. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  6348. // Create the framebuffer
  6349. var framebuffer = gl.createFramebuffer();
  6350. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6351. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6352. // Unbind
  6353. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6354. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6355. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6356. texture._framebuffer = framebuffer;
  6357. texture._depthBuffer = depthBuffer;
  6358. this.resetTextureCache();
  6359. texture._width = size;
  6360. texture._height = size;
  6361. texture.isReady = true;
  6362. return texture;
  6363. };
  6364. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  6365. var _this = this;
  6366. var gl = this._gl;
  6367. var texture = gl.createTexture();
  6368. texture.isCube = true;
  6369. texture.url = rootUrl;
  6370. texture.references = 1;
  6371. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  6372. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6373. if (isDDS) {
  6374. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  6375. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6376. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  6377. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6378. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  6379. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  6380. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  6381. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6382. }
  6383. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6384. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  6385. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6386. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6387. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6388. _this.resetTextureCache();
  6389. texture._width = info.width;
  6390. texture._height = info.height;
  6391. texture.isReady = true;
  6392. }, null, null, true);
  6393. }
  6394. else {
  6395. cascadeLoad(rootUrl, scene, function (imgs) {
  6396. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  6397. var height = width;
  6398. _this._prepareWorkingCanvas();
  6399. _this._workingCanvas.width = width;
  6400. _this._workingCanvas.height = height;
  6401. var faces = [
  6402. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6403. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6404. ];
  6405. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6406. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6407. for (var index = 0; index < faces.length; index++) {
  6408. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  6409. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  6410. }
  6411. if (!noMipmap) {
  6412. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6413. }
  6414. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6415. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6416. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6417. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6418. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6419. _this.resetTextureCache();
  6420. texture._width = width;
  6421. texture._height = height;
  6422. texture.isReady = true;
  6423. }, extensions);
  6424. }
  6425. return texture;
  6426. };
  6427. Engine.prototype._releaseTexture = function (texture) {
  6428. var gl = this._gl;
  6429. if (texture._framebuffer) {
  6430. gl.deleteFramebuffer(texture._framebuffer);
  6431. }
  6432. if (texture._depthBuffer) {
  6433. gl.deleteRenderbuffer(texture._depthBuffer);
  6434. }
  6435. gl.deleteTexture(texture);
  6436. // Unbind channels
  6437. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  6438. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6439. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6440. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6441. this._activeTexturesCache[channel] = null;
  6442. }
  6443. var index = this._loadedTexturesCache.indexOf(texture);
  6444. if (index !== -1) {
  6445. this._loadedTexturesCache.splice(index, 1);
  6446. }
  6447. };
  6448. Engine.prototype.bindSamplers = function (effect) {
  6449. this._gl.useProgram(effect.getProgram());
  6450. var samplers = effect.getSamplers();
  6451. for (var index = 0; index < samplers.length; index++) {
  6452. var uniform = effect.getUniform(samplers[index]);
  6453. this._gl.uniform1i(uniform, index);
  6454. }
  6455. this._currentEffect = null;
  6456. };
  6457. Engine.prototype._bindTexture = function (channel, texture) {
  6458. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6459. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6460. this._activeTexturesCache[channel] = null;
  6461. };
  6462. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  6463. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  6464. };
  6465. Engine.prototype.setTexture = function (channel, texture) {
  6466. if (channel < 0) {
  6467. return;
  6468. }
  6469. // Not ready?
  6470. if (!texture || !texture.isReady()) {
  6471. if (this._activeTexturesCache[channel] != null) {
  6472. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6473. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6474. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6475. this._activeTexturesCache[channel] = null;
  6476. }
  6477. return;
  6478. }
  6479. // Video
  6480. if (texture instanceof BABYLON.VideoTexture) {
  6481. if (texture.update()) {
  6482. this._activeTexturesCache[channel] = null;
  6483. }
  6484. }
  6485. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  6486. texture.delayLoad();
  6487. return;
  6488. }
  6489. if (this._activeTexturesCache[channel] === texture) {
  6490. return;
  6491. }
  6492. this._activeTexturesCache[channel] = texture;
  6493. var internalTexture = texture.getInternalTexture();
  6494. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6495. if (internalTexture.isCube) {
  6496. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  6497. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  6498. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  6499. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  6500. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  6501. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  6502. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  6503. }
  6504. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  6505. }
  6506. else {
  6507. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  6508. if (internalTexture._cachedWrapU !== texture.wrapU) {
  6509. internalTexture._cachedWrapU = texture.wrapU;
  6510. switch (texture.wrapU) {
  6511. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6512. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  6513. break;
  6514. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6515. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  6516. break;
  6517. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6518. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  6519. break;
  6520. }
  6521. }
  6522. if (internalTexture._cachedWrapV !== texture.wrapV) {
  6523. internalTexture._cachedWrapV = texture.wrapV;
  6524. switch (texture.wrapV) {
  6525. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6526. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  6527. break;
  6528. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6529. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  6530. break;
  6531. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6532. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  6533. break;
  6534. }
  6535. }
  6536. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  6537. }
  6538. };
  6539. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  6540. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  6541. var value = texture.anisotropicFilteringLevel;
  6542. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6543. value = 1;
  6544. }
  6545. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  6546. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  6547. texture._cachedAnisotropicFilteringLevel = value;
  6548. }
  6549. };
  6550. Engine.prototype.readPixels = function (x, y, width, height) {
  6551. var data = new Uint8Array(height * width * 4);
  6552. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  6553. return data;
  6554. };
  6555. Engine.prototype.releaseInternalTexture = function (texture) {
  6556. if (!texture) {
  6557. return;
  6558. }
  6559. texture.references--;
  6560. // Final reference ?
  6561. if (texture.references === 0) {
  6562. var texturesCache = this.getLoadedTexturesCache();
  6563. var index = texturesCache.indexOf(texture);
  6564. if (index > -1) {
  6565. texturesCache.splice(index, 1);
  6566. }
  6567. this._releaseTexture(texture);
  6568. }
  6569. };
  6570. // Dispose
  6571. Engine.prototype.dispose = function () {
  6572. this.hideLoadingUI();
  6573. this.stopRenderLoop();
  6574. // Release scenes
  6575. while (this.scenes.length) {
  6576. this.scenes[0].dispose();
  6577. }
  6578. // Release audio engine
  6579. Engine.audioEngine.dispose();
  6580. // Release effects
  6581. for (var name in this._compiledEffects) {
  6582. this._gl.deleteProgram(this._compiledEffects[name]._program);
  6583. }
  6584. // Unbind
  6585. for (var i in this._vertexAttribArrays) {
  6586. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  6587. continue;
  6588. }
  6589. this._gl.disableVertexAttribArray(i);
  6590. }
  6591. this._gl = null;
  6592. // Events
  6593. window.removeEventListener("blur", this._onBlur);
  6594. window.removeEventListener("focus", this._onFocus);
  6595. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  6596. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  6597. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  6598. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  6599. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  6600. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  6601. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  6602. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  6603. };
  6604. // Loading screen
  6605. Engine.prototype.displayLoadingUI = function () {
  6606. this._loadingScreen.displayLoadingUI();
  6607. };
  6608. Engine.prototype.hideLoadingUI = function () {
  6609. this._loadingScreen.hideLoadingUI();
  6610. };
  6611. Object.defineProperty(Engine.prototype, "loadingScreen", {
  6612. get: function () {
  6613. return this._loadingScreen;
  6614. },
  6615. set: function (loadingScreen) {
  6616. this._loadingScreen = loadingScreen;
  6617. },
  6618. enumerable: true,
  6619. configurable: true
  6620. });
  6621. Object.defineProperty(Engine.prototype, "loadingUIText", {
  6622. set: function (text) {
  6623. this._loadingScreen.loadingUIText = text;
  6624. },
  6625. enumerable: true,
  6626. configurable: true
  6627. });
  6628. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  6629. set: function (color) {
  6630. this._loadingScreen.loadingUIBackgroundColor = color;
  6631. },
  6632. enumerable: true,
  6633. configurable: true
  6634. });
  6635. // FPS
  6636. Engine.prototype.getFps = function () {
  6637. return this.fps;
  6638. };
  6639. Engine.prototype.getDeltaTime = function () {
  6640. return this.deltaTime;
  6641. };
  6642. Engine.prototype._measureFps = function () {
  6643. this.previousFramesDuration.push(BABYLON.Tools.Now);
  6644. var length = this.previousFramesDuration.length;
  6645. if (length >= 2) {
  6646. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  6647. }
  6648. if (length >= this.fpsRange) {
  6649. if (length > this.fpsRange) {
  6650. this.previousFramesDuration.splice(0, 1);
  6651. length = this.previousFramesDuration.length;
  6652. }
  6653. var sum = 0;
  6654. for (var id = 0; id < length - 1; id++) {
  6655. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  6656. }
  6657. this.fps = 1000.0 / (sum / (length - 1));
  6658. }
  6659. };
  6660. // Statics
  6661. Engine.isSupported = function () {
  6662. try {
  6663. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  6664. if (navigator.isCocoonJS) {
  6665. return true;
  6666. }
  6667. var tempcanvas = document.createElement("canvas");
  6668. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  6669. return gl != null && !!window.WebGLRenderingContext;
  6670. }
  6671. catch (e) {
  6672. return false;
  6673. }
  6674. };
  6675. // Const statics
  6676. Engine._ALPHA_DISABLE = 0;
  6677. Engine._ALPHA_ADD = 1;
  6678. Engine._ALPHA_COMBINE = 2;
  6679. Engine._ALPHA_SUBTRACT = 3;
  6680. Engine._ALPHA_MULTIPLY = 4;
  6681. Engine._ALPHA_MAXIMIZED = 5;
  6682. Engine._ALPHA_ONEONE = 6;
  6683. Engine._DELAYLOADSTATE_NONE = 0;
  6684. Engine._DELAYLOADSTATE_LOADED = 1;
  6685. Engine._DELAYLOADSTATE_LOADING = 2;
  6686. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  6687. Engine._TEXTUREFORMAT_ALPHA = 0;
  6688. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  6689. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  6690. Engine._TEXTUREFORMAT_RGB = 4;
  6691. Engine._TEXTUREFORMAT_RGBA = 5;
  6692. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  6693. Engine._TEXTURETYPE_FLOAT = 1;
  6694. // Updatable statics so stick with vars here
  6695. Engine.Epsilon = 0.001;
  6696. Engine.CollisionsEpsilon = 0.001;
  6697. Engine.CodeRepository = "src/";
  6698. Engine.ShadersRepository = "src/Shaders/";
  6699. return Engine;
  6700. })();
  6701. BABYLON.Engine = Engine;
  6702. })(BABYLON || (BABYLON = {}));
  6703. var BABYLON;
  6704. (function (BABYLON) {
  6705. /**
  6706. * Node is the basic class for all scene objects (Mesh, Light Camera).
  6707. */
  6708. var Node = (function () {
  6709. /**
  6710. * @constructor
  6711. * @param {string} name - the name and id to be given to this node
  6712. * @param {BABYLON.Scene} the scene this node will be added to
  6713. */
  6714. function Node(name, scene) {
  6715. this.state = "";
  6716. this.animations = new Array();
  6717. this._childrenFlag = -1;
  6718. this._isEnabled = true;
  6719. this._isReady = true;
  6720. this._currentRenderId = -1;
  6721. this._parentRenderId = -1;
  6722. this.name = name;
  6723. this.id = name;
  6724. this._scene = scene;
  6725. this._initCache();
  6726. }
  6727. Node.prototype.getScene = function () {
  6728. return this._scene;
  6729. };
  6730. Node.prototype.getEngine = function () {
  6731. return this._scene.getEngine();
  6732. };
  6733. // override it in derived class
  6734. Node.prototype.getWorldMatrix = function () {
  6735. return BABYLON.Matrix.Identity();
  6736. };
  6737. // override it in derived class if you add new variables to the cache
  6738. // and call the parent class method
  6739. Node.prototype._initCache = function () {
  6740. this._cache = {};
  6741. this._cache.parent = undefined;
  6742. };
  6743. Node.prototype.updateCache = function (force) {
  6744. if (!force && this.isSynchronized())
  6745. return;
  6746. this._cache.parent = this.parent;
  6747. this._updateCache();
  6748. };
  6749. // override it in derived class if you add new variables to the cache
  6750. // and call the parent class method if !ignoreParentClass
  6751. Node.prototype._updateCache = function (ignoreParentClass) {
  6752. };
  6753. // override it in derived class if you add new variables to the cache
  6754. Node.prototype._isSynchronized = function () {
  6755. return true;
  6756. };
  6757. Node.prototype._markSyncedWithParent = function () {
  6758. this._parentRenderId = this.parent._currentRenderId;
  6759. };
  6760. Node.prototype.isSynchronizedWithParent = function () {
  6761. if (!this.parent) {
  6762. return true;
  6763. }
  6764. if (this._parentRenderId !== this.parent._currentRenderId) {
  6765. return false;
  6766. }
  6767. return this.parent.isSynchronized();
  6768. };
  6769. Node.prototype.isSynchronized = function (updateCache) {
  6770. var check = this.hasNewParent();
  6771. check = check || !this.isSynchronizedWithParent();
  6772. check = check || !this._isSynchronized();
  6773. if (updateCache)
  6774. this.updateCache(true);
  6775. return !check;
  6776. };
  6777. Node.prototype.hasNewParent = function (update) {
  6778. if (this._cache.parent === this.parent)
  6779. return false;
  6780. if (update)
  6781. this._cache.parent = this.parent;
  6782. return true;
  6783. };
  6784. /**
  6785. * Is this node ready to be used/rendered
  6786. * @return {boolean} is it ready
  6787. */
  6788. Node.prototype.isReady = function () {
  6789. return this._isReady;
  6790. };
  6791. /**
  6792. * Is this node enabled.
  6793. * If the node has a parent and is enabled, the parent will be inspected as well.
  6794. * @return {boolean} whether this node (and its parent) is enabled.
  6795. * @see setEnabled
  6796. */
  6797. Node.prototype.isEnabled = function () {
  6798. if (!this._isEnabled) {
  6799. return false;
  6800. }
  6801. if (this.parent) {
  6802. return this.parent.isEnabled();
  6803. }
  6804. return true;
  6805. };
  6806. /**
  6807. * Set the enabled state of this node.
  6808. * @param {boolean} value - the new enabled state
  6809. * @see isEnabled
  6810. */
  6811. Node.prototype.setEnabled = function (value) {
  6812. this._isEnabled = value;
  6813. };
  6814. /**
  6815. * Is this node a descendant of the given node.
  6816. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  6817. * @param {BABYLON.Node} ancestor - The parent node to inspect
  6818. * @see parent
  6819. */
  6820. Node.prototype.isDescendantOf = function (ancestor) {
  6821. if (this.parent) {
  6822. if (this.parent === ancestor) {
  6823. return true;
  6824. }
  6825. return this.parent.isDescendantOf(ancestor);
  6826. }
  6827. return false;
  6828. };
  6829. Node.prototype._getDescendants = function (list, results) {
  6830. for (var index = 0; index < list.length; index++) {
  6831. var item = list[index];
  6832. if (item.isDescendantOf(this)) {
  6833. results.push(item);
  6834. }
  6835. }
  6836. };
  6837. /**
  6838. * Will return all nodes that have this node as parent.
  6839. * @return {BABYLON.Node[]} all children nodes of all types.
  6840. */
  6841. Node.prototype.getDescendants = function () {
  6842. var results = [];
  6843. this._getDescendants(this._scene.meshes, results);
  6844. this._getDescendants(this._scene.lights, results);
  6845. this._getDescendants(this._scene.cameras, results);
  6846. return results;
  6847. };
  6848. Node.prototype._setReady = function (state) {
  6849. if (state == this._isReady) {
  6850. return;
  6851. }
  6852. if (!state) {
  6853. this._isReady = false;
  6854. return;
  6855. }
  6856. this._isReady = true;
  6857. if (this.onReady) {
  6858. this.onReady(this);
  6859. }
  6860. };
  6861. return Node;
  6862. })();
  6863. BABYLON.Node = Node;
  6864. })(BABYLON || (BABYLON = {}));
  6865. var BABYLON;
  6866. (function (BABYLON) {
  6867. var FilesInput = (function () {
  6868. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  6869. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  6870. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  6871. this._engine = p_engine;
  6872. this._canvas = p_canvas;
  6873. this._currentScene = p_scene;
  6874. this._sceneLoadedCallback = p_sceneLoadedCallback;
  6875. this._progressCallback = p_progressCallback;
  6876. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  6877. this._textureLoadingCallback = p_textureLoadingCallback;
  6878. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  6879. }
  6880. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  6881. var _this = this;
  6882. if (p_elementToMonitor) {
  6883. this._elementToMonitor = p_elementToMonitor;
  6884. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  6885. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  6886. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  6887. }
  6888. };
  6889. FilesInput.prototype.renderFunction = function () {
  6890. if (this._additionnalRenderLoopLogicCallback) {
  6891. this._additionnalRenderLoopLogicCallback();
  6892. }
  6893. if (this._currentScene) {
  6894. if (this._textureLoadingCallback) {
  6895. var remaining = this._currentScene.getWaitingItemsCount();
  6896. if (remaining > 0) {
  6897. this._textureLoadingCallback(remaining);
  6898. }
  6899. }
  6900. this._currentScene.render();
  6901. }
  6902. };
  6903. FilesInput.prototype.drag = function (e) {
  6904. e.stopPropagation();
  6905. e.preventDefault();
  6906. };
  6907. FilesInput.prototype.drop = function (eventDrop) {
  6908. eventDrop.stopPropagation();
  6909. eventDrop.preventDefault();
  6910. this.loadFiles(eventDrop);
  6911. };
  6912. FilesInput.prototype.loadFiles = function (event) {
  6913. if (this._startingProcessingFilesCallback)
  6914. this._startingProcessingFilesCallback();
  6915. // Handling data transfer via drag'n'drop
  6916. if (event && event.dataTransfer && event.dataTransfer.files) {
  6917. this._filesToLoad = event.dataTransfer.files;
  6918. }
  6919. // Handling files from input files
  6920. if (event && event.target && event.target.files) {
  6921. this._filesToLoad = event.target.files;
  6922. }
  6923. if (this._filesToLoad && this._filesToLoad.length > 0) {
  6924. for (var i = 0; i < this._filesToLoad.length; i++) {
  6925. switch (this._filesToLoad[i].type) {
  6926. case "image/jpeg":
  6927. case "image/png":
  6928. case "image/bmp":
  6929. FilesInput.FilesTextures[this._filesToLoad[i].name] = this._filesToLoad[i];
  6930. break;
  6931. case "image/targa":
  6932. case "image/vnd.ms-dds":
  6933. case "audio/wav":
  6934. case "audio/x-wav":
  6935. case "audio/mp3":
  6936. case "audio/mpeg":
  6937. case "audio/mpeg3":
  6938. case "audio/x-mpeg-3":
  6939. case "audio/ogg":
  6940. FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
  6941. break;
  6942. default:
  6943. if ((this._filesToLoad[i].name.indexOf(".babylon") !== -1 || this._filesToLoad[i].name.indexOf(".stl") !== -1 ||
  6944. this._filesToLoad[i].name.indexOf(".obj") !== -1 || this._filesToLoad[i].name.indexOf(".mtl") !== -1)
  6945. && this._filesToLoad[i].name.indexOf(".manifest") === -1
  6946. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  6947. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  6948. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  6949. this._sceneFileToLoad = this._filesToLoad[i];
  6950. }
  6951. break;
  6952. }
  6953. }
  6954. this.reload();
  6955. }
  6956. };
  6957. FilesInput.prototype.reload = function () {
  6958. var _this = this;
  6959. var that = this;
  6960. // If a ".babylon" file has been provided
  6961. if (this._sceneFileToLoad) {
  6962. if (this._currentScene) {
  6963. if (BABYLON.Tools.errorsCount > 0) {
  6964. BABYLON.Tools.ClearLogCache();
  6965. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  6966. }
  6967. this._engine.stopRenderLoop();
  6968. this._currentScene.dispose();
  6969. }
  6970. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  6971. that._currentScene = newScene;
  6972. // Wait for textures and shaders to be ready
  6973. that._currentScene.executeWhenReady(function () {
  6974. // Attach camera to canvas inputs
  6975. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  6976. that._currentScene.createDefaultCameraOrLight();
  6977. }
  6978. that._currentScene.activeCamera.attachControl(that._canvas);
  6979. if (that._sceneLoadedCallback) {
  6980. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  6981. }
  6982. that._engine.runRenderLoop(function () { that.renderFunction(); });
  6983. });
  6984. }, function (progress) {
  6985. if (_this._progressCallback) {
  6986. _this._progressCallback(progress);
  6987. }
  6988. });
  6989. }
  6990. else {
  6991. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  6992. }
  6993. };
  6994. FilesInput.FilesTextures = new Array();
  6995. FilesInput.FilesToLoad = new Array();
  6996. return FilesInput;
  6997. })();
  6998. BABYLON.FilesInput = FilesInput;
  6999. })(BABYLON || (BABYLON = {}));
  7000. var BABYLON;
  7001. (function (BABYLON) {
  7002. var IntersectionInfo = (function () {
  7003. function IntersectionInfo(bu, bv, distance) {
  7004. this.bu = bu;
  7005. this.bv = bv;
  7006. this.distance = distance;
  7007. this.faceId = 0;
  7008. this.subMeshId = 0;
  7009. }
  7010. return IntersectionInfo;
  7011. })();
  7012. BABYLON.IntersectionInfo = IntersectionInfo;
  7013. var PickingInfo = (function () {
  7014. function PickingInfo() {
  7015. this.hit = false;
  7016. this.distance = 0;
  7017. this.pickedPoint = null;
  7018. this.pickedMesh = null;
  7019. this.bu = 0;
  7020. this.bv = 0;
  7021. this.faceId = -1;
  7022. this.subMeshId = 0;
  7023. this.pickedSprite = null;
  7024. }
  7025. // Methods
  7026. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  7027. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  7028. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  7029. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  7030. return null;
  7031. }
  7032. var indices = this.pickedMesh.getIndices();
  7033. var result;
  7034. if (useVerticesNormals) {
  7035. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  7036. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  7037. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  7038. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  7039. normal0 = normal0.scale(this.bu);
  7040. normal1 = normal1.scale(this.bv);
  7041. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  7042. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  7043. }
  7044. else {
  7045. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  7046. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  7047. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  7048. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  7049. var p1p2 = vertex1.subtract(vertex2);
  7050. var p3p2 = vertex3.subtract(vertex2);
  7051. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  7052. }
  7053. if (useWorldCoordinates) {
  7054. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  7055. }
  7056. return BABYLON.Vector3.Normalize(result);
  7057. };
  7058. PickingInfo.prototype.getTextureCoordinates = function () {
  7059. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  7060. return null;
  7061. }
  7062. var indices = this.pickedMesh.getIndices();
  7063. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  7064. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  7065. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  7066. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  7067. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  7068. uv1 = uv1.scale(this.bu);
  7069. uv2 = uv2.scale(this.bv);
  7070. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  7071. };
  7072. return PickingInfo;
  7073. })();
  7074. BABYLON.PickingInfo = PickingInfo;
  7075. })(BABYLON || (BABYLON = {}));
  7076. var BABYLON;
  7077. (function (BABYLON) {
  7078. var BoundingSphere = (function () {
  7079. function BoundingSphere(minimum, maximum) {
  7080. this.minimum = minimum;
  7081. this.maximum = maximum;
  7082. this._tempRadiusVector = BABYLON.Vector3.Zero();
  7083. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  7084. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  7085. this.radius = distance * 0.5;
  7086. this.centerWorld = BABYLON.Vector3.Zero();
  7087. this._update(BABYLON.Matrix.Identity());
  7088. }
  7089. // Methods
  7090. BoundingSphere.prototype._update = function (world) {
  7091. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  7092. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  7093. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  7094. };
  7095. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  7096. for (var i = 0; i < 6; i++) {
  7097. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  7098. return false;
  7099. }
  7100. return true;
  7101. };
  7102. BoundingSphere.prototype.intersectsPoint = function (point) {
  7103. var x = this.centerWorld.x - point.x;
  7104. var y = this.centerWorld.y - point.y;
  7105. var z = this.centerWorld.z - point.z;
  7106. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7107. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  7108. return false;
  7109. return true;
  7110. };
  7111. // Statics
  7112. BoundingSphere.Intersects = function (sphere0, sphere1) {
  7113. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  7114. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  7115. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  7116. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7117. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  7118. return false;
  7119. return true;
  7120. };
  7121. return BoundingSphere;
  7122. })();
  7123. BABYLON.BoundingSphere = BoundingSphere;
  7124. })(BABYLON || (BABYLON = {}));
  7125. var BABYLON;
  7126. (function (BABYLON) {
  7127. var BoundingBox = (function () {
  7128. function BoundingBox(minimum, maximum) {
  7129. this.minimum = minimum;
  7130. this.maximum = maximum;
  7131. this.vectors = new Array();
  7132. this.vectorsWorld = new Array();
  7133. // Bounding vectors
  7134. this.vectors.push(this.minimum.clone());
  7135. this.vectors.push(this.maximum.clone());
  7136. this.vectors.push(this.minimum.clone());
  7137. this.vectors[2].x = this.maximum.x;
  7138. this.vectors.push(this.minimum.clone());
  7139. this.vectors[3].y = this.maximum.y;
  7140. this.vectors.push(this.minimum.clone());
  7141. this.vectors[4].z = this.maximum.z;
  7142. this.vectors.push(this.maximum.clone());
  7143. this.vectors[5].z = this.minimum.z;
  7144. this.vectors.push(this.maximum.clone());
  7145. this.vectors[6].x = this.minimum.x;
  7146. this.vectors.push(this.maximum.clone());
  7147. this.vectors[7].y = this.minimum.y;
  7148. // OBB
  7149. this.center = this.maximum.add(this.minimum).scale(0.5);
  7150. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  7151. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  7152. // World
  7153. for (var index = 0; index < this.vectors.length; index++) {
  7154. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  7155. }
  7156. this.minimumWorld = BABYLON.Vector3.Zero();
  7157. this.maximumWorld = BABYLON.Vector3.Zero();
  7158. this._update(BABYLON.Matrix.Identity());
  7159. }
  7160. // Methods
  7161. BoundingBox.prototype.getWorldMatrix = function () {
  7162. return this._worldMatrix;
  7163. };
  7164. BoundingBox.prototype._update = function (world) {
  7165. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  7166. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  7167. for (var index = 0; index < this.vectors.length; index++) {
  7168. var v = this.vectorsWorld[index];
  7169. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  7170. if (v.x < this.minimumWorld.x)
  7171. this.minimumWorld.x = v.x;
  7172. if (v.y < this.minimumWorld.y)
  7173. this.minimumWorld.y = v.y;
  7174. if (v.z < this.minimumWorld.z)
  7175. this.minimumWorld.z = v.z;
  7176. if (v.x > this.maximumWorld.x)
  7177. this.maximumWorld.x = v.x;
  7178. if (v.y > this.maximumWorld.y)
  7179. this.maximumWorld.y = v.y;
  7180. if (v.z > this.maximumWorld.z)
  7181. this.maximumWorld.z = v.z;
  7182. }
  7183. // OBB
  7184. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  7185. this.center.scaleInPlace(0.5);
  7186. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  7187. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  7188. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  7189. this._worldMatrix = world;
  7190. };
  7191. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  7192. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  7193. };
  7194. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7195. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  7196. };
  7197. BoundingBox.prototype.intersectsPoint = function (point) {
  7198. var delta = -BABYLON.Engine.Epsilon;
  7199. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  7200. return false;
  7201. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  7202. return false;
  7203. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  7204. return false;
  7205. return true;
  7206. };
  7207. BoundingBox.prototype.intersectsSphere = function (sphere) {
  7208. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  7209. };
  7210. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  7211. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  7212. return false;
  7213. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  7214. return false;
  7215. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  7216. return false;
  7217. return true;
  7218. };
  7219. // Statics
  7220. BoundingBox.Intersects = function (box0, box1) {
  7221. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  7222. return false;
  7223. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  7224. return false;
  7225. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  7226. return false;
  7227. return true;
  7228. };
  7229. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  7230. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  7231. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  7232. return (num <= (sphereRadius * sphereRadius));
  7233. };
  7234. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  7235. for (var p = 0; p < 6; p++) {
  7236. for (var i = 0; i < 8; i++) {
  7237. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7238. return false;
  7239. }
  7240. }
  7241. }
  7242. return true;
  7243. };
  7244. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  7245. for (var p = 0; p < 6; p++) {
  7246. var inCount = 8;
  7247. for (var i = 0; i < 8; i++) {
  7248. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7249. --inCount;
  7250. }
  7251. else {
  7252. break;
  7253. }
  7254. }
  7255. if (inCount === 0)
  7256. return false;
  7257. }
  7258. return true;
  7259. };
  7260. return BoundingBox;
  7261. })();
  7262. BABYLON.BoundingBox = BoundingBox;
  7263. })(BABYLON || (BABYLON = {}));
  7264. var BABYLON;
  7265. (function (BABYLON) {
  7266. var computeBoxExtents = function (axis, box) {
  7267. var p = BABYLON.Vector3.Dot(box.center, axis);
  7268. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  7269. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  7270. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  7271. var r = r0 + r1 + r2;
  7272. return {
  7273. min: p - r,
  7274. max: p + r
  7275. };
  7276. };
  7277. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  7278. var axisOverlap = function (axis, box0, box1) {
  7279. var result0 = computeBoxExtents(axis, box0);
  7280. var result1 = computeBoxExtents(axis, box1);
  7281. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  7282. };
  7283. var BoundingInfo = (function () {
  7284. function BoundingInfo(minimum, maximum) {
  7285. this.minimum = minimum;
  7286. this.maximum = maximum;
  7287. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  7288. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  7289. }
  7290. // Methods
  7291. BoundingInfo.prototype._update = function (world) {
  7292. this.boundingBox._update(world);
  7293. this.boundingSphere._update(world);
  7294. };
  7295. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  7296. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  7297. return false;
  7298. return this.boundingBox.isInFrustum(frustumPlanes);
  7299. };
  7300. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7301. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  7302. };
  7303. BoundingInfo.prototype._checkCollision = function (collider) {
  7304. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  7305. };
  7306. BoundingInfo.prototype.intersectsPoint = function (point) {
  7307. if (!this.boundingSphere.centerWorld) {
  7308. return false;
  7309. }
  7310. if (!this.boundingSphere.intersectsPoint(point)) {
  7311. return false;
  7312. }
  7313. if (!this.boundingBox.intersectsPoint(point)) {
  7314. return false;
  7315. }
  7316. return true;
  7317. };
  7318. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  7319. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  7320. return false;
  7321. }
  7322. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  7323. return false;
  7324. }
  7325. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  7326. return false;
  7327. }
  7328. if (!precise) {
  7329. return true;
  7330. }
  7331. var box0 = this.boundingBox;
  7332. var box1 = boundingInfo.boundingBox;
  7333. if (!axisOverlap(box0.directions[0], box0, box1))
  7334. return false;
  7335. if (!axisOverlap(box0.directions[1], box0, box1))
  7336. return false;
  7337. if (!axisOverlap(box0.directions[2], box0, box1))
  7338. return false;
  7339. if (!axisOverlap(box1.directions[0], box0, box1))
  7340. return false;
  7341. if (!axisOverlap(box1.directions[1], box0, box1))
  7342. return false;
  7343. if (!axisOverlap(box1.directions[2], box0, box1))
  7344. return false;
  7345. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  7346. return false;
  7347. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  7348. return false;
  7349. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  7350. return false;
  7351. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  7352. return false;
  7353. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  7354. return false;
  7355. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  7356. return false;
  7357. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  7358. return false;
  7359. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  7360. return false;
  7361. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  7362. return false;
  7363. return true;
  7364. };
  7365. return BoundingInfo;
  7366. })();
  7367. BABYLON.BoundingInfo = BoundingInfo;
  7368. })(BABYLON || (BABYLON = {}));
  7369. var BABYLON;
  7370. (function (BABYLON) {
  7371. var AbstractMesh = (function (_super) {
  7372. __extends(AbstractMesh, _super);
  7373. function AbstractMesh(name, scene) {
  7374. var _this = this;
  7375. _super.call(this, name, scene);
  7376. // Properties
  7377. this.definedFacingForward = true; // orientation for POV movement & rotation
  7378. this.position = new BABYLON.Vector3(0, 0, 0);
  7379. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7380. this.scaling = new BABYLON.Vector3(1, 1, 1);
  7381. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  7382. this.visibility = 1.0;
  7383. this.alphaIndex = Number.MAX_VALUE;
  7384. this.infiniteDistance = false;
  7385. this.isVisible = true;
  7386. this.isPickable = true;
  7387. this.showBoundingBox = false;
  7388. this.showSubMeshesBoundingBox = false;
  7389. this.onDispose = null;
  7390. this.isBlocker = false;
  7391. this.renderingGroupId = 0;
  7392. this.receiveShadows = false;
  7393. this.renderOutline = false;
  7394. this.outlineColor = BABYLON.Color3.Red();
  7395. this.outlineWidth = 0.02;
  7396. this.renderOverlay = false;
  7397. this.overlayColor = BABYLON.Color3.Red();
  7398. this.overlayAlpha = 0.5;
  7399. this.hasVertexAlpha = false;
  7400. this.useVertexColors = true;
  7401. this.applyFog = true;
  7402. this.computeBonesUsingShaders = true;
  7403. this.scalingDeterminant = 1;
  7404. this.useOctreeForRenderingSelection = true;
  7405. this.useOctreeForPicking = true;
  7406. this.useOctreeForCollisions = true;
  7407. this.layerMask = 0x0FFFFFFF;
  7408. this.alwaysSelectAsActiveMesh = false;
  7409. // Physics
  7410. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  7411. // Collisions
  7412. this._checkCollisions = false;
  7413. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7414. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  7415. this._collider = new BABYLON.Collider();
  7416. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7417. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7418. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7419. // Edges
  7420. this.edgesWidth = 1;
  7421. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  7422. // Cache
  7423. this._localScaling = BABYLON.Matrix.Zero();
  7424. this._localRotation = BABYLON.Matrix.Zero();
  7425. this._localTranslation = BABYLON.Matrix.Zero();
  7426. this._localBillboard = BABYLON.Matrix.Zero();
  7427. this._localPivotScaling = BABYLON.Matrix.Zero();
  7428. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  7429. this._localWorld = BABYLON.Matrix.Zero();
  7430. this._worldMatrix = BABYLON.Matrix.Zero();
  7431. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  7432. this._absolutePosition = BABYLON.Vector3.Zero();
  7433. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  7434. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  7435. this._isDirty = false;
  7436. this._pivotMatrix = BABYLON.Matrix.Identity();
  7437. this._isDisposed = false;
  7438. this._renderId = 0;
  7439. this._intersectionsInProgress = new Array();
  7440. this._onAfterWorldMatrixUpdate = new Array();
  7441. this._isWorldMatrixFrozen = false;
  7442. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  7443. if (collidedMesh === void 0) { collidedMesh = null; }
  7444. //TODO move this to the collision coordinator!
  7445. if (_this.getScene().workerCollisions)
  7446. newPosition.multiplyInPlace(_this._collider.radius);
  7447. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  7448. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  7449. _this.position.addInPlace(_this._diffPositionForCollisions);
  7450. }
  7451. if (_this.onCollide && collidedMesh) {
  7452. _this.onCollide(collidedMesh);
  7453. }
  7454. };
  7455. scene.addMesh(this);
  7456. }
  7457. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  7458. get: function () {
  7459. return AbstractMesh._BILLBOARDMODE_NONE;
  7460. },
  7461. enumerable: true,
  7462. configurable: true
  7463. });
  7464. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  7465. get: function () {
  7466. return AbstractMesh._BILLBOARDMODE_X;
  7467. },
  7468. enumerable: true,
  7469. configurable: true
  7470. });
  7471. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  7472. get: function () {
  7473. return AbstractMesh._BILLBOARDMODE_Y;
  7474. },
  7475. enumerable: true,
  7476. configurable: true
  7477. });
  7478. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  7479. get: function () {
  7480. return AbstractMesh._BILLBOARDMODE_Z;
  7481. },
  7482. enumerable: true,
  7483. configurable: true
  7484. });
  7485. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  7486. get: function () {
  7487. return AbstractMesh._BILLBOARDMODE_ALL;
  7488. },
  7489. enumerable: true,
  7490. configurable: true
  7491. });
  7492. // Methods
  7493. AbstractMesh.prototype.disableEdgesRendering = function () {
  7494. if (this._edgesRenderer !== undefined) {
  7495. this._edgesRenderer.dispose();
  7496. this._edgesRenderer = undefined;
  7497. }
  7498. };
  7499. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  7500. if (epsilon === void 0) { epsilon = 0.95; }
  7501. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  7502. this.disableEdgesRendering();
  7503. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  7504. };
  7505. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  7506. get: function () {
  7507. return false;
  7508. },
  7509. enumerable: true,
  7510. configurable: true
  7511. });
  7512. AbstractMesh.prototype.getLOD = function (camera) {
  7513. return this;
  7514. };
  7515. AbstractMesh.prototype.getTotalVertices = function () {
  7516. return 0;
  7517. };
  7518. AbstractMesh.prototype.getIndices = function () {
  7519. return null;
  7520. };
  7521. AbstractMesh.prototype.getVerticesData = function (kind) {
  7522. return null;
  7523. };
  7524. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  7525. return false;
  7526. };
  7527. AbstractMesh.prototype.getBoundingInfo = function () {
  7528. if (this._masterMesh) {
  7529. return this._masterMesh.getBoundingInfo();
  7530. }
  7531. if (!this._boundingInfo) {
  7532. this._updateBoundingInfo();
  7533. }
  7534. return this._boundingInfo;
  7535. };
  7536. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  7537. get: function () {
  7538. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  7539. },
  7540. enumerable: true,
  7541. configurable: true
  7542. });
  7543. AbstractMesh.prototype._preActivate = function () {
  7544. };
  7545. AbstractMesh.prototype._activate = function (renderId) {
  7546. this._renderId = renderId;
  7547. };
  7548. AbstractMesh.prototype.getWorldMatrix = function () {
  7549. if (this._masterMesh) {
  7550. return this._masterMesh.getWorldMatrix();
  7551. }
  7552. if (this._currentRenderId !== this.getScene().getRenderId()) {
  7553. this.computeWorldMatrix();
  7554. }
  7555. return this._worldMatrix;
  7556. };
  7557. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  7558. get: function () {
  7559. return this._worldMatrix;
  7560. },
  7561. enumerable: true,
  7562. configurable: true
  7563. });
  7564. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  7565. get: function () {
  7566. return this._absolutePosition;
  7567. },
  7568. enumerable: true,
  7569. configurable: true
  7570. });
  7571. AbstractMesh.prototype.freezeWorldMatrix = function () {
  7572. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  7573. this.computeWorldMatrix(true);
  7574. this._isWorldMatrixFrozen = true;
  7575. };
  7576. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  7577. this._isWorldMatrixFrozen = false;
  7578. this.computeWorldMatrix(true);
  7579. };
  7580. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  7581. get: function () {
  7582. return this._isWorldMatrixFrozen;
  7583. },
  7584. enumerable: true,
  7585. configurable: true
  7586. });
  7587. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  7588. axis.normalize();
  7589. if (!this.rotationQuaternion) {
  7590. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7591. this.rotation = BABYLON.Vector3.Zero();
  7592. }
  7593. var rotationQuaternion;
  7594. if (!space || space === BABYLON.Space.LOCAL) {
  7595. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7596. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  7597. }
  7598. else {
  7599. if (this.parent) {
  7600. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7601. invertParentWorldMatrix.invert();
  7602. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  7603. }
  7604. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7605. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  7606. }
  7607. };
  7608. AbstractMesh.prototype.translate = function (axis, distance, space) {
  7609. var displacementVector = axis.scale(distance);
  7610. if (!space || space === BABYLON.Space.LOCAL) {
  7611. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  7612. this.setPositionWithLocalVector(tempV3);
  7613. }
  7614. else {
  7615. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  7616. }
  7617. };
  7618. AbstractMesh.prototype.getAbsolutePosition = function () {
  7619. this.computeWorldMatrix();
  7620. return this._absolutePosition;
  7621. };
  7622. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  7623. if (!absolutePosition) {
  7624. return;
  7625. }
  7626. var absolutePositionX;
  7627. var absolutePositionY;
  7628. var absolutePositionZ;
  7629. if (absolutePosition.x === undefined) {
  7630. if (arguments.length < 3) {
  7631. return;
  7632. }
  7633. absolutePositionX = arguments[0];
  7634. absolutePositionY = arguments[1];
  7635. absolutePositionZ = arguments[2];
  7636. }
  7637. else {
  7638. absolutePositionX = absolutePosition.x;
  7639. absolutePositionY = absolutePosition.y;
  7640. absolutePositionZ = absolutePosition.z;
  7641. }
  7642. if (this.parent) {
  7643. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7644. invertParentWorldMatrix.invert();
  7645. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  7646. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  7647. }
  7648. else {
  7649. this.position.x = absolutePositionX;
  7650. this.position.y = absolutePositionY;
  7651. this.position.z = absolutePositionZ;
  7652. }
  7653. };
  7654. // ================================== Point of View Movement =================================
  7655. /**
  7656. * Perform relative position change from the point of view of behind the front of the mesh.
  7657. * This is performed taking into account the meshes current rotation, so you do not have to care.
  7658. * Supports definition of mesh facing forward or backward.
  7659. * @param {number} amountRight
  7660. * @param {number} amountUp
  7661. * @param {number} amountForward
  7662. */
  7663. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  7664. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  7665. };
  7666. /**
  7667. * Calculate relative position change from the point of view of behind the front of the mesh.
  7668. * This is performed taking into account the meshes current rotation, so you do not have to care.
  7669. * Supports definition of mesh facing forward or backward.
  7670. * @param {number} amountRight
  7671. * @param {number} amountUp
  7672. * @param {number} amountForward
  7673. */
  7674. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  7675. var rotMatrix = new BABYLON.Matrix();
  7676. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7677. rotQuaternion.toRotationMatrix(rotMatrix);
  7678. var translationDelta = BABYLON.Vector3.Zero();
  7679. var defForwardMult = this.definedFacingForward ? -1 : 1;
  7680. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  7681. return translationDelta;
  7682. };
  7683. // ================================== Point of View Rotation =================================
  7684. /**
  7685. * Perform relative rotation change from the point of view of behind the front of the mesh.
  7686. * Supports definition of mesh facing forward or backward.
  7687. * @param {number} flipBack
  7688. * @param {number} twirlClockwise
  7689. * @param {number} tiltRight
  7690. */
  7691. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  7692. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  7693. };
  7694. /**
  7695. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  7696. * Supports definition of mesh facing forward or backward.
  7697. * @param {number} flipBack
  7698. * @param {number} twirlClockwise
  7699. * @param {number} tiltRight
  7700. */
  7701. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  7702. var defForwardMult = this.definedFacingForward ? 1 : -1;
  7703. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  7704. };
  7705. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  7706. this._pivotMatrix = matrix;
  7707. this._cache.pivotMatrixUpdated = true;
  7708. };
  7709. AbstractMesh.prototype.getPivotMatrix = function () {
  7710. return this._pivotMatrix;
  7711. };
  7712. AbstractMesh.prototype._isSynchronized = function () {
  7713. if (this._isDirty) {
  7714. return false;
  7715. }
  7716. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  7717. return false;
  7718. if (this._cache.pivotMatrixUpdated) {
  7719. return false;
  7720. }
  7721. if (this.infiniteDistance) {
  7722. return false;
  7723. }
  7724. if (!this._cache.position.equals(this.position))
  7725. return false;
  7726. if (this.rotationQuaternion) {
  7727. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  7728. return false;
  7729. }
  7730. else {
  7731. if (!this._cache.rotation.equals(this.rotation))
  7732. return false;
  7733. }
  7734. if (!this._cache.scaling.equals(this.scaling))
  7735. return false;
  7736. return true;
  7737. };
  7738. AbstractMesh.prototype._initCache = function () {
  7739. _super.prototype._initCache.call(this);
  7740. this._cache.localMatrixUpdated = false;
  7741. this._cache.position = BABYLON.Vector3.Zero();
  7742. this._cache.scaling = BABYLON.Vector3.Zero();
  7743. this._cache.rotation = BABYLON.Vector3.Zero();
  7744. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  7745. };
  7746. AbstractMesh.prototype.markAsDirty = function (property) {
  7747. if (property === "rotation") {
  7748. this.rotationQuaternion = null;
  7749. }
  7750. this._currentRenderId = Number.MAX_VALUE;
  7751. this._isDirty = true;
  7752. };
  7753. AbstractMesh.prototype._updateBoundingInfo = function () {
  7754. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  7755. this._boundingInfo._update(this.worldMatrixFromCache);
  7756. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  7757. };
  7758. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  7759. if (!this.subMeshes) {
  7760. return;
  7761. }
  7762. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  7763. var subMesh = this.subMeshes[subIndex];
  7764. subMesh.updateBoundingInfo(matrix);
  7765. }
  7766. };
  7767. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  7768. if (this._isWorldMatrixFrozen) {
  7769. return this._worldMatrix;
  7770. }
  7771. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  7772. return this._worldMatrix;
  7773. }
  7774. this._cache.position.copyFrom(this.position);
  7775. this._cache.scaling.copyFrom(this.scaling);
  7776. this._cache.pivotMatrixUpdated = false;
  7777. this._currentRenderId = this.getScene().getRenderId();
  7778. this._isDirty = false;
  7779. // Scaling
  7780. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, this._localScaling);
  7781. // Rotation
  7782. if (this.rotationQuaternion) {
  7783. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  7784. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  7785. }
  7786. else {
  7787. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  7788. this._cache.rotation.copyFrom(this.rotation);
  7789. }
  7790. // Translation
  7791. if (this.infiniteDistance && !this.parent) {
  7792. var camera = this.getScene().activeCamera;
  7793. if (camera) {
  7794. var cameraWorldMatrix = camera.getWorldMatrix();
  7795. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  7796. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  7797. }
  7798. }
  7799. else {
  7800. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  7801. }
  7802. // Composing transformations
  7803. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  7804. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  7805. // Billboarding
  7806. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  7807. var localPosition = this.position.clone();
  7808. var zero = this.getScene().activeCamera.globalPosition.clone();
  7809. if (this.parent && this.parent.position) {
  7810. localPosition.addInPlace(this.parent.position);
  7811. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  7812. }
  7813. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  7814. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  7815. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  7816. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  7817. zero.y = localPosition.y + 0.001;
  7818. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  7819. zero.z = localPosition.z + 0.001;
  7820. }
  7821. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  7822. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  7823. this._localBillboard.invert();
  7824. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  7825. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  7826. }
  7827. // Local world
  7828. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  7829. // Parent
  7830. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  7831. this._markSyncedWithParent();
  7832. if (this._meshToBoneReferal) {
  7833. if (!this._localMeshReferalTransform) {
  7834. this._localMeshReferalTransform = BABYLON.Matrix.Zero();
  7835. }
  7836. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._localMeshReferalTransform);
  7837. this._localMeshReferalTransform.multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  7838. }
  7839. else {
  7840. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  7841. }
  7842. }
  7843. else {
  7844. this._worldMatrix.copyFrom(this._localWorld);
  7845. }
  7846. // Bounding info
  7847. this._updateBoundingInfo();
  7848. // Absolute position
  7849. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  7850. // Callbacks
  7851. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  7852. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  7853. }
  7854. return this._worldMatrix;
  7855. };
  7856. /**
  7857. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  7858. * @param func: callback function to add
  7859. */
  7860. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  7861. this._onAfterWorldMatrixUpdate.push(func);
  7862. };
  7863. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  7864. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  7865. if (index > -1) {
  7866. this._onAfterWorldMatrixUpdate.splice(index, 1);
  7867. }
  7868. };
  7869. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  7870. this.computeWorldMatrix();
  7871. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  7872. };
  7873. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  7874. this.computeWorldMatrix();
  7875. var invLocalWorldMatrix = this._localWorld.clone();
  7876. invLocalWorldMatrix.invert();
  7877. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  7878. };
  7879. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  7880. this.computeWorldMatrix(true);
  7881. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  7882. };
  7883. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  7884. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  7885. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  7886. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  7887. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  7888. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  7889. /// <returns>Mesh oriented towards targetMesh</returns>
  7890. yawCor = yawCor || 0; // default to zero if undefined
  7891. pitchCor = pitchCor || 0;
  7892. rollCor = rollCor || 0;
  7893. var dv = targetPoint.subtract(this.position);
  7894. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  7895. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  7896. var pitch = Math.atan2(dv.y, len);
  7897. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  7898. };
  7899. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  7900. this._meshToBoneReferal = affectedMesh;
  7901. this.parent = bone;
  7902. if (bone.getWorldMatrix().determinant() < 0) {
  7903. this.scalingDeterminant *= -1;
  7904. }
  7905. };
  7906. AbstractMesh.prototype.detachFromBone = function () {
  7907. if (this.parent.getWorldMatrix().determinant() < 0) {
  7908. this.scalingDeterminant *= -1;
  7909. }
  7910. this._meshToBoneReferal = null;
  7911. this.parent = null;
  7912. };
  7913. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  7914. return this._boundingInfo.isInFrustum(frustumPlanes);
  7915. };
  7916. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  7917. if (!camera) {
  7918. camera = this.getScene().activeCamera;
  7919. }
  7920. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  7921. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  7922. return false;
  7923. }
  7924. return true;
  7925. };
  7926. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  7927. if (!this._boundingInfo || !mesh._boundingInfo) {
  7928. return false;
  7929. }
  7930. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  7931. };
  7932. AbstractMesh.prototype.intersectsPoint = function (point) {
  7933. if (!this._boundingInfo) {
  7934. return false;
  7935. }
  7936. return this._boundingInfo.intersectsPoint(point);
  7937. };
  7938. // Physics
  7939. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  7940. var physicsEngine = this.getScene().getPhysicsEngine();
  7941. if (!physicsEngine) {
  7942. return null;
  7943. }
  7944. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  7945. if (impostor.impostor) {
  7946. // Old API
  7947. options = impostor;
  7948. impostor = impostor.impostor;
  7949. }
  7950. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  7951. physicsEngine._unregisterMesh(this);
  7952. return null;
  7953. }
  7954. if (!options) {
  7955. options = { mass: 0, friction: 0.2, restitution: 0.2 };
  7956. }
  7957. else {
  7958. if (!options.mass && options.mass !== 0)
  7959. options.mass = 0;
  7960. if (!options.friction && options.friction !== 0)
  7961. options.friction = 0.2;
  7962. if (!options.restitution && options.restitution !== 0)
  7963. options.restitution = 0.2;
  7964. }
  7965. this._physicImpostor = impostor;
  7966. this._physicsMass = options.mass;
  7967. this._physicsFriction = options.friction;
  7968. this._physicRestitution = options.restitution;
  7969. return physicsEngine._registerMesh(this, impostor, options);
  7970. };
  7971. AbstractMesh.prototype.getPhysicsImpostor = function () {
  7972. if (!this._physicImpostor) {
  7973. return BABYLON.PhysicsEngine.NoImpostor;
  7974. }
  7975. return this._physicImpostor;
  7976. };
  7977. AbstractMesh.prototype.getPhysicsMass = function () {
  7978. if (!this._physicsMass) {
  7979. return 0;
  7980. }
  7981. return this._physicsMass;
  7982. };
  7983. AbstractMesh.prototype.getPhysicsFriction = function () {
  7984. if (!this._physicsFriction) {
  7985. return 0;
  7986. }
  7987. return this._physicsFriction;
  7988. };
  7989. AbstractMesh.prototype.getPhysicsRestitution = function () {
  7990. if (!this._physicRestitution) {
  7991. return 0;
  7992. }
  7993. return this._physicRestitution;
  7994. };
  7995. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  7996. if (!camera) {
  7997. camera = this.getScene().activeCamera;
  7998. }
  7999. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  8000. };
  8001. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  8002. if (!camera) {
  8003. camera = this.getScene().activeCamera;
  8004. }
  8005. return this.absolutePosition.subtract(camera.position).length();
  8006. };
  8007. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  8008. if (!this._physicImpostor) {
  8009. return;
  8010. }
  8011. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  8012. };
  8013. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  8014. if (!this._physicImpostor) {
  8015. return;
  8016. }
  8017. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  8018. };
  8019. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  8020. if (!this._physicImpostor) {
  8021. return;
  8022. }
  8023. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  8024. };
  8025. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  8026. // Collisions
  8027. get: function () {
  8028. return this._checkCollisions;
  8029. },
  8030. set: function (collisionEnabled) {
  8031. this._checkCollisions = collisionEnabled;
  8032. if (this.getScene().workerCollisions) {
  8033. this.getScene().collisionCoordinator.onMeshUpdated(this);
  8034. }
  8035. },
  8036. enumerable: true,
  8037. configurable: true
  8038. });
  8039. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  8040. var globalPosition = this.getAbsolutePosition();
  8041. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  8042. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  8043. this._collider.radius = this.ellipsoid;
  8044. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  8045. };
  8046. // Submeshes octree
  8047. /**
  8048. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  8049. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  8050. */
  8051. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  8052. if (maxCapacity === void 0) { maxCapacity = 64; }
  8053. if (maxDepth === void 0) { maxDepth = 2; }
  8054. if (!this._submeshesOctree) {
  8055. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  8056. }
  8057. this.computeWorldMatrix(true);
  8058. // Update octree
  8059. var bbox = this.getBoundingInfo().boundingBox;
  8060. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  8061. return this._submeshesOctree;
  8062. };
  8063. // Collisions
  8064. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  8065. this._generatePointsArray();
  8066. // Transformation
  8067. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  8068. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  8069. subMesh._lastColliderWorldVertices = [];
  8070. subMesh._trianglePlanes = [];
  8071. var start = subMesh.verticesStart;
  8072. var end = (subMesh.verticesStart + subMesh.verticesCount);
  8073. for (var i = start; i < end; i++) {
  8074. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  8075. }
  8076. }
  8077. // Collide
  8078. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  8079. if (collider.collisionFound) {
  8080. collider.collidedMesh = this;
  8081. }
  8082. };
  8083. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  8084. var subMeshes;
  8085. var len;
  8086. // Octrees
  8087. if (this._submeshesOctree && this.useOctreeForCollisions) {
  8088. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  8089. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  8090. len = intersections.length;
  8091. subMeshes = intersections.data;
  8092. }
  8093. else {
  8094. subMeshes = this.subMeshes;
  8095. len = subMeshes.length;
  8096. }
  8097. for (var index = 0; index < len; index++) {
  8098. var subMesh = subMeshes[index];
  8099. // Bounding test
  8100. if (len > 1 && !subMesh._checkCollision(collider))
  8101. continue;
  8102. this._collideForSubMesh(subMesh, transformMatrix, collider);
  8103. }
  8104. };
  8105. AbstractMesh.prototype._checkCollision = function (collider) {
  8106. // Bounding box test
  8107. if (!this._boundingInfo._checkCollision(collider))
  8108. return;
  8109. // Transformation matrix
  8110. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  8111. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  8112. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  8113. };
  8114. // Picking
  8115. AbstractMesh.prototype._generatePointsArray = function () {
  8116. return false;
  8117. };
  8118. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  8119. var pickingInfo = new BABYLON.PickingInfo();
  8120. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  8121. return pickingInfo;
  8122. }
  8123. if (!this._generatePointsArray()) {
  8124. return pickingInfo;
  8125. }
  8126. var intersectInfo = null;
  8127. // Octrees
  8128. var subMeshes;
  8129. var len;
  8130. if (this._submeshesOctree && this.useOctreeForPicking) {
  8131. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  8132. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  8133. len = intersections.length;
  8134. subMeshes = intersections.data;
  8135. }
  8136. else {
  8137. subMeshes = this.subMeshes;
  8138. len = subMeshes.length;
  8139. }
  8140. for (var index = 0; index < len; index++) {
  8141. var subMesh = subMeshes[index];
  8142. // Bounding test
  8143. if (len > 1 && !subMesh.canIntersects(ray))
  8144. continue;
  8145. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  8146. if (currentIntersectInfo) {
  8147. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  8148. intersectInfo = currentIntersectInfo;
  8149. intersectInfo.subMeshId = index;
  8150. if (fastCheck) {
  8151. break;
  8152. }
  8153. }
  8154. }
  8155. }
  8156. if (intersectInfo) {
  8157. // Get picked point
  8158. var world = this.getWorldMatrix();
  8159. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  8160. var direction = ray.direction.clone();
  8161. direction = direction.scale(intersectInfo.distance);
  8162. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  8163. var pickedPoint = worldOrigin.add(worldDirection);
  8164. // Return result
  8165. pickingInfo.hit = true;
  8166. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  8167. pickingInfo.pickedPoint = pickedPoint;
  8168. pickingInfo.pickedMesh = this;
  8169. pickingInfo.bu = intersectInfo.bu;
  8170. pickingInfo.bv = intersectInfo.bv;
  8171. pickingInfo.faceId = intersectInfo.faceId;
  8172. pickingInfo.subMeshId = intersectInfo.subMeshId;
  8173. return pickingInfo;
  8174. }
  8175. return pickingInfo;
  8176. };
  8177. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8178. return null;
  8179. };
  8180. AbstractMesh.prototype.releaseSubMeshes = function () {
  8181. if (this.subMeshes) {
  8182. while (this.subMeshes.length) {
  8183. this.subMeshes[0].dispose();
  8184. }
  8185. }
  8186. else {
  8187. this.subMeshes = new Array();
  8188. }
  8189. };
  8190. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  8191. var index;
  8192. // Animations
  8193. this.getScene().stopAnimation(this);
  8194. // Physics
  8195. if (this.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  8196. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  8197. }
  8198. // Intersections in progress
  8199. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  8200. var other = this._intersectionsInProgress[index];
  8201. var pos = other._intersectionsInProgress.indexOf(this);
  8202. other._intersectionsInProgress.splice(pos, 1);
  8203. }
  8204. this._intersectionsInProgress = [];
  8205. // Edges
  8206. if (this._edgesRenderer) {
  8207. this._edgesRenderer.dispose();
  8208. this._edgesRenderer = null;
  8209. }
  8210. // SubMeshes
  8211. this.releaseSubMeshes();
  8212. // Remove from scene
  8213. this.getScene().removeMesh(this);
  8214. if (!doNotRecurse) {
  8215. // Particles
  8216. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8217. if (this.getScene().particleSystems[index].emitter === this) {
  8218. this.getScene().particleSystems[index].dispose();
  8219. index--;
  8220. }
  8221. }
  8222. // Children
  8223. var objects = this.getScene().meshes.slice(0);
  8224. for (index = 0; index < objects.length; index++) {
  8225. if (objects[index].parent === this) {
  8226. objects[index].dispose();
  8227. }
  8228. }
  8229. }
  8230. else {
  8231. for (index = 0; index < this.getScene().meshes.length; index++) {
  8232. var obj = this.getScene().meshes[index];
  8233. if (obj.parent === this) {
  8234. obj.parent = null;
  8235. obj.computeWorldMatrix(true);
  8236. }
  8237. }
  8238. }
  8239. this._onAfterWorldMatrixUpdate = [];
  8240. this._isDisposed = true;
  8241. // Callback
  8242. if (this.onDispose) {
  8243. this.onDispose();
  8244. }
  8245. };
  8246. // Statics
  8247. AbstractMesh._BILLBOARDMODE_NONE = 0;
  8248. AbstractMesh._BILLBOARDMODE_X = 1;
  8249. AbstractMesh._BILLBOARDMODE_Y = 2;
  8250. AbstractMesh._BILLBOARDMODE_Z = 4;
  8251. AbstractMesh._BILLBOARDMODE_ALL = 7;
  8252. return AbstractMesh;
  8253. })(BABYLON.Node);
  8254. BABYLON.AbstractMesh = AbstractMesh;
  8255. })(BABYLON || (BABYLON = {}));
  8256. var BABYLON;
  8257. (function (BABYLON) {
  8258. var Light = (function (_super) {
  8259. __extends(Light, _super);
  8260. function Light(name, scene) {
  8261. _super.call(this, name, scene);
  8262. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  8263. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  8264. this.intensity = 1.0;
  8265. this.range = Number.MAX_VALUE;
  8266. this.includeOnlyWithLayerMask = 0;
  8267. this.includedOnlyMeshes = new Array();
  8268. this.excludedMeshes = new Array();
  8269. this.excludeWithLayerMask = 0;
  8270. this._excludedMeshesIds = new Array();
  8271. this._includedOnlyMeshesIds = new Array();
  8272. scene.addLight(this);
  8273. }
  8274. Light.prototype.getShadowGenerator = function () {
  8275. return this._shadowGenerator;
  8276. };
  8277. Light.prototype.getAbsolutePosition = function () {
  8278. return BABYLON.Vector3.Zero();
  8279. };
  8280. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  8281. };
  8282. Light.prototype._getWorldMatrix = function () {
  8283. return BABYLON.Matrix.Identity();
  8284. };
  8285. Light.prototype.canAffectMesh = function (mesh) {
  8286. if (!mesh) {
  8287. return true;
  8288. }
  8289. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  8290. return false;
  8291. }
  8292. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  8293. return false;
  8294. }
  8295. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  8296. return false;
  8297. }
  8298. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  8299. return false;
  8300. }
  8301. return true;
  8302. };
  8303. Light.prototype.getWorldMatrix = function () {
  8304. this._currentRenderId = this.getScene().getRenderId();
  8305. var worldMatrix = this._getWorldMatrix();
  8306. if (this.parent && this.parent.getWorldMatrix) {
  8307. if (!this._parentedWorldMatrix) {
  8308. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  8309. }
  8310. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  8311. this._markSyncedWithParent();
  8312. return this._parentedWorldMatrix;
  8313. }
  8314. return worldMatrix;
  8315. };
  8316. Light.prototype.dispose = function () {
  8317. if (this._shadowGenerator) {
  8318. this._shadowGenerator.dispose();
  8319. this._shadowGenerator = null;
  8320. }
  8321. // Animations
  8322. this.getScene().stopAnimation(this);
  8323. // Remove from scene
  8324. this.getScene().removeLight(this);
  8325. };
  8326. return Light;
  8327. })(BABYLON.Node);
  8328. BABYLON.Light = Light;
  8329. })(BABYLON || (BABYLON = {}));
  8330. var BABYLON;
  8331. (function (BABYLON) {
  8332. var PointLight = (function (_super) {
  8333. __extends(PointLight, _super);
  8334. function PointLight(name, position, scene) {
  8335. _super.call(this, name, scene);
  8336. this.position = position;
  8337. }
  8338. PointLight.prototype.getAbsolutePosition = function () {
  8339. return this._transformedPosition ? this._transformedPosition : this.position;
  8340. };
  8341. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  8342. if (this.parent && this.parent.getWorldMatrix) {
  8343. if (!this._transformedPosition) {
  8344. this._transformedPosition = BABYLON.Vector3.Zero();
  8345. }
  8346. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  8347. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  8348. return;
  8349. }
  8350. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  8351. };
  8352. PointLight.prototype.getShadowGenerator = function () {
  8353. return null;
  8354. };
  8355. PointLight.prototype._getWorldMatrix = function () {
  8356. if (!this._worldMatrix) {
  8357. this._worldMatrix = BABYLON.Matrix.Identity();
  8358. }
  8359. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8360. return this._worldMatrix;
  8361. };
  8362. return PointLight;
  8363. })(BABYLON.Light);
  8364. BABYLON.PointLight = PointLight;
  8365. })(BABYLON || (BABYLON = {}));
  8366. var BABYLON;
  8367. (function (BABYLON) {
  8368. var SpotLight = (function (_super) {
  8369. __extends(SpotLight, _super);
  8370. function SpotLight(name, position, direction, angle, exponent, scene) {
  8371. _super.call(this, name, scene);
  8372. this.position = position;
  8373. this.direction = direction;
  8374. this.angle = angle;
  8375. this.exponent = exponent;
  8376. }
  8377. SpotLight.prototype.getAbsolutePosition = function () {
  8378. return this.transformedPosition ? this.transformedPosition : this.position;
  8379. };
  8380. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8381. var activeCamera = this.getScene().activeCamera;
  8382. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  8383. };
  8384. SpotLight.prototype.supportsVSM = function () {
  8385. return true;
  8386. };
  8387. SpotLight.prototype.needRefreshPerFrame = function () {
  8388. return false;
  8389. };
  8390. SpotLight.prototype.setDirectionToTarget = function (target) {
  8391. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8392. return this.direction;
  8393. };
  8394. SpotLight.prototype.computeTransformedPosition = function () {
  8395. if (this.parent && this.parent.getWorldMatrix) {
  8396. if (!this.transformedPosition) {
  8397. this.transformedPosition = BABYLON.Vector3.Zero();
  8398. }
  8399. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8400. return true;
  8401. }
  8402. return false;
  8403. };
  8404. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  8405. var normalizeDirection;
  8406. if (this.parent && this.parent.getWorldMatrix) {
  8407. if (!this._transformedDirection) {
  8408. this._transformedDirection = BABYLON.Vector3.Zero();
  8409. }
  8410. this.computeTransformedPosition();
  8411. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8412. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  8413. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  8414. }
  8415. else {
  8416. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  8417. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8418. }
  8419. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  8420. };
  8421. SpotLight.prototype._getWorldMatrix = function () {
  8422. if (!this._worldMatrix) {
  8423. this._worldMatrix = BABYLON.Matrix.Identity();
  8424. }
  8425. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8426. return this._worldMatrix;
  8427. };
  8428. return SpotLight;
  8429. })(BABYLON.Light);
  8430. BABYLON.SpotLight = SpotLight;
  8431. })(BABYLON || (BABYLON = {}));
  8432. var BABYLON;
  8433. (function (BABYLON) {
  8434. var HemisphericLight = (function (_super) {
  8435. __extends(HemisphericLight, _super);
  8436. function HemisphericLight(name, direction, scene) {
  8437. _super.call(this, name, scene);
  8438. this.direction = direction;
  8439. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  8440. }
  8441. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  8442. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  8443. return this.direction;
  8444. };
  8445. HemisphericLight.prototype.getShadowGenerator = function () {
  8446. return null;
  8447. };
  8448. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  8449. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8450. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  8451. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  8452. };
  8453. HemisphericLight.prototype._getWorldMatrix = function () {
  8454. if (!this._worldMatrix) {
  8455. this._worldMatrix = BABYLON.Matrix.Identity();
  8456. }
  8457. return this._worldMatrix;
  8458. };
  8459. return HemisphericLight;
  8460. })(BABYLON.Light);
  8461. BABYLON.HemisphericLight = HemisphericLight;
  8462. })(BABYLON || (BABYLON = {}));
  8463. var BABYLON;
  8464. (function (BABYLON) {
  8465. var DirectionalLight = (function (_super) {
  8466. __extends(DirectionalLight, _super);
  8467. function DirectionalLight(name, direction, scene) {
  8468. _super.call(this, name, scene);
  8469. this.direction = direction;
  8470. this.shadowOrthoScale = 0.5;
  8471. this.autoUpdateExtends = true;
  8472. // Cache
  8473. this._orthoLeft = Number.MAX_VALUE;
  8474. this._orthoRight = Number.MIN_VALUE;
  8475. this._orthoTop = Number.MIN_VALUE;
  8476. this._orthoBottom = Number.MAX_VALUE;
  8477. this.position = direction.scale(-1);
  8478. }
  8479. DirectionalLight.prototype.getAbsolutePosition = function () {
  8480. return this.transformedPosition ? this.transformedPosition : this.position;
  8481. };
  8482. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  8483. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8484. return this.direction;
  8485. };
  8486. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8487. var activeCamera = this.getScene().activeCamera;
  8488. // Check extends
  8489. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  8490. var tempVector3 = BABYLON.Vector3.Zero();
  8491. this._orthoLeft = Number.MAX_VALUE;
  8492. this._orthoRight = Number.MIN_VALUE;
  8493. this._orthoTop = Number.MIN_VALUE;
  8494. this._orthoBottom = Number.MAX_VALUE;
  8495. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  8496. var mesh = renderList[meshIndex];
  8497. if (!mesh) {
  8498. continue;
  8499. }
  8500. var boundingInfo = mesh.getBoundingInfo();
  8501. if (!boundingInfo) {
  8502. continue;
  8503. }
  8504. var boundingBox = boundingInfo.boundingBox;
  8505. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  8506. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  8507. if (tempVector3.x < this._orthoLeft)
  8508. this._orthoLeft = tempVector3.x;
  8509. if (tempVector3.y < this._orthoBottom)
  8510. this._orthoBottom = tempVector3.y;
  8511. if (tempVector3.x > this._orthoRight)
  8512. this._orthoRight = tempVector3.x;
  8513. if (tempVector3.y > this._orthoTop)
  8514. this._orthoTop = tempVector3.y;
  8515. }
  8516. }
  8517. }
  8518. var xOffset = this._orthoRight - this._orthoLeft;
  8519. var yOffset = this._orthoTop - this._orthoBottom;
  8520. 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);
  8521. };
  8522. DirectionalLight.prototype.supportsVSM = function () {
  8523. return true;
  8524. };
  8525. DirectionalLight.prototype.needRefreshPerFrame = function () {
  8526. return true;
  8527. };
  8528. DirectionalLight.prototype.computeTransformedPosition = function () {
  8529. if (this.parent && this.parent.getWorldMatrix) {
  8530. if (!this.transformedPosition) {
  8531. this.transformedPosition = BABYLON.Vector3.Zero();
  8532. }
  8533. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8534. return true;
  8535. }
  8536. return false;
  8537. };
  8538. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  8539. if (this.parent && this.parent.getWorldMatrix) {
  8540. if (!this._transformedDirection) {
  8541. this._transformedDirection = BABYLON.Vector3.Zero();
  8542. }
  8543. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8544. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  8545. return;
  8546. }
  8547. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  8548. };
  8549. DirectionalLight.prototype._getWorldMatrix = function () {
  8550. if (!this._worldMatrix) {
  8551. this._worldMatrix = BABYLON.Matrix.Identity();
  8552. }
  8553. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8554. return this._worldMatrix;
  8555. };
  8556. return DirectionalLight;
  8557. })(BABYLON.Light);
  8558. BABYLON.DirectionalLight = DirectionalLight;
  8559. })(BABYLON || (BABYLON = {}));
  8560. var BABYLON;
  8561. (function (BABYLON) {
  8562. var ShadowGenerator = (function () {
  8563. function ShadowGenerator(mapSize, light) {
  8564. var _this = this;
  8565. // Members
  8566. this._filter = ShadowGenerator.FILTER_NONE;
  8567. this.blurScale = 2;
  8568. this._blurBoxOffset = 0;
  8569. this._bias = 0.00005;
  8570. this._lightDirection = BABYLON.Vector3.Zero();
  8571. this._darkness = 0;
  8572. this._transparencyShadow = false;
  8573. this._viewMatrix = BABYLON.Matrix.Zero();
  8574. this._projectionMatrix = BABYLON.Matrix.Zero();
  8575. this._transformMatrix = BABYLON.Matrix.Zero();
  8576. this._worldViewProjection = BABYLON.Matrix.Zero();
  8577. this._light = light;
  8578. this._scene = light.getScene();
  8579. this._mapSize = mapSize;
  8580. light._shadowGenerator = this;
  8581. // Render target
  8582. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  8583. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8584. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8585. this._shadowMap.anisotropicFilteringLevel = 1;
  8586. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8587. this._shadowMap.renderParticles = false;
  8588. this._shadowMap.onAfterUnbind = function () {
  8589. if (!_this.useBlurVarianceShadowMap) {
  8590. return;
  8591. }
  8592. if (!_this._shadowMap2) {
  8593. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  8594. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8595. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8596. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  8597. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  8598. _this._downSamplePostprocess.onApply = function (effect) {
  8599. effect.setTexture("textureSampler", _this._shadowMap);
  8600. };
  8601. _this.blurBoxOffset = 1;
  8602. }
  8603. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  8604. };
  8605. // Custom render function
  8606. var renderSubMesh = function (subMesh) {
  8607. var mesh = subMesh.getRenderingMesh();
  8608. var scene = _this._scene;
  8609. var engine = scene.getEngine();
  8610. // Culling
  8611. engine.setState(subMesh.getMaterial().backFaceCulling);
  8612. // Managing instances
  8613. var batch = mesh._getInstancesRenderList(subMesh._id);
  8614. if (batch.mustReturn) {
  8615. return;
  8616. }
  8617. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  8618. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  8619. engine.enableEffect(_this._effect);
  8620. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  8621. var material = subMesh.getMaterial();
  8622. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  8623. // Alpha test
  8624. if (material && material.needAlphaTesting()) {
  8625. var alphaTexture = material.getAlphaTestTexture();
  8626. _this._effect.setTexture("diffuseSampler", alphaTexture);
  8627. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  8628. }
  8629. // Bones
  8630. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  8631. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  8632. }
  8633. // Draw
  8634. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  8635. }
  8636. else {
  8637. // Need to reset refresh rate of the shadowMap
  8638. _this._shadowMap.resetRefreshCounter();
  8639. }
  8640. };
  8641. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  8642. var index;
  8643. for (index = 0; index < opaqueSubMeshes.length; index++) {
  8644. renderSubMesh(opaqueSubMeshes.data[index]);
  8645. }
  8646. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  8647. renderSubMesh(alphaTestSubMeshes.data[index]);
  8648. }
  8649. if (_this._transparencyShadow) {
  8650. for (index = 0; index < transparentSubMeshes.length; index++) {
  8651. renderSubMesh(transparentSubMeshes.data[index]);
  8652. }
  8653. }
  8654. };
  8655. this._shadowMap.onClear = function (engine) {
  8656. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  8657. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  8658. }
  8659. else {
  8660. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  8661. }
  8662. };
  8663. }
  8664. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  8665. // Static
  8666. get: function () {
  8667. return ShadowGenerator._FILTER_NONE;
  8668. },
  8669. enumerable: true,
  8670. configurable: true
  8671. });
  8672. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  8673. get: function () {
  8674. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  8675. },
  8676. enumerable: true,
  8677. configurable: true
  8678. });
  8679. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  8680. get: function () {
  8681. return ShadowGenerator._FILTER_POISSONSAMPLING;
  8682. },
  8683. enumerable: true,
  8684. configurable: true
  8685. });
  8686. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  8687. get: function () {
  8688. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  8689. },
  8690. enumerable: true,
  8691. configurable: true
  8692. });
  8693. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  8694. get: function () {
  8695. return this._bias;
  8696. },
  8697. set: function (bias) {
  8698. this._bias = bias;
  8699. },
  8700. enumerable: true,
  8701. configurable: true
  8702. });
  8703. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  8704. get: function () {
  8705. return this._blurBoxOffset;
  8706. },
  8707. set: function (value) {
  8708. var _this = this;
  8709. if (this._blurBoxOffset === value) {
  8710. return;
  8711. }
  8712. this._blurBoxOffset = value;
  8713. if (this._boxBlurPostprocess) {
  8714. this._boxBlurPostprocess.dispose();
  8715. }
  8716. 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);
  8717. this._boxBlurPostprocess.onApply = function (effect) {
  8718. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  8719. };
  8720. },
  8721. enumerable: true,
  8722. configurable: true
  8723. });
  8724. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  8725. get: function () {
  8726. return this._filter;
  8727. },
  8728. set: function (value) {
  8729. if (this._filter === value) {
  8730. return;
  8731. }
  8732. this._filter = value;
  8733. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  8734. this._shadowMap.anisotropicFilteringLevel = 16;
  8735. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  8736. }
  8737. else {
  8738. this._shadowMap.anisotropicFilteringLevel = 1;
  8739. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8740. }
  8741. },
  8742. enumerable: true,
  8743. configurable: true
  8744. });
  8745. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  8746. get: function () {
  8747. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  8748. },
  8749. set: function (value) {
  8750. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  8751. },
  8752. enumerable: true,
  8753. configurable: true
  8754. });
  8755. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  8756. get: function () {
  8757. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  8758. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  8759. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  8760. },
  8761. set: function (value) {
  8762. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  8763. },
  8764. enumerable: true,
  8765. configurable: true
  8766. });
  8767. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  8768. get: function () {
  8769. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  8770. },
  8771. set: function (value) {
  8772. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  8773. },
  8774. enumerable: true,
  8775. configurable: true
  8776. });
  8777. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  8778. var defines = [];
  8779. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  8780. defines.push("#define VSM");
  8781. }
  8782. var attribs = [BABYLON.VertexBuffer.PositionKind];
  8783. var mesh = subMesh.getMesh();
  8784. var material = subMesh.getMaterial();
  8785. // Alpha test
  8786. if (material && material.needAlphaTesting()) {
  8787. defines.push("#define ALPHATEST");
  8788. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  8789. attribs.push(BABYLON.VertexBuffer.UVKind);
  8790. defines.push("#define UV1");
  8791. }
  8792. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  8793. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  8794. defines.push("#define UV2");
  8795. }
  8796. }
  8797. // Bones
  8798. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  8799. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  8800. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  8801. defines.push("#define BONES");
  8802. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  8803. }
  8804. // Instances
  8805. if (useInstances) {
  8806. defines.push("#define INSTANCES");
  8807. attribs.push("world0");
  8808. attribs.push("world1");
  8809. attribs.push("world2");
  8810. attribs.push("world3");
  8811. }
  8812. // Get correct effect
  8813. var join = defines.join("\n");
  8814. if (this._cachedDefines !== join) {
  8815. this._cachedDefines = join;
  8816. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  8817. }
  8818. return this._effect.isReady();
  8819. };
  8820. ShadowGenerator.prototype.getShadowMap = function () {
  8821. return this._shadowMap;
  8822. };
  8823. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  8824. if (this._shadowMap2) {
  8825. return this._shadowMap2;
  8826. }
  8827. return this._shadowMap;
  8828. };
  8829. ShadowGenerator.prototype.getLight = function () {
  8830. return this._light;
  8831. };
  8832. // Methods
  8833. ShadowGenerator.prototype.getTransformMatrix = function () {
  8834. var scene = this._scene;
  8835. if (this._currentRenderID === scene.getRenderId()) {
  8836. return this._transformMatrix;
  8837. }
  8838. this._currentRenderID = scene.getRenderId();
  8839. var lightPosition = this._light.position;
  8840. BABYLON.Vector3.NormalizeToRef(this._light.direction, this._lightDirection);
  8841. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) == 1.0) {
  8842. this._lightDirection.z = 0.0000000000001; // Need to avoid perfectly perpendicular light
  8843. }
  8844. if (this._light.computeTransformedPosition()) {
  8845. lightPosition = this._light.transformedPosition;
  8846. }
  8847. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  8848. this._cachedPosition = lightPosition.clone();
  8849. this._cachedDirection = this._lightDirection.clone();
  8850. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  8851. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  8852. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  8853. }
  8854. return this._transformMatrix;
  8855. };
  8856. ShadowGenerator.prototype.getDarkness = function () {
  8857. return this._darkness;
  8858. };
  8859. ShadowGenerator.prototype.setDarkness = function (darkness) {
  8860. if (darkness >= 1.0)
  8861. this._darkness = 1.0;
  8862. else if (darkness <= 0.0)
  8863. this._darkness = 0.0;
  8864. else
  8865. this._darkness = darkness;
  8866. };
  8867. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  8868. this._transparencyShadow = hasShadow;
  8869. };
  8870. ShadowGenerator.prototype._packHalf = function (depth) {
  8871. var scale = depth * 255.0;
  8872. var fract = scale - Math.floor(scale);
  8873. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  8874. };
  8875. ShadowGenerator.prototype.dispose = function () {
  8876. this._shadowMap.dispose();
  8877. if (this._shadowMap2) {
  8878. this._shadowMap2.dispose();
  8879. }
  8880. if (this._downSamplePostprocess) {
  8881. this._downSamplePostprocess.dispose();
  8882. }
  8883. if (this._boxBlurPostprocess) {
  8884. this._boxBlurPostprocess.dispose();
  8885. }
  8886. };
  8887. ShadowGenerator._FILTER_NONE = 0;
  8888. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  8889. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  8890. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  8891. return ShadowGenerator;
  8892. })();
  8893. BABYLON.ShadowGenerator = ShadowGenerator;
  8894. })(BABYLON || (BABYLON = {}));
  8895. var BABYLON;
  8896. (function (BABYLON) {
  8897. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  8898. if (boxMin.x > sphereCenter.x + sphereRadius)
  8899. return false;
  8900. if (sphereCenter.x - sphereRadius > boxMax.x)
  8901. return false;
  8902. if (boxMin.y > sphereCenter.y + sphereRadius)
  8903. return false;
  8904. if (sphereCenter.y - sphereRadius > boxMax.y)
  8905. return false;
  8906. if (boxMin.z > sphereCenter.z + sphereRadius)
  8907. return false;
  8908. if (sphereCenter.z - sphereRadius > boxMax.z)
  8909. return false;
  8910. return true;
  8911. };
  8912. var getLowestRoot = function (a, b, c, maxR) {
  8913. var determinant = b * b - 4.0 * a * c;
  8914. var result = { root: 0, found: false };
  8915. if (determinant < 0)
  8916. return result;
  8917. var sqrtD = Math.sqrt(determinant);
  8918. var r1 = (-b - sqrtD) / (2.0 * a);
  8919. var r2 = (-b + sqrtD) / (2.0 * a);
  8920. if (r1 > r2) {
  8921. var temp = r2;
  8922. r2 = r1;
  8923. r1 = temp;
  8924. }
  8925. if (r1 > 0 && r1 < maxR) {
  8926. result.root = r1;
  8927. result.found = true;
  8928. return result;
  8929. }
  8930. if (r2 > 0 && r2 < maxR) {
  8931. result.root = r2;
  8932. result.found = true;
  8933. return result;
  8934. }
  8935. return result;
  8936. };
  8937. var Collider = (function () {
  8938. function Collider() {
  8939. this.radius = new BABYLON.Vector3(1, 1, 1);
  8940. this.retry = 0;
  8941. this.basePointWorld = BABYLON.Vector3.Zero();
  8942. this.velocityWorld = BABYLON.Vector3.Zero();
  8943. this.normalizedVelocity = BABYLON.Vector3.Zero();
  8944. this._collisionPoint = BABYLON.Vector3.Zero();
  8945. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  8946. this._tempVector = BABYLON.Vector3.Zero();
  8947. this._tempVector2 = BABYLON.Vector3.Zero();
  8948. this._tempVector3 = BABYLON.Vector3.Zero();
  8949. this._tempVector4 = BABYLON.Vector3.Zero();
  8950. this._edge = BABYLON.Vector3.Zero();
  8951. this._baseToVertex = BABYLON.Vector3.Zero();
  8952. this._destinationPoint = BABYLON.Vector3.Zero();
  8953. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  8954. this._displacementVector = BABYLON.Vector3.Zero();
  8955. }
  8956. // Methods
  8957. Collider.prototype._initialize = function (source, dir, e) {
  8958. this.velocity = dir;
  8959. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  8960. this.basePoint = source;
  8961. source.multiplyToRef(this.radius, this.basePointWorld);
  8962. dir.multiplyToRef(this.radius, this.velocityWorld);
  8963. this.velocityWorldLength = this.velocityWorld.length();
  8964. this.epsilon = e;
  8965. this.collisionFound = false;
  8966. };
  8967. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  8968. pa.subtractToRef(point, this._tempVector);
  8969. pb.subtractToRef(point, this._tempVector2);
  8970. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  8971. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  8972. if (d < 0)
  8973. return false;
  8974. pc.subtractToRef(point, this._tempVector3);
  8975. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  8976. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  8977. if (d < 0)
  8978. return false;
  8979. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  8980. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  8981. return d >= 0;
  8982. };
  8983. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  8984. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  8985. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  8986. if (distance > this.velocityWorldLength + max + sphereRadius) {
  8987. return false;
  8988. }
  8989. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  8990. return false;
  8991. return true;
  8992. };
  8993. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  8994. var t0;
  8995. var embeddedInPlane = false;
  8996. //defensive programming, actually not needed.
  8997. if (!trianglePlaneArray) {
  8998. trianglePlaneArray = [];
  8999. }
  9000. if (!trianglePlaneArray[faceIndex]) {
  9001. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  9002. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  9003. }
  9004. var trianglePlane = trianglePlaneArray[faceIndex];
  9005. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  9006. return;
  9007. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  9008. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  9009. if (normalDotVelocity == 0) {
  9010. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  9011. return;
  9012. embeddedInPlane = true;
  9013. t0 = 0;
  9014. }
  9015. else {
  9016. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9017. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9018. if (t0 > t1) {
  9019. var temp = t1;
  9020. t1 = t0;
  9021. t0 = temp;
  9022. }
  9023. if (t0 > 1.0 || t1 < 0.0)
  9024. return;
  9025. if (t0 < 0)
  9026. t0 = 0;
  9027. if (t0 > 1.0)
  9028. t0 = 1.0;
  9029. }
  9030. this._collisionPoint.copyFromFloats(0, 0, 0);
  9031. var found = false;
  9032. var t = 1.0;
  9033. if (!embeddedInPlane) {
  9034. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  9035. this.velocity.scaleToRef(t0, this._tempVector);
  9036. this._planeIntersectionPoint.addInPlace(this._tempVector);
  9037. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  9038. found = true;
  9039. t = t0;
  9040. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  9041. }
  9042. }
  9043. if (!found) {
  9044. var velocitySquaredLength = this.velocity.lengthSquared();
  9045. var a = velocitySquaredLength;
  9046. this.basePoint.subtractToRef(p1, this._tempVector);
  9047. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9048. var c = this._tempVector.lengthSquared() - 1.0;
  9049. var lowestRoot = getLowestRoot(a, b, c, t);
  9050. if (lowestRoot.found) {
  9051. t = lowestRoot.root;
  9052. found = true;
  9053. this._collisionPoint.copyFrom(p1);
  9054. }
  9055. this.basePoint.subtractToRef(p2, this._tempVector);
  9056. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9057. c = this._tempVector.lengthSquared() - 1.0;
  9058. lowestRoot = getLowestRoot(a, b, c, t);
  9059. if (lowestRoot.found) {
  9060. t = lowestRoot.root;
  9061. found = true;
  9062. this._collisionPoint.copyFrom(p2);
  9063. }
  9064. this.basePoint.subtractToRef(p3, this._tempVector);
  9065. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9066. c = this._tempVector.lengthSquared() - 1.0;
  9067. lowestRoot = getLowestRoot(a, b, c, t);
  9068. if (lowestRoot.found) {
  9069. t = lowestRoot.root;
  9070. found = true;
  9071. this._collisionPoint.copyFrom(p3);
  9072. }
  9073. p2.subtractToRef(p1, this._edge);
  9074. p1.subtractToRef(this.basePoint, this._baseToVertex);
  9075. var edgeSquaredLength = this._edge.lengthSquared();
  9076. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9077. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9078. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9079. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9080. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9081. lowestRoot = getLowestRoot(a, b, c, t);
  9082. if (lowestRoot.found) {
  9083. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9084. if (f >= 0.0 && f <= 1.0) {
  9085. t = lowestRoot.root;
  9086. found = true;
  9087. this._edge.scaleInPlace(f);
  9088. p1.addToRef(this._edge, this._collisionPoint);
  9089. }
  9090. }
  9091. p3.subtractToRef(p2, this._edge);
  9092. p2.subtractToRef(this.basePoint, this._baseToVertex);
  9093. edgeSquaredLength = this._edge.lengthSquared();
  9094. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9095. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9096. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9097. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9098. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9099. lowestRoot = getLowestRoot(a, b, c, t);
  9100. if (lowestRoot.found) {
  9101. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9102. if (f >= 0.0 && f <= 1.0) {
  9103. t = lowestRoot.root;
  9104. found = true;
  9105. this._edge.scaleInPlace(f);
  9106. p2.addToRef(this._edge, this._collisionPoint);
  9107. }
  9108. }
  9109. p1.subtractToRef(p3, this._edge);
  9110. p3.subtractToRef(this.basePoint, this._baseToVertex);
  9111. edgeSquaredLength = this._edge.lengthSquared();
  9112. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9113. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9114. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9115. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9116. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9117. lowestRoot = getLowestRoot(a, b, c, t);
  9118. if (lowestRoot.found) {
  9119. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9120. if (f >= 0.0 && f <= 1.0) {
  9121. t = lowestRoot.root;
  9122. found = true;
  9123. this._edge.scaleInPlace(f);
  9124. p3.addToRef(this._edge, this._collisionPoint);
  9125. }
  9126. }
  9127. }
  9128. if (found) {
  9129. var distToCollision = t * this.velocity.length();
  9130. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  9131. if (!this.intersectionPoint) {
  9132. this.intersectionPoint = this._collisionPoint.clone();
  9133. }
  9134. else {
  9135. this.intersectionPoint.copyFrom(this._collisionPoint);
  9136. }
  9137. this.nearestDistance = distToCollision;
  9138. this.collisionFound = true;
  9139. }
  9140. }
  9141. };
  9142. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  9143. for (var i = indexStart; i < indexEnd; i += 3) {
  9144. var p1 = pts[indices[i] - decal];
  9145. var p2 = pts[indices[i + 1] - decal];
  9146. var p3 = pts[indices[i + 2] - decal];
  9147. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  9148. }
  9149. };
  9150. Collider.prototype._getResponse = function (pos, vel) {
  9151. pos.addToRef(vel, this._destinationPoint);
  9152. vel.scaleInPlace((this.nearestDistance / vel.length()));
  9153. this.basePoint.addToRef(vel, pos);
  9154. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  9155. this._slidePlaneNormal.normalize();
  9156. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  9157. pos.addInPlace(this._displacementVector);
  9158. this.intersectionPoint.addInPlace(this._displacementVector);
  9159. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  9160. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  9161. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  9162. };
  9163. return Collider;
  9164. })();
  9165. BABYLON.Collider = Collider;
  9166. })(BABYLON || (BABYLON = {}));
  9167. var BABYLON;
  9168. (function (BABYLON) {
  9169. //WebWorker code will be inserted to this variable.
  9170. BABYLON.CollisionWorker = "";
  9171. (function (WorkerTaskType) {
  9172. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  9173. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  9174. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  9175. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  9176. var WorkerTaskType = BABYLON.WorkerTaskType;
  9177. (function (WorkerReplyType) {
  9178. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  9179. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  9180. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  9181. var WorkerReplyType = BABYLON.WorkerReplyType;
  9182. var CollisionCoordinatorWorker = (function () {
  9183. function CollisionCoordinatorWorker() {
  9184. var _this = this;
  9185. this._scaledPosition = BABYLON.Vector3.Zero();
  9186. this._scaledVelocity = BABYLON.Vector3.Zero();
  9187. this.onMeshUpdated = function (mesh) {
  9188. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  9189. };
  9190. this.onGeometryUpdated = function (geometry) {
  9191. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  9192. };
  9193. this._afterRender = function () {
  9194. if (!_this._init)
  9195. return;
  9196. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  9197. return;
  9198. }
  9199. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  9200. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  9201. if (_this._runningUpdated > 4) {
  9202. return;
  9203. }
  9204. ++_this._runningUpdated;
  9205. var payload = {
  9206. updatedMeshes: _this._addUpdateMeshesList,
  9207. updatedGeometries: _this._addUpdateGeometriesList,
  9208. removedGeometries: _this._toRemoveGeometryArray,
  9209. removedMeshes: _this._toRemoveMeshesArray
  9210. };
  9211. var message = {
  9212. payload: payload,
  9213. taskType: WorkerTaskType.UPDATE
  9214. };
  9215. var serializable = [];
  9216. for (var id in payload.updatedGeometries) {
  9217. if (payload.updatedGeometries.hasOwnProperty(id)) {
  9218. //prepare transferables
  9219. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  9220. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  9221. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  9222. }
  9223. }
  9224. _this._worker.postMessage(message, serializable);
  9225. _this._addUpdateMeshesList = {};
  9226. _this._addUpdateGeometriesList = {};
  9227. _this._toRemoveGeometryArray = [];
  9228. _this._toRemoveMeshesArray = [];
  9229. };
  9230. this._onMessageFromWorker = function (e) {
  9231. var returnData = e.data;
  9232. if (returnData.error != WorkerReplyType.SUCCESS) {
  9233. //TODO what errors can be returned from the worker?
  9234. BABYLON.Tools.Warn("error returned from worker!");
  9235. return;
  9236. }
  9237. switch (returnData.taskType) {
  9238. case WorkerTaskType.INIT:
  9239. _this._init = true;
  9240. //Update the worked with ALL of the scene's current state
  9241. _this._scene.meshes.forEach(function (mesh) {
  9242. _this.onMeshAdded(mesh);
  9243. });
  9244. _this._scene.getGeometries().forEach(function (geometry) {
  9245. _this.onGeometryAdded(geometry);
  9246. });
  9247. break;
  9248. case WorkerTaskType.UPDATE:
  9249. _this._runningUpdated--;
  9250. break;
  9251. case WorkerTaskType.COLLIDE:
  9252. _this._runningCollisionTask = false;
  9253. var returnPayload = returnData.payload;
  9254. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  9255. return;
  9256. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  9257. //cleanup
  9258. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  9259. break;
  9260. }
  9261. };
  9262. this._collisionsCallbackArray = [];
  9263. this._init = false;
  9264. this._runningUpdated = 0;
  9265. this._runningCollisionTask = false;
  9266. this._addUpdateMeshesList = {};
  9267. this._addUpdateGeometriesList = {};
  9268. this._toRemoveGeometryArray = [];
  9269. this._toRemoveMeshesArray = [];
  9270. }
  9271. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9272. if (!this._init)
  9273. return;
  9274. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  9275. return;
  9276. position.divideToRef(collider.radius, this._scaledPosition);
  9277. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9278. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  9279. var payload = {
  9280. collider: {
  9281. position: this._scaledPosition.asArray(),
  9282. velocity: this._scaledVelocity.asArray(),
  9283. radius: collider.radius.asArray()
  9284. },
  9285. collisionId: collisionIndex,
  9286. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  9287. maximumRetry: maximumRetry
  9288. };
  9289. var message = {
  9290. payload: payload,
  9291. taskType: WorkerTaskType.COLLIDE
  9292. };
  9293. this._worker.postMessage(message);
  9294. };
  9295. CollisionCoordinatorWorker.prototype.init = function (scene) {
  9296. this._scene = scene;
  9297. this._scene.registerAfterRender(this._afterRender);
  9298. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  9299. this._worker = new Worker(workerUrl);
  9300. this._worker.onmessage = this._onMessageFromWorker;
  9301. var message = {
  9302. payload: {},
  9303. taskType: WorkerTaskType.INIT
  9304. };
  9305. this._worker.postMessage(message);
  9306. };
  9307. CollisionCoordinatorWorker.prototype.destroy = function () {
  9308. this._scene.unregisterAfterRender(this._afterRender);
  9309. this._worker.terminate();
  9310. };
  9311. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  9312. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  9313. this.onMeshUpdated(mesh);
  9314. };
  9315. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  9316. this._toRemoveMeshesArray.push(mesh.uniqueId);
  9317. };
  9318. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  9319. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  9320. geometry.onGeometryUpdated = this.onGeometryUpdated;
  9321. this.onGeometryUpdated(geometry);
  9322. };
  9323. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  9324. this._toRemoveGeometryArray.push(geometry.id);
  9325. };
  9326. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  9327. var submeshes = [];
  9328. if (mesh.subMeshes) {
  9329. submeshes = mesh.subMeshes.map(function (sm, idx) {
  9330. return {
  9331. position: idx,
  9332. verticesStart: sm.verticesStart,
  9333. verticesCount: sm.verticesCount,
  9334. indexStart: sm.indexStart,
  9335. indexCount: sm.indexCount,
  9336. hasMaterial: !!sm.getMaterial(),
  9337. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9338. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  9339. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9340. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  9341. };
  9342. });
  9343. }
  9344. var geometryId = null;
  9345. if (mesh instanceof BABYLON.Mesh) {
  9346. geometryId = mesh.geometry ? mesh.geometry.id : null;
  9347. }
  9348. else if (mesh instanceof BABYLON.InstancedMesh) {
  9349. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  9350. }
  9351. return {
  9352. uniqueId: mesh.uniqueId,
  9353. id: mesh.id,
  9354. name: mesh.name,
  9355. geometryId: geometryId,
  9356. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9357. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  9358. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9359. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  9360. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  9361. subMeshes: submeshes,
  9362. checkCollisions: mesh.checkCollisions
  9363. };
  9364. };
  9365. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  9366. return {
  9367. id: geometry.id,
  9368. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  9369. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  9370. indices: new Int32Array(geometry.getIndices() || []),
  9371. };
  9372. };
  9373. return CollisionCoordinatorWorker;
  9374. })();
  9375. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  9376. var CollisionCoordinatorLegacy = (function () {
  9377. function CollisionCoordinatorLegacy() {
  9378. this._scaledPosition = BABYLON.Vector3.Zero();
  9379. this._scaledVelocity = BABYLON.Vector3.Zero();
  9380. this._finalPosition = BABYLON.Vector3.Zero();
  9381. }
  9382. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9383. position.divideToRef(collider.radius, this._scaledPosition);
  9384. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9385. collider.collidedMesh = null;
  9386. collider.retry = 0;
  9387. collider.initialVelocity = this._scaledVelocity;
  9388. collider.initialPosition = this._scaledPosition;
  9389. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  9390. this._finalPosition.multiplyInPlace(collider.radius);
  9391. //run the callback
  9392. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  9393. };
  9394. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  9395. this._scene = scene;
  9396. };
  9397. CollisionCoordinatorLegacy.prototype.destroy = function () {
  9398. //Legacy need no destruction method.
  9399. };
  9400. //No update in legacy mode
  9401. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  9402. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  9403. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  9404. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  9405. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  9406. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  9407. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9408. if (excludedMesh === void 0) { excludedMesh = null; }
  9409. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  9410. if (collider.retry >= maximumRetry) {
  9411. finalPosition.copyFrom(position);
  9412. return;
  9413. }
  9414. collider._initialize(position, velocity, closeDistance);
  9415. // Check all meshes
  9416. for (var index = 0; index < this._scene.meshes.length; index++) {
  9417. var mesh = this._scene.meshes[index];
  9418. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  9419. mesh._checkCollision(collider);
  9420. }
  9421. }
  9422. if (!collider.collisionFound) {
  9423. position.addToRef(velocity, finalPosition);
  9424. return;
  9425. }
  9426. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  9427. collider._getResponse(position, velocity);
  9428. }
  9429. if (velocity.length() <= closeDistance) {
  9430. finalPosition.copyFrom(position);
  9431. return;
  9432. }
  9433. collider.retry++;
  9434. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  9435. };
  9436. return CollisionCoordinatorLegacy;
  9437. })();
  9438. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  9439. })(BABYLON || (BABYLON = {}));
  9440. var BABYLON;
  9441. (function (BABYLON) {
  9442. var VRCameraMetrics = (function () {
  9443. function VRCameraMetrics() {
  9444. this.compensateDistortion = true;
  9445. }
  9446. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  9447. get: function () {
  9448. return this.hResolution / (2 * this.vResolution);
  9449. },
  9450. enumerable: true,
  9451. configurable: true
  9452. });
  9453. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  9454. get: function () {
  9455. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  9456. },
  9457. enumerable: true,
  9458. configurable: true
  9459. });
  9460. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  9461. get: function () {
  9462. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  9463. var h = (4 * meters) / this.hScreenSize;
  9464. return BABYLON.Matrix.Translation(h, 0, 0);
  9465. },
  9466. enumerable: true,
  9467. configurable: true
  9468. });
  9469. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  9470. get: function () {
  9471. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  9472. var h = (4 * meters) / this.hScreenSize;
  9473. return BABYLON.Matrix.Translation(-h, 0, 0);
  9474. },
  9475. enumerable: true,
  9476. configurable: true
  9477. });
  9478. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  9479. get: function () {
  9480. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  9481. },
  9482. enumerable: true,
  9483. configurable: true
  9484. });
  9485. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  9486. get: function () {
  9487. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  9488. },
  9489. enumerable: true,
  9490. configurable: true
  9491. });
  9492. VRCameraMetrics.GetDefault = function () {
  9493. var result = new VRCameraMetrics();
  9494. result.hResolution = 1280;
  9495. result.vResolution = 800;
  9496. result.hScreenSize = 0.149759993;
  9497. result.vScreenSize = 0.0935999975;
  9498. result.vScreenCenter = 0.0467999987,
  9499. result.eyeToScreenDistance = 0.0410000011;
  9500. result.lensSeparationDistance = 0.0635000020;
  9501. result.interpupillaryDistance = 0.0640000030;
  9502. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  9503. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  9504. result.postProcessScaleFactor = 1.714605507808412;
  9505. result.lensCenterOffset = 0.151976421;
  9506. return result;
  9507. };
  9508. return VRCameraMetrics;
  9509. })();
  9510. BABYLON.VRCameraMetrics = VRCameraMetrics;
  9511. var Camera = (function (_super) {
  9512. __extends(Camera, _super);
  9513. function Camera(name, position, scene) {
  9514. _super.call(this, name, scene);
  9515. this.position = position;
  9516. // Members
  9517. this.upVector = BABYLON.Vector3.Up();
  9518. this.orthoLeft = null;
  9519. this.orthoRight = null;
  9520. this.orthoBottom = null;
  9521. this.orthoTop = null;
  9522. this.fov = 0.8;
  9523. this.minZ = 1.0;
  9524. this.maxZ = 10000.0;
  9525. this.inertia = 0.9;
  9526. this.mode = Camera.PERSPECTIVE_CAMERA;
  9527. this.isIntermediate = false;
  9528. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  9529. this.layerMask = 0x0FFFFFFF;
  9530. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  9531. // Camera rig members
  9532. this.cameraRigMode = Camera.RIG_MODE_NONE;
  9533. this._rigCameras = new Array();
  9534. // Cache
  9535. this._computedViewMatrix = BABYLON.Matrix.Identity();
  9536. this._projectionMatrix = new BABYLON.Matrix();
  9537. this._postProcesses = new Array();
  9538. this._postProcessesTakenIndices = [];
  9539. this._activeMeshes = new BABYLON.SmartArray(256);
  9540. this._globalPosition = BABYLON.Vector3.Zero();
  9541. scene.addCamera(this);
  9542. if (!scene.activeCamera) {
  9543. scene.activeCamera = this;
  9544. }
  9545. }
  9546. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  9547. get: function () {
  9548. return Camera._PERSPECTIVE_CAMERA;
  9549. },
  9550. enumerable: true,
  9551. configurable: true
  9552. });
  9553. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  9554. get: function () {
  9555. return Camera._ORTHOGRAPHIC_CAMERA;
  9556. },
  9557. enumerable: true,
  9558. configurable: true
  9559. });
  9560. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  9561. get: function () {
  9562. return Camera._FOVMODE_VERTICAL_FIXED;
  9563. },
  9564. enumerable: true,
  9565. configurable: true
  9566. });
  9567. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  9568. get: function () {
  9569. return Camera._FOVMODE_HORIZONTAL_FIXED;
  9570. },
  9571. enumerable: true,
  9572. configurable: true
  9573. });
  9574. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  9575. get: function () {
  9576. return Camera._RIG_MODE_NONE;
  9577. },
  9578. enumerable: true,
  9579. configurable: true
  9580. });
  9581. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  9582. get: function () {
  9583. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  9584. },
  9585. enumerable: true,
  9586. configurable: true
  9587. });
  9588. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  9589. get: function () {
  9590. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  9591. },
  9592. enumerable: true,
  9593. configurable: true
  9594. });
  9595. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  9596. get: function () {
  9597. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  9598. },
  9599. enumerable: true,
  9600. configurable: true
  9601. });
  9602. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  9603. get: function () {
  9604. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  9605. },
  9606. enumerable: true,
  9607. configurable: true
  9608. });
  9609. Object.defineProperty(Camera, "RIG_MODE_VR", {
  9610. get: function () {
  9611. return Camera._RIG_MODE_VR;
  9612. },
  9613. enumerable: true,
  9614. configurable: true
  9615. });
  9616. Object.defineProperty(Camera.prototype, "globalPosition", {
  9617. get: function () {
  9618. return this._globalPosition;
  9619. },
  9620. enumerable: true,
  9621. configurable: true
  9622. });
  9623. Camera.prototype.getActiveMeshes = function () {
  9624. return this._activeMeshes;
  9625. };
  9626. Camera.prototype.isActiveMesh = function (mesh) {
  9627. return (this._activeMeshes.indexOf(mesh) !== -1);
  9628. };
  9629. //Cache
  9630. Camera.prototype._initCache = function () {
  9631. _super.prototype._initCache.call(this);
  9632. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9633. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9634. this._cache.mode = undefined;
  9635. this._cache.minZ = undefined;
  9636. this._cache.maxZ = undefined;
  9637. this._cache.fov = undefined;
  9638. this._cache.aspectRatio = undefined;
  9639. this._cache.orthoLeft = undefined;
  9640. this._cache.orthoRight = undefined;
  9641. this._cache.orthoBottom = undefined;
  9642. this._cache.orthoTop = undefined;
  9643. this._cache.renderWidth = undefined;
  9644. this._cache.renderHeight = undefined;
  9645. };
  9646. Camera.prototype._updateCache = function (ignoreParentClass) {
  9647. if (!ignoreParentClass) {
  9648. _super.prototype._updateCache.call(this);
  9649. }
  9650. var engine = this.getEngine();
  9651. this._cache.position.copyFrom(this.position);
  9652. this._cache.upVector.copyFrom(this.upVector);
  9653. this._cache.mode = this.mode;
  9654. this._cache.minZ = this.minZ;
  9655. this._cache.maxZ = this.maxZ;
  9656. this._cache.fov = this.fov;
  9657. this._cache.aspectRatio = engine.getAspectRatio(this);
  9658. this._cache.orthoLeft = this.orthoLeft;
  9659. this._cache.orthoRight = this.orthoRight;
  9660. this._cache.orthoBottom = this.orthoBottom;
  9661. this._cache.orthoTop = this.orthoTop;
  9662. this._cache.renderWidth = engine.getRenderWidth();
  9663. this._cache.renderHeight = engine.getRenderHeight();
  9664. };
  9665. Camera.prototype._updateFromScene = function () {
  9666. this.updateCache();
  9667. this._update();
  9668. };
  9669. // Synchronized
  9670. Camera.prototype._isSynchronized = function () {
  9671. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  9672. };
  9673. Camera.prototype._isSynchronizedViewMatrix = function () {
  9674. if (!_super.prototype._isSynchronized.call(this))
  9675. return false;
  9676. return this._cache.position.equals(this.position)
  9677. && this._cache.upVector.equals(this.upVector)
  9678. && this.isSynchronizedWithParent();
  9679. };
  9680. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  9681. var check = this._cache.mode === this.mode
  9682. && this._cache.minZ === this.minZ
  9683. && this._cache.maxZ === this.maxZ;
  9684. if (!check) {
  9685. return false;
  9686. }
  9687. var engine = this.getEngine();
  9688. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  9689. check = this._cache.fov === this.fov
  9690. && this._cache.aspectRatio === engine.getAspectRatio(this);
  9691. }
  9692. else {
  9693. check = this._cache.orthoLeft === this.orthoLeft
  9694. && this._cache.orthoRight === this.orthoRight
  9695. && this._cache.orthoBottom === this.orthoBottom
  9696. && this._cache.orthoTop === this.orthoTop
  9697. && this._cache.renderWidth === engine.getRenderWidth()
  9698. && this._cache.renderHeight === engine.getRenderHeight();
  9699. }
  9700. return check;
  9701. };
  9702. // Controls
  9703. Camera.prototype.attachControl = function (element) {
  9704. };
  9705. Camera.prototype.detachControl = function (element) {
  9706. };
  9707. Camera.prototype._update = function () {
  9708. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  9709. this._updateRigCameras();
  9710. }
  9711. this._checkInputs();
  9712. };
  9713. Camera.prototype._checkInputs = function () {
  9714. };
  9715. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  9716. if (insertAt === void 0) { insertAt = null; }
  9717. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  9718. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  9719. return 0;
  9720. }
  9721. if (insertAt == null || insertAt < 0) {
  9722. this._postProcesses.push(postProcess);
  9723. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  9724. return this._postProcesses.length - 1;
  9725. }
  9726. var add = 0;
  9727. var i;
  9728. var start;
  9729. if (this._postProcesses[insertAt]) {
  9730. start = this._postProcesses.length - 1;
  9731. for (i = start; i >= insertAt + 1; --i) {
  9732. this._postProcesses[i + 1] = this._postProcesses[i];
  9733. }
  9734. add = 1;
  9735. }
  9736. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  9737. if (this._postProcessesTakenIndices[i] < insertAt) {
  9738. continue;
  9739. }
  9740. start = this._postProcessesTakenIndices.length - 1;
  9741. for (var j = start; j >= i; --j) {
  9742. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  9743. }
  9744. this._postProcessesTakenIndices[i] = insertAt;
  9745. break;
  9746. }
  9747. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) === -1) {
  9748. this._postProcessesTakenIndices.push(insertAt);
  9749. }
  9750. var result = insertAt + add;
  9751. this._postProcesses[result] = postProcess;
  9752. return result;
  9753. };
  9754. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  9755. if (atIndices === void 0) { atIndices = null; }
  9756. var result = [];
  9757. var i;
  9758. var index;
  9759. if (!atIndices) {
  9760. var length = this._postProcesses.length;
  9761. for (i = 0; i < length; i++) {
  9762. if (this._postProcesses[i] !== postProcess) {
  9763. continue;
  9764. }
  9765. delete this._postProcesses[i];
  9766. index = this._postProcessesTakenIndices.indexOf(i);
  9767. this._postProcessesTakenIndices.splice(index, 1);
  9768. }
  9769. }
  9770. else {
  9771. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  9772. for (i = 0; i < atIndices.length; i++) {
  9773. var foundPostProcess = this._postProcesses[atIndices[i]];
  9774. if (foundPostProcess !== postProcess) {
  9775. result.push(i);
  9776. continue;
  9777. }
  9778. delete this._postProcesses[atIndices[i]];
  9779. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  9780. this._postProcessesTakenIndices.splice(index, 1);
  9781. }
  9782. }
  9783. return result;
  9784. };
  9785. Camera.prototype.getWorldMatrix = function () {
  9786. if (!this._worldMatrix) {
  9787. this._worldMatrix = BABYLON.Matrix.Identity();
  9788. }
  9789. var viewMatrix = this.getViewMatrix();
  9790. viewMatrix.invertToRef(this._worldMatrix);
  9791. return this._worldMatrix;
  9792. };
  9793. Camera.prototype._getViewMatrix = function () {
  9794. return BABYLON.Matrix.Identity();
  9795. };
  9796. Camera.prototype.getViewMatrix = function (force) {
  9797. this._computedViewMatrix = this._computeViewMatrix(force);
  9798. if (!force && this._isSynchronizedViewMatrix()) {
  9799. return this._computedViewMatrix;
  9800. }
  9801. if (!this.parent || !this.parent.getWorldMatrix) {
  9802. this._globalPosition.copyFrom(this.position);
  9803. }
  9804. else {
  9805. if (!this._worldMatrix) {
  9806. this._worldMatrix = BABYLON.Matrix.Identity();
  9807. }
  9808. this._computedViewMatrix.invertToRef(this._worldMatrix);
  9809. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  9810. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  9811. this._computedViewMatrix.invert();
  9812. this._markSyncedWithParent();
  9813. }
  9814. this._currentRenderId = this.getScene().getRenderId();
  9815. return this._computedViewMatrix;
  9816. };
  9817. Camera.prototype._computeViewMatrix = function (force) {
  9818. if (!force && this._isSynchronizedViewMatrix()) {
  9819. return this._computedViewMatrix;
  9820. }
  9821. this._computedViewMatrix = this._getViewMatrix();
  9822. this._currentRenderId = this.getScene().getRenderId();
  9823. return this._computedViewMatrix;
  9824. };
  9825. Camera.prototype.getProjectionMatrix = function (force) {
  9826. if (!force && this._isSynchronizedProjectionMatrix()) {
  9827. return this._projectionMatrix;
  9828. }
  9829. var engine = this.getEngine();
  9830. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  9831. if (this.minZ <= 0) {
  9832. this.minZ = 0.1;
  9833. }
  9834. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
  9835. return this._projectionMatrix;
  9836. }
  9837. var halfWidth = engine.getRenderWidth() / 2.0;
  9838. var halfHeight = engine.getRenderHeight() / 2.0;
  9839. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  9840. return this._projectionMatrix;
  9841. };
  9842. Camera.prototype.dispose = function () {
  9843. // Animations
  9844. this.getScene().stopAnimation(this);
  9845. // Remove from scene
  9846. this.getScene().removeCamera(this);
  9847. while (this._rigCameras.length > 0) {
  9848. this._rigCameras.pop().dispose();
  9849. }
  9850. // Postprocesses
  9851. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  9852. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  9853. }
  9854. };
  9855. // ---- Camera rigs section ----
  9856. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  9857. while (this._rigCameras.length > 0) {
  9858. this._rigCameras.pop().dispose();
  9859. }
  9860. this.cameraRigMode = mode;
  9861. this._cameraRigParams = {};
  9862. switch (this.cameraRigMode) {
  9863. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  9864. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  9865. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  9866. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  9867. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  9868. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  9869. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  9870. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  9871. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  9872. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  9873. break;
  9874. }
  9875. var postProcesses = new Array();
  9876. switch (this.cameraRigMode) {
  9877. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  9878. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]));
  9879. this._rigCameras[0].isIntermediate = true;
  9880. postProcesses.push(new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras[1]));
  9881. postProcesses[1].onApply = function (effect) {
  9882. effect.setTextureFromPostProcess("leftSampler", postProcesses[0]);
  9883. };
  9884. break;
  9885. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  9886. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  9887. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  9888. var isStereoscopicHoriz = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED);
  9889. var firstCamIndex = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : 0;
  9890. var secondCamIndex = 1 - firstCamIndex;
  9891. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[firstCamIndex]));
  9892. this._rigCameras[firstCamIndex].isIntermediate = true;
  9893. postProcesses.push(new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras[secondCamIndex], postProcesses[0], isStereoscopicHoriz));
  9894. break;
  9895. case Camera.RIG_MODE_VR:
  9896. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  9897. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  9898. var metrics = rigParams.vrCameraMetrics || VRCameraMetrics.GetDefault();
  9899. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  9900. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  9901. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  9902. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  9903. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  9904. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  9905. if (metrics.compensateDistortion) {
  9906. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics));
  9907. }
  9908. this._rigCameras[1]._cameraRigParams.vrMetrics = this._rigCameras[0]._cameraRigParams.vrMetrics;
  9909. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  9910. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  9911. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  9912. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  9913. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  9914. if (metrics.compensateDistortion) {
  9915. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics));
  9916. }
  9917. break;
  9918. }
  9919. this._update();
  9920. };
  9921. Camera.prototype._getVRProjectionMatrix = function () {
  9922. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  9923. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  9924. return this._projectionMatrix;
  9925. };
  9926. Camera.prototype.setCameraRigParameter = function (name, value) {
  9927. this._cameraRigParams[name] = value;
  9928. //provisionnally:
  9929. if (name === "interaxialDistance") {
  9930. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  9931. }
  9932. };
  9933. /**
  9934. * May needs to be overridden by children so sub has required properties to be copied
  9935. */
  9936. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  9937. return null;
  9938. };
  9939. /**
  9940. * May needs to be overridden by children
  9941. */
  9942. Camera.prototype._updateRigCameras = function () {
  9943. for (var i = 0; i < this._rigCameras.length; i++) {
  9944. this._rigCameras[i].minZ = this.minZ;
  9945. this._rigCameras[i].maxZ = this.maxZ;
  9946. this._rigCameras[i].fov = this.fov;
  9947. }
  9948. // only update viewport when ANAGLYPH
  9949. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  9950. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  9951. }
  9952. };
  9953. // Statics
  9954. Camera._PERSPECTIVE_CAMERA = 0;
  9955. Camera._ORTHOGRAPHIC_CAMERA = 1;
  9956. Camera._FOVMODE_VERTICAL_FIXED = 0;
  9957. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  9958. Camera._RIG_MODE_NONE = 0;
  9959. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  9960. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  9961. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  9962. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  9963. Camera._RIG_MODE_VR = 20;
  9964. return Camera;
  9965. })(BABYLON.Node);
  9966. BABYLON.Camera = Camera;
  9967. })(BABYLON || (BABYLON = {}));
  9968. var BABYLON;
  9969. (function (BABYLON) {
  9970. var TargetCamera = (function (_super) {
  9971. __extends(TargetCamera, _super);
  9972. function TargetCamera(name, position, scene) {
  9973. _super.call(this, name, position, scene);
  9974. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  9975. this.cameraRotation = new BABYLON.Vector2(0, 0);
  9976. this.rotation = new BABYLON.Vector3(0, 0, 0);
  9977. this.speed = 2.0;
  9978. this.noRotationConstraint = false;
  9979. this.lockedTarget = null;
  9980. this._currentTarget = BABYLON.Vector3.Zero();
  9981. this._viewMatrix = BABYLON.Matrix.Zero();
  9982. this._camMatrix = BABYLON.Matrix.Zero();
  9983. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  9984. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  9985. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  9986. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  9987. this._lookAtTemp = BABYLON.Matrix.Zero();
  9988. this._tempMatrix = BABYLON.Matrix.Zero();
  9989. }
  9990. TargetCamera.prototype.getFrontPosition = function (distance) {
  9991. var direction = this.getTarget().subtract(this.position);
  9992. direction.normalize();
  9993. direction.scaleInPlace(distance);
  9994. return this.globalPosition.add(direction);
  9995. };
  9996. TargetCamera.prototype._getLockedTargetPosition = function () {
  9997. if (!this.lockedTarget) {
  9998. return null;
  9999. }
  10000. return this.lockedTarget.position || this.lockedTarget;
  10001. };
  10002. // Cache
  10003. TargetCamera.prototype._initCache = function () {
  10004. _super.prototype._initCache.call(this);
  10005. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10006. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10007. };
  10008. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  10009. if (!ignoreParentClass) {
  10010. _super.prototype._updateCache.call(this);
  10011. }
  10012. var lockedTargetPosition = this._getLockedTargetPosition();
  10013. if (!lockedTargetPosition) {
  10014. this._cache.lockedTarget = null;
  10015. }
  10016. else {
  10017. if (!this._cache.lockedTarget) {
  10018. this._cache.lockedTarget = lockedTargetPosition.clone();
  10019. }
  10020. else {
  10021. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  10022. }
  10023. }
  10024. this._cache.rotation.copyFrom(this.rotation);
  10025. };
  10026. // Synchronized
  10027. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  10028. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  10029. return false;
  10030. }
  10031. var lockedTargetPosition = this._getLockedTargetPosition();
  10032. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  10033. && this._cache.rotation.equals(this.rotation);
  10034. };
  10035. // Methods
  10036. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  10037. var engine = this.getEngine();
  10038. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  10039. };
  10040. // Target
  10041. TargetCamera.prototype.setTarget = function (target) {
  10042. this.upVector.normalize();
  10043. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  10044. this._camMatrix.invert();
  10045. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  10046. var vDir = target.subtract(this.position);
  10047. if (vDir.x >= 0.0) {
  10048. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  10049. }
  10050. else {
  10051. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  10052. }
  10053. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  10054. if (isNaN(this.rotation.x)) {
  10055. this.rotation.x = 0;
  10056. }
  10057. if (isNaN(this.rotation.y)) {
  10058. this.rotation.y = 0;
  10059. }
  10060. if (isNaN(this.rotation.z)) {
  10061. this.rotation.z = 0;
  10062. }
  10063. };
  10064. TargetCamera.prototype.getTarget = function () {
  10065. return this._currentTarget;
  10066. };
  10067. TargetCamera.prototype._decideIfNeedsToMove = function () {
  10068. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10069. };
  10070. TargetCamera.prototype._updatePosition = function () {
  10071. this.position.addInPlace(this.cameraDirection);
  10072. };
  10073. TargetCamera.prototype._checkInputs = function () {
  10074. var needToMove = this._decideIfNeedsToMove();
  10075. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  10076. // Move
  10077. if (needToMove) {
  10078. this._updatePosition();
  10079. }
  10080. // Rotate
  10081. if (needToRotate) {
  10082. this.rotation.x += this.cameraRotation.x;
  10083. this.rotation.y += this.cameraRotation.y;
  10084. if (!this.noRotationConstraint) {
  10085. var limit = (Math.PI / 2) * 0.95;
  10086. if (this.rotation.x > limit)
  10087. this.rotation.x = limit;
  10088. if (this.rotation.x < -limit)
  10089. this.rotation.x = -limit;
  10090. }
  10091. }
  10092. // Inertia
  10093. if (needToMove) {
  10094. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  10095. this.cameraDirection.x = 0;
  10096. }
  10097. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  10098. this.cameraDirection.y = 0;
  10099. }
  10100. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  10101. this.cameraDirection.z = 0;
  10102. }
  10103. this.cameraDirection.scaleInPlace(this.inertia);
  10104. }
  10105. if (needToRotate) {
  10106. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  10107. this.cameraRotation.x = 0;
  10108. }
  10109. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  10110. this.cameraRotation.y = 0;
  10111. }
  10112. this.cameraRotation.scaleInPlace(this.inertia);
  10113. }
  10114. _super.prototype._checkInputs.call(this);
  10115. };
  10116. TargetCamera.prototype._getViewMatrix = function () {
  10117. if (!this.lockedTarget) {
  10118. // Compute
  10119. if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
  10120. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  10121. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10122. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  10123. this._lookAtTemp.invert();
  10124. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  10125. }
  10126. else {
  10127. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10128. }
  10129. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10130. // Computing target and final matrix
  10131. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10132. }
  10133. else {
  10134. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  10135. }
  10136. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  10137. return this._viewMatrix;
  10138. };
  10139. TargetCamera.prototype._getVRViewMatrix = function () {
  10140. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10141. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10142. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._cameraRigParams.vrActualUp);
  10143. // Computing target and final matrix
  10144. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10145. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._cameraRigParams.vrActualUp, this._cameraRigParams.vrWorkMatrix);
  10146. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._viewMatrix);
  10147. return this._viewMatrix;
  10148. };
  10149. /**
  10150. * @override
  10151. * Override Camera.createRigCamera
  10152. */
  10153. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  10154. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  10155. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  10156. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  10157. rigCamera._cameraRigParams = {};
  10158. rigCamera._cameraRigParams.vrActualUp = new BABYLON.Vector3(0, 0, 0);
  10159. rigCamera._getViewMatrix = rigCamera._getVRViewMatrix;
  10160. }
  10161. return rigCamera;
  10162. }
  10163. return null;
  10164. };
  10165. /**
  10166. * @override
  10167. * Override Camera._updateRigCameras
  10168. */
  10169. TargetCamera.prototype._updateRigCameras = function () {
  10170. switch (this.cameraRigMode) {
  10171. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10172. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10173. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10174. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10175. case BABYLON.Camera.RIG_MODE_VR:
  10176. var camLeft = this._rigCameras[0];
  10177. var camRight = this._rigCameras[1];
  10178. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  10179. camLeft.rotation.x = camRight.rotation.x = this.rotation.x;
  10180. camLeft.rotation.y = camRight.rotation.y = this.rotation.y;
  10181. camLeft.rotation.z = camRight.rotation.z = this.rotation.z;
  10182. camLeft.position.copyFrom(this.position);
  10183. camRight.position.copyFrom(this.position);
  10184. }
  10185. else {
  10186. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  10187. this._getRigCamPosition(-this._cameraRigParams.stereoHalfAngle, camLeft.position);
  10188. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle, camRight.position);
  10189. camLeft.setTarget(this.getTarget());
  10190. camRight.setTarget(this.getTarget());
  10191. }
  10192. break;
  10193. }
  10194. _super.prototype._updateRigCameras.call(this);
  10195. };
  10196. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  10197. if (!this._rigCamTransformMatrix) {
  10198. this._rigCamTransformMatrix = new BABYLON.Matrix();
  10199. }
  10200. var target = this.getTarget();
  10201. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  10202. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  10203. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  10204. };
  10205. return TargetCamera;
  10206. })(BABYLON.Camera);
  10207. BABYLON.TargetCamera = TargetCamera;
  10208. })(BABYLON || (BABYLON = {}));
  10209. var BABYLON;
  10210. (function (BABYLON) {
  10211. var FreeCamera = (function (_super) {
  10212. __extends(FreeCamera, _super);
  10213. function FreeCamera(name, position, scene) {
  10214. var _this = this;
  10215. _super.call(this, name, position, scene);
  10216. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  10217. this.keysUp = [38];
  10218. this.keysDown = [40];
  10219. this.keysLeft = [37];
  10220. this.keysRight = [39];
  10221. this.checkCollisions = false;
  10222. this.applyGravity = false;
  10223. this.angularSensibility = 2000.0;
  10224. this._keys = [];
  10225. this._collider = new BABYLON.Collider();
  10226. this._needMoveForGravity = false;
  10227. this._oldPosition = BABYLON.Vector3.Zero();
  10228. this._diffPosition = BABYLON.Vector3.Zero();
  10229. this._newPosition = BABYLON.Vector3.Zero();
  10230. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10231. if (collidedMesh === void 0) { collidedMesh = null; }
  10232. //TODO move this to the collision coordinator!
  10233. if (_this.getScene().workerCollisions)
  10234. newPosition.multiplyInPlace(_this._collider.radius);
  10235. var updatePosition = function (newPos) {
  10236. _this._newPosition.copyFrom(newPos);
  10237. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  10238. var oldPosition = _this.position.clone();
  10239. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  10240. _this.position.addInPlace(_this._diffPosition);
  10241. if (_this.onCollide && collidedMesh) {
  10242. _this.onCollide(collidedMesh);
  10243. }
  10244. }
  10245. };
  10246. updatePosition(newPosition);
  10247. };
  10248. }
  10249. // Controls
  10250. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  10251. var _this = this;
  10252. var previousPosition;
  10253. var engine = this.getEngine();
  10254. if (this._attachedElement) {
  10255. return;
  10256. }
  10257. this._attachedElement = element;
  10258. if (this._onMouseDown === undefined) {
  10259. this._onMouseDown = function (evt) {
  10260. previousPosition = {
  10261. x: evt.clientX,
  10262. y: evt.clientY
  10263. };
  10264. if (!noPreventDefault) {
  10265. evt.preventDefault();
  10266. }
  10267. };
  10268. this._onMouseUp = function (evt) {
  10269. previousPosition = null;
  10270. if (!noPreventDefault) {
  10271. evt.preventDefault();
  10272. }
  10273. };
  10274. this._onMouseOut = function (evt) {
  10275. previousPosition = null;
  10276. _this._keys = [];
  10277. if (!noPreventDefault) {
  10278. evt.preventDefault();
  10279. }
  10280. };
  10281. this._onMouseMove = function (evt) {
  10282. if (!previousPosition && !engine.isPointerLock) {
  10283. return;
  10284. }
  10285. var offsetX;
  10286. var offsetY;
  10287. if (!engine.isPointerLock) {
  10288. offsetX = evt.clientX - previousPosition.x;
  10289. offsetY = evt.clientY - previousPosition.y;
  10290. }
  10291. else {
  10292. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  10293. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  10294. }
  10295. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  10296. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  10297. previousPosition = {
  10298. x: evt.clientX,
  10299. y: evt.clientY
  10300. };
  10301. if (!noPreventDefault) {
  10302. evt.preventDefault();
  10303. }
  10304. };
  10305. this._onKeyDown = function (evt) {
  10306. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10307. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10308. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10309. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10310. var index = _this._keys.indexOf(evt.keyCode);
  10311. if (index === -1) {
  10312. _this._keys.push(evt.keyCode);
  10313. }
  10314. if (!noPreventDefault) {
  10315. evt.preventDefault();
  10316. }
  10317. }
  10318. };
  10319. this._onKeyUp = function (evt) {
  10320. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10321. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10322. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10323. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10324. var index = _this._keys.indexOf(evt.keyCode);
  10325. if (index >= 0) {
  10326. _this._keys.splice(index, 1);
  10327. }
  10328. if (!noPreventDefault) {
  10329. evt.preventDefault();
  10330. }
  10331. }
  10332. };
  10333. this._onLostFocus = function () {
  10334. _this._keys = [];
  10335. };
  10336. this._reset = function () {
  10337. _this._keys = [];
  10338. previousPosition = null;
  10339. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10340. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  10341. };
  10342. }
  10343. element.addEventListener("mousedown", this._onMouseDown, false);
  10344. element.addEventListener("mouseup", this._onMouseUp, false);
  10345. element.addEventListener("mouseout", this._onMouseOut, false);
  10346. element.addEventListener("mousemove", this._onMouseMove, false);
  10347. BABYLON.Tools.RegisterTopRootEvents([
  10348. { name: "keydown", handler: this._onKeyDown },
  10349. { name: "keyup", handler: this._onKeyUp },
  10350. { name: "blur", handler: this._onLostFocus }
  10351. ]);
  10352. };
  10353. FreeCamera.prototype.detachControl = function (element) {
  10354. if (this._attachedElement != element) {
  10355. return;
  10356. }
  10357. element.removeEventListener("mousedown", this._onMouseDown);
  10358. element.removeEventListener("mouseup", this._onMouseUp);
  10359. element.removeEventListener("mouseout", this._onMouseOut);
  10360. element.removeEventListener("mousemove", this._onMouseMove);
  10361. BABYLON.Tools.UnregisterTopRootEvents([
  10362. { name: "keydown", handler: this._onKeyDown },
  10363. { name: "keyup", handler: this._onKeyUp },
  10364. { name: "blur", handler: this._onLostFocus }
  10365. ]);
  10366. this._attachedElement = null;
  10367. if (this._reset) {
  10368. this._reset();
  10369. }
  10370. };
  10371. FreeCamera.prototype._collideWithWorld = function (velocity) {
  10372. var globalPosition;
  10373. if (this.parent) {
  10374. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  10375. }
  10376. else {
  10377. globalPosition = this.position;
  10378. }
  10379. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  10380. this._collider.radius = this.ellipsoid;
  10381. //no need for clone, as long as gravity is not on.
  10382. var actualVelocity = velocity;
  10383. //add gravity to the velocity to prevent the dual-collision checking
  10384. if (this.applyGravity) {
  10385. //this prevents mending with cameraDirection, a global variable of the free camera class.
  10386. actualVelocity = velocity.add(this.getScene().gravity);
  10387. }
  10388. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  10389. };
  10390. FreeCamera.prototype._checkInputs = function () {
  10391. if (!this._localDirection) {
  10392. this._localDirection = BABYLON.Vector3.Zero();
  10393. this._transformedDirection = BABYLON.Vector3.Zero();
  10394. }
  10395. // Keyboard
  10396. for (var index = 0; index < this._keys.length; index++) {
  10397. var keyCode = this._keys[index];
  10398. var speed = this._computeLocalCameraSpeed();
  10399. if (this.keysLeft.indexOf(keyCode) !== -1) {
  10400. this._localDirection.copyFromFloats(-speed, 0, 0);
  10401. }
  10402. else if (this.keysUp.indexOf(keyCode) !== -1) {
  10403. this._localDirection.copyFromFloats(0, 0, speed);
  10404. }
  10405. else if (this.keysRight.indexOf(keyCode) !== -1) {
  10406. this._localDirection.copyFromFloats(speed, 0, 0);
  10407. }
  10408. else if (this.keysDown.indexOf(keyCode) !== -1) {
  10409. this._localDirection.copyFromFloats(0, 0, -speed);
  10410. }
  10411. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  10412. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  10413. this.cameraDirection.addInPlace(this._transformedDirection);
  10414. }
  10415. _super.prototype._checkInputs.call(this);
  10416. };
  10417. FreeCamera.prototype._decideIfNeedsToMove = function () {
  10418. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10419. };
  10420. FreeCamera.prototype._updatePosition = function () {
  10421. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  10422. this._collideWithWorld(this.cameraDirection);
  10423. }
  10424. else {
  10425. this.position.addInPlace(this.cameraDirection);
  10426. }
  10427. };
  10428. return FreeCamera;
  10429. })(BABYLON.TargetCamera);
  10430. BABYLON.FreeCamera = FreeCamera;
  10431. })(BABYLON || (BABYLON = {}));
  10432. var BABYLON;
  10433. (function (BABYLON) {
  10434. var FollowCamera = (function (_super) {
  10435. __extends(FollowCamera, _super);
  10436. function FollowCamera(name, position, scene) {
  10437. _super.call(this, name, position, scene);
  10438. this.radius = 12;
  10439. this.rotationOffset = 0;
  10440. this.heightOffset = 4;
  10441. this.cameraAcceleration = 0.05;
  10442. this.maxCameraSpeed = 20;
  10443. }
  10444. FollowCamera.prototype.getRadians = function (degrees) {
  10445. return degrees * Math.PI / 180;
  10446. };
  10447. FollowCamera.prototype.follow = function (cameraTarget) {
  10448. if (!cameraTarget)
  10449. return;
  10450. var yRotation;
  10451. if (cameraTarget.rotationQuaternion) {
  10452. var rotMatrix = new BABYLON.Matrix();
  10453. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  10454. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  10455. }
  10456. else {
  10457. yRotation = cameraTarget.rotation.y;
  10458. }
  10459. var radians = this.getRadians(this.rotationOffset) + yRotation;
  10460. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  10461. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  10462. var dx = targetX - this.position.x;
  10463. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  10464. var dz = (targetZ) - this.position.z;
  10465. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  10466. var vy = dy * this.cameraAcceleration;
  10467. var vz = dz * this.cameraAcceleration * 2;
  10468. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  10469. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10470. }
  10471. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  10472. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10473. }
  10474. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  10475. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10476. }
  10477. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  10478. this.setTarget(cameraTarget.position);
  10479. };
  10480. FollowCamera.prototype._checkInputs = function () {
  10481. _super.prototype._checkInputs.call(this);
  10482. this.follow(this.target);
  10483. };
  10484. return FollowCamera;
  10485. })(BABYLON.TargetCamera);
  10486. BABYLON.FollowCamera = FollowCamera;
  10487. var ArcFollowCamera = (function (_super) {
  10488. __extends(ArcFollowCamera, _super);
  10489. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  10490. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  10491. this.alpha = alpha;
  10492. this.beta = beta;
  10493. this.radius = radius;
  10494. this.target = target;
  10495. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  10496. this.follow();
  10497. }
  10498. ArcFollowCamera.prototype.follow = function () {
  10499. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  10500. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  10501. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  10502. this.position = this.target.position.add(this._cartesianCoordinates);
  10503. this.setTarget(this.target.position);
  10504. };
  10505. ArcFollowCamera.prototype._checkInputs = function () {
  10506. _super.prototype._checkInputs.call(this);
  10507. this.follow();
  10508. };
  10509. return ArcFollowCamera;
  10510. })(BABYLON.TargetCamera);
  10511. BABYLON.ArcFollowCamera = ArcFollowCamera;
  10512. })(BABYLON || (BABYLON = {}));
  10513. var BABYLON;
  10514. (function (BABYLON) {
  10515. // We're mainly based on the logic defined into the FreeCamera code
  10516. var TouchCamera = (function (_super) {
  10517. __extends(TouchCamera, _super);
  10518. function TouchCamera(name, position, scene) {
  10519. _super.call(this, name, position, scene);
  10520. this._offsetX = null;
  10521. this._offsetY = null;
  10522. this._pointerCount = 0;
  10523. this._pointerPressed = [];
  10524. this.angularSensibility = 200000.0;
  10525. this.moveSensibility = 500.0;
  10526. }
  10527. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  10528. var _this = this;
  10529. var previousPosition;
  10530. if (this._attachedCanvas) {
  10531. return;
  10532. }
  10533. this._attachedCanvas = canvas;
  10534. if (this._onPointerDown === undefined) {
  10535. this._onPointerDown = function (evt) {
  10536. if (!noPreventDefault) {
  10537. evt.preventDefault();
  10538. }
  10539. _this._pointerPressed.push(evt.pointerId);
  10540. if (_this._pointerPressed.length !== 1) {
  10541. return;
  10542. }
  10543. previousPosition = {
  10544. x: evt.clientX,
  10545. y: evt.clientY
  10546. };
  10547. };
  10548. this._onPointerUp = function (evt) {
  10549. if (!noPreventDefault) {
  10550. evt.preventDefault();
  10551. }
  10552. var index = _this._pointerPressed.indexOf(evt.pointerId);
  10553. if (index === -1) {
  10554. return;
  10555. }
  10556. _this._pointerPressed.splice(index, 1);
  10557. if (index != 0) {
  10558. return;
  10559. }
  10560. previousPosition = null;
  10561. _this._offsetX = null;
  10562. _this._offsetY = null;
  10563. };
  10564. this._onPointerMove = function (evt) {
  10565. if (!noPreventDefault) {
  10566. evt.preventDefault();
  10567. }
  10568. if (!previousPosition) {
  10569. return;
  10570. }
  10571. var index = _this._pointerPressed.indexOf(evt.pointerId);
  10572. if (index != 0) {
  10573. return;
  10574. }
  10575. _this._offsetX = evt.clientX - previousPosition.x;
  10576. _this._offsetY = -(evt.clientY - previousPosition.y);
  10577. };
  10578. this._onLostFocus = function () {
  10579. _this._offsetX = null;
  10580. _this._offsetY = null;
  10581. };
  10582. }
  10583. canvas.addEventListener("pointerdown", this._onPointerDown);
  10584. canvas.addEventListener("pointerup", this._onPointerUp);
  10585. canvas.addEventListener("pointerout", this._onPointerUp);
  10586. canvas.addEventListener("pointermove", this._onPointerMove);
  10587. BABYLON.Tools.RegisterTopRootEvents([
  10588. { name: "blur", handler: this._onLostFocus }
  10589. ]);
  10590. };
  10591. TouchCamera.prototype.detachControl = function (canvas) {
  10592. if (this._attachedCanvas != canvas) {
  10593. return;
  10594. }
  10595. canvas.removeEventListener("pointerdown", this._onPointerDown);
  10596. canvas.removeEventListener("pointerup", this._onPointerUp);
  10597. canvas.removeEventListener("pointerout", this._onPointerUp);
  10598. canvas.removeEventListener("pointermove", this._onPointerMove);
  10599. BABYLON.Tools.UnregisterTopRootEvents([
  10600. { name: "blur", handler: this._onLostFocus }
  10601. ]);
  10602. this._attachedCanvas = null;
  10603. };
  10604. TouchCamera.prototype._checkInputs = function () {
  10605. if (this._offsetX) {
  10606. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  10607. if (this._pointerPressed.length > 1) {
  10608. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  10609. }
  10610. else {
  10611. var speed = this._computeLocalCameraSpeed();
  10612. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  10613. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  10614. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  10615. }
  10616. }
  10617. _super.prototype._checkInputs.call(this);
  10618. };
  10619. return TouchCamera;
  10620. })(BABYLON.FreeCamera);
  10621. BABYLON.TouchCamera = TouchCamera;
  10622. })(BABYLON || (BABYLON = {}));
  10623. var BABYLON;
  10624. (function (BABYLON) {
  10625. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  10626. var ArcRotateCamera = (function (_super) {
  10627. __extends(ArcRotateCamera, _super);
  10628. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  10629. var _this = this;
  10630. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  10631. this.alpha = alpha;
  10632. this.beta = beta;
  10633. this.radius = radius;
  10634. this.target = target;
  10635. this.inertialAlphaOffset = 0;
  10636. this.inertialBetaOffset = 0;
  10637. this.inertialRadiusOffset = 0;
  10638. this.lowerAlphaLimit = null;
  10639. this.upperAlphaLimit = null;
  10640. this.lowerBetaLimit = 0.01;
  10641. this.upperBetaLimit = Math.PI;
  10642. this.lowerRadiusLimit = null;
  10643. this.upperRadiusLimit = null;
  10644. this.angularSensibilityX = 1000.0;
  10645. this.angularSensibilityY = 1000.0;
  10646. this.wheelPrecision = 3.0;
  10647. this.pinchPrecision = 2.0;
  10648. this.panningSensibility = 50.0;
  10649. this.inertialPanningX = 0;
  10650. this.inertialPanningY = 0;
  10651. this.keysUp = [38];
  10652. this.keysDown = [40];
  10653. this.keysLeft = [37];
  10654. this.keysRight = [39];
  10655. this.zoomOnFactor = 1;
  10656. this.targetScreenOffset = BABYLON.Vector2.Zero();
  10657. this.pinchInwards = true;
  10658. this.allowUpsideDown = true;
  10659. this._keys = [];
  10660. this._viewMatrix = new BABYLON.Matrix();
  10661. this._isRightClick = false;
  10662. this._isCtrlPushed = false;
  10663. this.checkCollisions = false;
  10664. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  10665. this._collider = new BABYLON.Collider();
  10666. this._previousPosition = BABYLON.Vector3.Zero();
  10667. this._collisionVelocity = BABYLON.Vector3.Zero();
  10668. this._newPosition = BABYLON.Vector3.Zero();
  10669. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10670. if (collidedMesh === void 0) { collidedMesh = null; }
  10671. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  10672. newPosition.multiplyInPlace(_this._collider.radius);
  10673. }
  10674. if (!collidedMesh) {
  10675. _this._previousPosition.copyFrom(_this.position);
  10676. }
  10677. else {
  10678. _this.setPosition(_this.position);
  10679. if (_this.onCollide) {
  10680. _this.onCollide(collidedMesh);
  10681. }
  10682. }
  10683. // Recompute because of constraints
  10684. var cosa = Math.cos(_this.alpha);
  10685. var sina = Math.sin(_this.alpha);
  10686. var cosb = Math.cos(_this.beta);
  10687. var sinb = Math.sin(_this.beta);
  10688. var target = _this._getTargetPosition();
  10689. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  10690. _this.position.copyFrom(_this._newPosition);
  10691. var up = _this.upVector;
  10692. if (_this.allowUpsideDown && _this.beta < 0) {
  10693. var up = up.clone();
  10694. up = up.negate();
  10695. }
  10696. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  10697. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  10698. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  10699. _this._collisionTriggered = false;
  10700. };
  10701. if (!this.target) {
  10702. this.target = BABYLON.Vector3.Zero();
  10703. }
  10704. this.getViewMatrix();
  10705. }
  10706. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibility", {
  10707. //deprecated angularSensibility support
  10708. get: function () {
  10709. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  10710. return Math.max(this.angularSensibilityX, this.angularSensibilityY);
  10711. },
  10712. //deprecated angularSensibility support
  10713. set: function (value) {
  10714. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  10715. this.angularSensibilityX = value;
  10716. this.angularSensibilityY = value;
  10717. },
  10718. enumerable: true,
  10719. configurable: true
  10720. });
  10721. ArcRotateCamera.prototype._getTargetPosition = function () {
  10722. return this.target.position || this.target;
  10723. };
  10724. // Cache
  10725. ArcRotateCamera.prototype._initCache = function () {
  10726. _super.prototype._initCache.call(this);
  10727. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10728. this._cache.alpha = undefined;
  10729. this._cache.beta = undefined;
  10730. this._cache.radius = undefined;
  10731. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  10732. };
  10733. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  10734. if (!ignoreParentClass) {
  10735. _super.prototype._updateCache.call(this);
  10736. }
  10737. this._cache.target.copyFrom(this._getTargetPosition());
  10738. this._cache.alpha = this.alpha;
  10739. this._cache.beta = this.beta;
  10740. this._cache.radius = this.radius;
  10741. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  10742. };
  10743. // Synchronized
  10744. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  10745. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  10746. return false;
  10747. return this._cache.target.equals(this._getTargetPosition())
  10748. && this._cache.alpha === this.alpha
  10749. && this._cache.beta === this.beta
  10750. && this._cache.radius === this.radius
  10751. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  10752. };
  10753. // Methods
  10754. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning) {
  10755. var _this = this;
  10756. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  10757. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  10758. var previousPinchDistance = 0;
  10759. var pointers = new BABYLON.SmartCollection();
  10760. if (this._attachedElement) {
  10761. return;
  10762. }
  10763. this._attachedElement = element;
  10764. var engine = this.getEngine();
  10765. if (this._onPointerDown === undefined) {
  10766. this._onPointerDown = function (evt) {
  10767. // Manage panning with right click
  10768. _this._isRightClick = evt.button === 2 ? true : false;
  10769. // manage pointers
  10770. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  10771. cacheSoloPointer = pointers.item(evt.pointerId);
  10772. if (!noPreventDefault) {
  10773. evt.preventDefault();
  10774. }
  10775. };
  10776. this._onPointerUp = function (evt) {
  10777. cacheSoloPointer = null;
  10778. previousPinchDistance = 0;
  10779. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  10780. //but emptying completly pointers collection is required to fix a bug on iPhone :
  10781. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  10782. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  10783. pointers.empty();
  10784. if (!noPreventDefault) {
  10785. evt.preventDefault();
  10786. }
  10787. };
  10788. this._onContextMenu = function (evt) {
  10789. evt.preventDefault();
  10790. };
  10791. this._onPointerMove = function (evt) {
  10792. if (!noPreventDefault) {
  10793. evt.preventDefault();
  10794. }
  10795. switch (pointers.count) {
  10796. case 1:
  10797. if (_this.panningSensibility !== 0 && ((_this._isCtrlPushed && useCtrlForPanning) || (!useCtrlForPanning && _this._isRightClick))) {
  10798. _this.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  10799. _this.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  10800. }
  10801. else {
  10802. var offsetX = evt.clientX - cacheSoloPointer.x;
  10803. var offsetY = evt.clientY - cacheSoloPointer.y;
  10804. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  10805. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  10806. }
  10807. cacheSoloPointer.x = evt.clientX;
  10808. cacheSoloPointer.y = evt.clientY;
  10809. break;
  10810. case 2:
  10811. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  10812. pointers.item(evt.pointerId).x = evt.clientX;
  10813. pointers.item(evt.pointerId).y = evt.clientY;
  10814. var direction = _this.pinchInwards ? 1 : -1;
  10815. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  10816. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  10817. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  10818. if (previousPinchDistance === 0) {
  10819. previousPinchDistance = pinchSquaredDistance;
  10820. return;
  10821. }
  10822. if (pinchSquaredDistance !== previousPinchDistance) {
  10823. _this.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (_this.pinchPrecision * _this.wheelPrecision * ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) * direction);
  10824. previousPinchDistance = pinchSquaredDistance;
  10825. }
  10826. break;
  10827. default:
  10828. if (pointers.item(evt.pointerId)) {
  10829. pointers.item(evt.pointerId).x = evt.clientX;
  10830. pointers.item(evt.pointerId).y = evt.clientY;
  10831. }
  10832. }
  10833. };
  10834. this._onMouseMove = function (evt) {
  10835. if (!engine.isPointerLock) {
  10836. return;
  10837. }
  10838. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  10839. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  10840. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  10841. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  10842. if (!noPreventDefault) {
  10843. evt.preventDefault();
  10844. }
  10845. };
  10846. this._wheel = function (event) {
  10847. var delta = 0;
  10848. if (event.wheelDelta) {
  10849. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  10850. }
  10851. else if (event.detail) {
  10852. delta = -event.detail / _this.wheelPrecision;
  10853. }
  10854. if (delta)
  10855. _this.inertialRadiusOffset += delta;
  10856. if (event.preventDefault) {
  10857. if (!noPreventDefault) {
  10858. event.preventDefault();
  10859. }
  10860. }
  10861. };
  10862. this._onKeyDown = function (evt) {
  10863. _this._isCtrlPushed = evt.ctrlKey;
  10864. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10865. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10866. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10867. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10868. var index = _this._keys.indexOf(evt.keyCode);
  10869. if (index === -1) {
  10870. _this._keys.push(evt.keyCode);
  10871. }
  10872. if (evt.preventDefault) {
  10873. if (!noPreventDefault) {
  10874. evt.preventDefault();
  10875. }
  10876. }
  10877. }
  10878. };
  10879. this._onKeyUp = function (evt) {
  10880. _this._isCtrlPushed = evt.ctrlKey;
  10881. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10882. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10883. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10884. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10885. var index = _this._keys.indexOf(evt.keyCode);
  10886. if (index >= 0) {
  10887. _this._keys.splice(index, 1);
  10888. }
  10889. if (evt.preventDefault) {
  10890. if (!noPreventDefault) {
  10891. evt.preventDefault();
  10892. }
  10893. }
  10894. }
  10895. };
  10896. this._onLostFocus = function () {
  10897. _this._keys = [];
  10898. pointers.empty();
  10899. previousPinchDistance = 0;
  10900. cacheSoloPointer = null;
  10901. };
  10902. this._onGestureStart = function (e) {
  10903. if (window.MSGesture === undefined) {
  10904. return;
  10905. }
  10906. if (!_this._MSGestureHandler) {
  10907. _this._MSGestureHandler = new MSGesture();
  10908. _this._MSGestureHandler.target = element;
  10909. }
  10910. _this._MSGestureHandler.addPointer(e.pointerId);
  10911. };
  10912. this._onGesture = function (e) {
  10913. _this.radius *= e.scale;
  10914. if (e.preventDefault) {
  10915. if (!noPreventDefault) {
  10916. e.stopPropagation();
  10917. e.preventDefault();
  10918. }
  10919. }
  10920. };
  10921. this._reset = function () {
  10922. _this._keys = [];
  10923. _this.inertialAlphaOffset = 0;
  10924. _this.inertialBetaOffset = 0;
  10925. _this.inertialRadiusOffset = 0;
  10926. pointers.empty();
  10927. previousPinchDistance = 0;
  10928. cacheSoloPointer = null;
  10929. };
  10930. }
  10931. if (!useCtrlForPanning) {
  10932. element.addEventListener("contextmenu", this._onContextMenu, false);
  10933. }
  10934. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  10935. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  10936. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  10937. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  10938. element.addEventListener("mousemove", this._onMouseMove, false);
  10939. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  10940. element.addEventListener("MSGestureChange", this._onGesture, false);
  10941. element.addEventListener('mousewheel', this._wheel, false);
  10942. element.addEventListener('DOMMouseScroll', this._wheel, false);
  10943. BABYLON.Tools.RegisterTopRootEvents([
  10944. { name: "keydown", handler: this._onKeyDown },
  10945. { name: "keyup", handler: this._onKeyUp },
  10946. { name: "blur", handler: this._onLostFocus }
  10947. ]);
  10948. };
  10949. ArcRotateCamera.prototype.detachControl = function (element) {
  10950. if (this._attachedElement !== element) {
  10951. return;
  10952. }
  10953. element.removeEventListener("contextmenu", this._onContextMenu);
  10954. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  10955. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  10956. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  10957. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  10958. element.removeEventListener("mousemove", this._onMouseMove);
  10959. element.removeEventListener("MSPointerDown", this._onGestureStart);
  10960. element.removeEventListener("MSGestureChange", this._onGesture);
  10961. element.removeEventListener('mousewheel', this._wheel);
  10962. element.removeEventListener('DOMMouseScroll', this._wheel);
  10963. BABYLON.Tools.UnregisterTopRootEvents([
  10964. { name: "keydown", handler: this._onKeyDown },
  10965. { name: "keyup", handler: this._onKeyUp },
  10966. { name: "blur", handler: this._onLostFocus }
  10967. ]);
  10968. this._MSGestureHandler = null;
  10969. this._attachedElement = null;
  10970. if (this._reset) {
  10971. this._reset();
  10972. }
  10973. };
  10974. ArcRotateCamera.prototype._checkInputs = function () {
  10975. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  10976. if (this._collisionTriggered) {
  10977. return;
  10978. }
  10979. // Keyboard
  10980. for (var index = 0; index < this._keys.length; index++) {
  10981. var keyCode = this._keys[index];
  10982. if (this.keysLeft.indexOf(keyCode) !== -1) {
  10983. this.inertialAlphaOffset -= 0.01;
  10984. }
  10985. else if (this.keysUp.indexOf(keyCode) !== -1) {
  10986. this.inertialBetaOffset -= 0.01;
  10987. }
  10988. else if (this.keysRight.indexOf(keyCode) !== -1) {
  10989. this.inertialAlphaOffset += 0.01;
  10990. }
  10991. else if (this.keysDown.indexOf(keyCode) !== -1) {
  10992. this.inertialBetaOffset += 0.01;
  10993. }
  10994. }
  10995. // Inertia
  10996. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset != 0) {
  10997. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  10998. this.beta += this.inertialBetaOffset;
  10999. this.radius -= this.inertialRadiusOffset;
  11000. this.inertialAlphaOffset *= this.inertia;
  11001. this.inertialBetaOffset *= this.inertia;
  11002. this.inertialRadiusOffset *= this.inertia;
  11003. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  11004. this.inertialAlphaOffset = 0;
  11005. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  11006. this.inertialBetaOffset = 0;
  11007. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  11008. this.inertialRadiusOffset = 0;
  11009. }
  11010. // Panning inertia
  11011. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  11012. if (!this._localDirection) {
  11013. this._localDirection = BABYLON.Vector3.Zero();
  11014. this._transformedDirection = BABYLON.Vector3.Zero();
  11015. }
  11016. this.inertialPanningX *= this.inertia;
  11017. this.inertialPanningY *= this.inertia;
  11018. if (Math.abs(this.inertialPanningX) < BABYLON.Engine.Epsilon)
  11019. this.inertialPanningX = 0;
  11020. if (Math.abs(this.inertialPanningY) < BABYLON.Engine.Epsilon)
  11021. this.inertialPanningY = 0;
  11022. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, 0);
  11023. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  11024. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  11025. this.target.addInPlace(this._transformedDirection);
  11026. }
  11027. // Limits
  11028. this._checkLimits();
  11029. _super.prototype._checkInputs.call(this);
  11030. };
  11031. ArcRotateCamera.prototype._checkLimits = function () {
  11032. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  11033. if (this.allowUpsideDown && this.beta > Math.PI) {
  11034. this.beta = this.beta - (2 * Math.PI);
  11035. }
  11036. }
  11037. else {
  11038. if (this.beta < this.lowerBetaLimit) {
  11039. this.beta = this.lowerBetaLimit;
  11040. }
  11041. }
  11042. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  11043. if (this.allowUpsideDown && this.beta < -Math.PI) {
  11044. this.beta = this.beta + (2 * Math.PI);
  11045. }
  11046. }
  11047. else {
  11048. if (this.beta > this.upperBetaLimit) {
  11049. this.beta = this.upperBetaLimit;
  11050. }
  11051. }
  11052. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  11053. this.alpha = this.lowerAlphaLimit;
  11054. }
  11055. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  11056. this.alpha = this.upperAlphaLimit;
  11057. }
  11058. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  11059. this.radius = this.lowerRadiusLimit;
  11060. }
  11061. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  11062. this.radius = this.upperRadiusLimit;
  11063. }
  11064. };
  11065. ArcRotateCamera.prototype.setPosition = function (position) {
  11066. var radiusv3 = position.subtract(this._getTargetPosition());
  11067. this.radius = radiusv3.length();
  11068. // Alpha
  11069. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  11070. if (radiusv3.z < 0) {
  11071. this.alpha = 2 * Math.PI - this.alpha;
  11072. }
  11073. // Beta
  11074. this.beta = Math.acos(radiusv3.y / this.radius);
  11075. this._checkLimits();
  11076. };
  11077. ArcRotateCamera.prototype.setTarget = function (target) {
  11078. this.target = target;
  11079. };
  11080. ArcRotateCamera.prototype._getViewMatrix = function () {
  11081. // Compute
  11082. var cosa = Math.cos(this.alpha);
  11083. var sina = Math.sin(this.alpha);
  11084. var cosb = Math.cos(this.beta);
  11085. var sinb = Math.sin(this.beta);
  11086. var target = this._getTargetPosition();
  11087. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  11088. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  11089. this._collider.radius = this.collisionRadius;
  11090. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  11091. this._collisionTriggered = true;
  11092. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  11093. }
  11094. else {
  11095. this.position.copyFrom(this._newPosition);
  11096. var up = this.upVector;
  11097. if (this.allowUpsideDown && this.beta < 0) {
  11098. var up = up.clone();
  11099. up = up.negate();
  11100. }
  11101. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  11102. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  11103. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  11104. }
  11105. return this._viewMatrix;
  11106. };
  11107. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  11108. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  11109. meshes = meshes || this.getScene().meshes;
  11110. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  11111. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  11112. this.radius = distance * this.zoomOnFactor;
  11113. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  11114. };
  11115. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  11116. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  11117. var meshesOrMinMaxVector;
  11118. var distance;
  11119. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  11120. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  11121. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  11122. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  11123. }
  11124. else {
  11125. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  11126. distance = meshesOrMinMaxVectorAndDistance.distance;
  11127. }
  11128. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  11129. if (!doNotUpdateMaxZ) {
  11130. this.maxZ = distance * 2;
  11131. }
  11132. };
  11133. /**
  11134. * @override
  11135. * Override Camera.createRigCamera
  11136. */
  11137. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  11138. switch (this.cameraRigMode) {
  11139. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11140. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11141. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11142. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11143. case BABYLON.Camera.RIG_MODE_VR:
  11144. var alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  11145. return new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  11146. }
  11147. };
  11148. /**
  11149. * @override
  11150. * Override Camera._updateRigCameras
  11151. */
  11152. ArcRotateCamera.prototype._updateRigCameras = function () {
  11153. switch (this.cameraRigMode) {
  11154. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11155. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11156. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11157. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11158. case BABYLON.Camera.RIG_MODE_VR:
  11159. var camLeft = this._rigCameras[0];
  11160. var camRight = this._rigCameras[1];
  11161. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  11162. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  11163. camLeft.beta = camRight.beta = this.beta;
  11164. camLeft.radius = camRight.radius = this.radius;
  11165. break;
  11166. }
  11167. _super.prototype._updateRigCameras.call(this);
  11168. };
  11169. return ArcRotateCamera;
  11170. })(BABYLON.TargetCamera);
  11171. BABYLON.ArcRotateCamera = ArcRotateCamera;
  11172. })(BABYLON || (BABYLON = {}));
  11173. var BABYLON;
  11174. (function (BABYLON) {
  11175. var RenderingManager = (function () {
  11176. function RenderingManager(scene) {
  11177. this._renderingGroups = new Array();
  11178. this._scene = scene;
  11179. }
  11180. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  11181. if (this._scene._activeParticleSystems.length === 0) {
  11182. return;
  11183. }
  11184. // Particles
  11185. var activeCamera = this._scene.activeCamera;
  11186. var beforeParticlesDate = BABYLON.Tools.Now;
  11187. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  11188. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  11189. if (particleSystem.renderingGroupId !== index) {
  11190. continue;
  11191. }
  11192. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  11193. continue;
  11194. }
  11195. this._clearDepthBuffer();
  11196. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  11197. this._scene._activeParticles += particleSystem.render();
  11198. }
  11199. }
  11200. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  11201. };
  11202. RenderingManager.prototype._renderSprites = function (index) {
  11203. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  11204. return;
  11205. }
  11206. // Sprites
  11207. var activeCamera = this._scene.activeCamera;
  11208. var beforeSpritessDate = BABYLON.Tools.Now;
  11209. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  11210. var spriteManager = this._scene.spriteManagers[id];
  11211. if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  11212. this._clearDepthBuffer();
  11213. spriteManager.render();
  11214. }
  11215. }
  11216. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  11217. };
  11218. RenderingManager.prototype._clearDepthBuffer = function () {
  11219. if (this._depthBufferAlreadyCleaned) {
  11220. return;
  11221. }
  11222. this._scene.getEngine().clear(0, false, true);
  11223. this._depthBufferAlreadyCleaned = true;
  11224. };
  11225. RenderingManager.prototype._renderSpritesAndParticles = function () {
  11226. if (this._currentRenderSprites) {
  11227. this._renderSprites(this._currentIndex);
  11228. }
  11229. if (this._currentRenderParticles) {
  11230. this._renderParticles(this._currentIndex, this._currentActiveMeshes);
  11231. }
  11232. };
  11233. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  11234. this._currentActiveMeshes = activeMeshes;
  11235. this._currentRenderParticles = renderParticles;
  11236. this._currentRenderSprites = renderSprites;
  11237. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  11238. this._depthBufferAlreadyCleaned = false;
  11239. var renderingGroup = this._renderingGroups[index];
  11240. var needToStepBack = false;
  11241. this._currentIndex = index;
  11242. if (renderingGroup) {
  11243. this._clearDepthBuffer();
  11244. if (!renderingGroup.onBeforeTransparentRendering) {
  11245. renderingGroup.onBeforeTransparentRendering = this._renderSpritesAndParticles.bind(this);
  11246. }
  11247. if (!renderingGroup.render(customRenderFunction)) {
  11248. this._renderingGroups.splice(index, 1);
  11249. needToStepBack = true;
  11250. this._renderSpritesAndParticles();
  11251. }
  11252. }
  11253. else {
  11254. this._renderSpritesAndParticles();
  11255. }
  11256. if (needToStepBack) {
  11257. index--;
  11258. }
  11259. }
  11260. };
  11261. RenderingManager.prototype.reset = function () {
  11262. this._renderingGroups.forEach(function (renderingGroup, index, array) {
  11263. if (renderingGroup) {
  11264. renderingGroup.prepare();
  11265. }
  11266. });
  11267. };
  11268. RenderingManager.prototype.dispatch = function (subMesh) {
  11269. var mesh = subMesh.getMesh();
  11270. var renderingGroupId = mesh.renderingGroupId || 0;
  11271. if (!this._renderingGroups[renderingGroupId]) {
  11272. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  11273. }
  11274. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  11275. };
  11276. RenderingManager.MAX_RENDERINGGROUPS = 4;
  11277. return RenderingManager;
  11278. })();
  11279. BABYLON.RenderingManager = RenderingManager;
  11280. })(BABYLON || (BABYLON = {}));
  11281. var BABYLON;
  11282. (function (BABYLON) {
  11283. var RenderingGroup = (function () {
  11284. function RenderingGroup(index, scene) {
  11285. this.index = index;
  11286. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  11287. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  11288. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  11289. this._scene = scene;
  11290. }
  11291. RenderingGroup.prototype.render = function (customRenderFunction) {
  11292. if (customRenderFunction) {
  11293. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  11294. return true;
  11295. }
  11296. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  11297. if (this.onBeforeTransparentRendering) {
  11298. this.onBeforeTransparentRendering();
  11299. }
  11300. return false;
  11301. }
  11302. var engine = this._scene.getEngine();
  11303. // Opaque
  11304. var subIndex;
  11305. var submesh;
  11306. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  11307. submesh = this._opaqueSubMeshes.data[subIndex];
  11308. submesh.render(false);
  11309. }
  11310. // Alpha test
  11311. engine.setAlphaTesting(true);
  11312. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  11313. submesh = this._alphaTestSubMeshes.data[subIndex];
  11314. submesh.render(false);
  11315. }
  11316. engine.setAlphaTesting(false);
  11317. if (this.onBeforeTransparentRendering) {
  11318. this.onBeforeTransparentRendering();
  11319. }
  11320. // Transparent
  11321. if (this._transparentSubMeshes.length) {
  11322. // Sorting
  11323. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  11324. submesh = this._transparentSubMeshes.data[subIndex];
  11325. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  11326. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.globalPosition).length();
  11327. }
  11328. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  11329. sortedArray.sort(function (a, b) {
  11330. // Alpha index first
  11331. if (a._alphaIndex > b._alphaIndex) {
  11332. return 1;
  11333. }
  11334. if (a._alphaIndex < b._alphaIndex) {
  11335. return -1;
  11336. }
  11337. // Then distance to camera
  11338. if (a._distanceToCamera < b._distanceToCamera) {
  11339. return 1;
  11340. }
  11341. if (a._distanceToCamera > b._distanceToCamera) {
  11342. return -1;
  11343. }
  11344. return 0;
  11345. });
  11346. // Rendering
  11347. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  11348. submesh = sortedArray[subIndex];
  11349. submesh.render(true);
  11350. }
  11351. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  11352. }
  11353. return true;
  11354. };
  11355. RenderingGroup.prototype.prepare = function () {
  11356. this._opaqueSubMeshes.reset();
  11357. this._transparentSubMeshes.reset();
  11358. this._alphaTestSubMeshes.reset();
  11359. };
  11360. RenderingGroup.prototype.dispatch = function (subMesh) {
  11361. var material = subMesh.getMaterial();
  11362. var mesh = subMesh.getMesh();
  11363. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  11364. this._transparentSubMeshes.push(subMesh);
  11365. }
  11366. else if (material.needAlphaTesting()) {
  11367. this._alphaTestSubMeshes.push(subMesh);
  11368. }
  11369. else {
  11370. this._opaqueSubMeshes.push(subMesh); // Opaque
  11371. }
  11372. };
  11373. return RenderingGroup;
  11374. })();
  11375. BABYLON.RenderingGroup = RenderingGroup;
  11376. })(BABYLON || (BABYLON = {}));
  11377. var BABYLON;
  11378. (function (BABYLON) {
  11379. /**
  11380. * Represents a scene to be rendered by the engine.
  11381. * @see http://doc.babylonjs.com/page.php?p=21911
  11382. */
  11383. var Scene = (function () {
  11384. /**
  11385. * @constructor
  11386. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  11387. */
  11388. function Scene(engine) {
  11389. // Members
  11390. this.autoClear = true;
  11391. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  11392. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  11393. this.forceWireframe = false;
  11394. this.forcePointsCloud = false;
  11395. this.forceShowBoundingBoxes = false;
  11396. this.animationsEnabled = true;
  11397. this.constantlyUpdateMeshUnderPointer = false;
  11398. 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
  11399. // Fog
  11400. /**
  11401. * is fog enabled on this scene.
  11402. * @type {boolean}
  11403. */
  11404. this.fogEnabled = true;
  11405. this.fogMode = Scene.FOGMODE_NONE;
  11406. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  11407. this.fogDensity = 0.1;
  11408. this.fogStart = 0;
  11409. this.fogEnd = 1000.0;
  11410. // Lights
  11411. /**
  11412. * is shadow enabled on this scene.
  11413. * @type {boolean}
  11414. */
  11415. this.shadowsEnabled = true;
  11416. /**
  11417. * is light enabled on this scene.
  11418. * @type {boolean}
  11419. */
  11420. this.lightsEnabled = true;
  11421. /**
  11422. * All of the lights added to this scene.
  11423. * @see BABYLON.Light
  11424. * @type {BABYLON.Light[]}
  11425. */
  11426. this.lights = new Array();
  11427. // Cameras
  11428. /**
  11429. * All of the cameras added to this scene.
  11430. * @see BABYLON.Camera
  11431. * @type {BABYLON.Camera[]}
  11432. */
  11433. this.cameras = new Array();
  11434. this.activeCameras = new Array();
  11435. // Meshes
  11436. /**
  11437. * All of the (abstract) meshes added to this scene.
  11438. * @see BABYLON.AbstractMesh
  11439. * @type {BABYLON.AbstractMesh[]}
  11440. */
  11441. this.meshes = new Array();
  11442. // Geometries
  11443. this._geometries = new Array();
  11444. this.materials = new Array();
  11445. this.multiMaterials = new Array();
  11446. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  11447. // Textures
  11448. this.texturesEnabled = true;
  11449. this.textures = new Array();
  11450. // Particles
  11451. this.particlesEnabled = true;
  11452. this.particleSystems = new Array();
  11453. // Sprites
  11454. this.spritesEnabled = true;
  11455. this.spriteManagers = new Array();
  11456. // Layers
  11457. this.layers = new Array();
  11458. // Skeletons
  11459. this.skeletonsEnabled = true;
  11460. this.skeletons = new Array();
  11461. // Lens flares
  11462. this.lensFlaresEnabled = true;
  11463. this.lensFlareSystems = new Array();
  11464. // Collisions
  11465. this.collisionsEnabled = true;
  11466. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  11467. // Postprocesses
  11468. this.postProcessesEnabled = true;
  11469. // Customs render targets
  11470. this.renderTargetsEnabled = true;
  11471. this.dumpNextRenderTargets = false;
  11472. this.customRenderTargets = new Array();
  11473. // Imported meshes
  11474. this.importedMeshesFiles = new Array();
  11475. // Probes
  11476. this.probesEnabled = true;
  11477. this.reflectionProbes = new Array();
  11478. this._actionManagers = new Array();
  11479. this._meshesForIntersections = new BABYLON.SmartArray(256);
  11480. // Procedural textures
  11481. this.proceduralTexturesEnabled = true;
  11482. this._proceduralTextures = new Array();
  11483. this.soundTracks = new Array();
  11484. this._audioEnabled = true;
  11485. this._headphone = false;
  11486. this._totalVertices = 0;
  11487. this._activeIndices = 0;
  11488. this._activeParticles = 0;
  11489. this._lastFrameDuration = 0;
  11490. this._evaluateActiveMeshesDuration = 0;
  11491. this._renderTargetsDuration = 0;
  11492. this._particlesDuration = 0;
  11493. this._renderDuration = 0;
  11494. this._spritesDuration = 0;
  11495. this._animationRatio = 0;
  11496. this._renderId = 0;
  11497. this._executeWhenReadyTimeoutId = -1;
  11498. this._toBeDisposed = new BABYLON.SmartArray(256);
  11499. this._onReadyCallbacks = new Array();
  11500. this._pendingData = []; //ANY
  11501. this._onBeforeRenderCallbacks = new Array();
  11502. this._onAfterRenderCallbacks = new Array();
  11503. this._activeMeshes = new BABYLON.SmartArray(256);
  11504. this._processedMaterials = new BABYLON.SmartArray(256);
  11505. this._renderTargets = new BABYLON.SmartArray(256);
  11506. this._activeParticleSystems = new BABYLON.SmartArray(256);
  11507. this._activeSkeletons = new BABYLON.SmartArray(32);
  11508. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  11509. this._activeBones = 0;
  11510. this._activeAnimatables = new Array();
  11511. this._transformMatrix = BABYLON.Matrix.Zero();
  11512. this._edgesRenderers = new BABYLON.SmartArray(16);
  11513. this._uniqueIdCounter = 0;
  11514. this._engine = engine;
  11515. engine.scenes.push(this);
  11516. this._renderingManager = new BABYLON.RenderingManager(this);
  11517. this.postProcessManager = new BABYLON.PostProcessManager(this);
  11518. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  11519. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  11520. if (BABYLON.OutlineRenderer) {
  11521. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  11522. }
  11523. this.attachControl();
  11524. this._debugLayer = new BABYLON.DebugLayer(this);
  11525. if (BABYLON.SoundTrack) {
  11526. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  11527. }
  11528. //simplification queue
  11529. if (BABYLON.SimplificationQueue) {
  11530. this.simplificationQueue = new BABYLON.SimplificationQueue();
  11531. }
  11532. //collision coordinator initialization. For now legacy per default.
  11533. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  11534. }
  11535. Object.defineProperty(Scene, "FOGMODE_NONE", {
  11536. get: function () {
  11537. return Scene._FOGMODE_NONE;
  11538. },
  11539. enumerable: true,
  11540. configurable: true
  11541. });
  11542. Object.defineProperty(Scene, "FOGMODE_EXP", {
  11543. get: function () {
  11544. return Scene._FOGMODE_EXP;
  11545. },
  11546. enumerable: true,
  11547. configurable: true
  11548. });
  11549. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  11550. get: function () {
  11551. return Scene._FOGMODE_EXP2;
  11552. },
  11553. enumerable: true,
  11554. configurable: true
  11555. });
  11556. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  11557. get: function () {
  11558. return Scene._FOGMODE_LINEAR;
  11559. },
  11560. enumerable: true,
  11561. configurable: true
  11562. });
  11563. Object.defineProperty(Scene.prototype, "debugLayer", {
  11564. // Properties
  11565. get: function () {
  11566. return this._debugLayer;
  11567. },
  11568. enumerable: true,
  11569. configurable: true
  11570. });
  11571. Object.defineProperty(Scene.prototype, "workerCollisions", {
  11572. get: function () {
  11573. return this._workerCollisions;
  11574. },
  11575. set: function (enabled) {
  11576. enabled = (enabled && !!Worker);
  11577. this._workerCollisions = enabled;
  11578. if (this.collisionCoordinator) {
  11579. this.collisionCoordinator.destroy();
  11580. }
  11581. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  11582. this.collisionCoordinator.init(this);
  11583. },
  11584. enumerable: true,
  11585. configurable: true
  11586. });
  11587. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  11588. get: function () {
  11589. return this._selectionOctree;
  11590. },
  11591. enumerable: true,
  11592. configurable: true
  11593. });
  11594. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  11595. /**
  11596. * The mesh that is currently under the pointer.
  11597. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  11598. */
  11599. get: function () {
  11600. return this._meshUnderPointer;
  11601. },
  11602. enumerable: true,
  11603. configurable: true
  11604. });
  11605. Object.defineProperty(Scene.prototype, "pointerX", {
  11606. /**
  11607. * Current on-screen X position of the pointer
  11608. * @return {number} X position of the pointer
  11609. */
  11610. get: function () {
  11611. return this._pointerX;
  11612. },
  11613. enumerable: true,
  11614. configurable: true
  11615. });
  11616. Object.defineProperty(Scene.prototype, "pointerY", {
  11617. /**
  11618. * Current on-screen Y position of the pointer
  11619. * @return {number} Y position of the pointer
  11620. */
  11621. get: function () {
  11622. return this._pointerY;
  11623. },
  11624. enumerable: true,
  11625. configurable: true
  11626. });
  11627. Scene.prototype.getCachedMaterial = function () {
  11628. return this._cachedMaterial;
  11629. };
  11630. Scene.prototype.getBoundingBoxRenderer = function () {
  11631. return this._boundingBoxRenderer;
  11632. };
  11633. Scene.prototype.getOutlineRenderer = function () {
  11634. return this._outlineRenderer;
  11635. };
  11636. Scene.prototype.getEngine = function () {
  11637. return this._engine;
  11638. };
  11639. Scene.prototype.getTotalVertices = function () {
  11640. return this._totalVertices;
  11641. };
  11642. Scene.prototype.getActiveIndices = function () {
  11643. return this._activeIndices;
  11644. };
  11645. Scene.prototype.getActiveParticles = function () {
  11646. return this._activeParticles;
  11647. };
  11648. Scene.prototype.getActiveBones = function () {
  11649. return this._activeBones;
  11650. };
  11651. // Stats
  11652. Scene.prototype.getLastFrameDuration = function () {
  11653. return this._lastFrameDuration;
  11654. };
  11655. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  11656. return this._evaluateActiveMeshesDuration;
  11657. };
  11658. Scene.prototype.getActiveMeshes = function () {
  11659. return this._activeMeshes;
  11660. };
  11661. Scene.prototype.getRenderTargetsDuration = function () {
  11662. return this._renderTargetsDuration;
  11663. };
  11664. Scene.prototype.getRenderDuration = function () {
  11665. return this._renderDuration;
  11666. };
  11667. Scene.prototype.getParticlesDuration = function () {
  11668. return this._particlesDuration;
  11669. };
  11670. Scene.prototype.getSpritesDuration = function () {
  11671. return this._spritesDuration;
  11672. };
  11673. Scene.prototype.getAnimationRatio = function () {
  11674. return this._animationRatio;
  11675. };
  11676. Scene.prototype.getRenderId = function () {
  11677. return this._renderId;
  11678. };
  11679. Scene.prototype.incrementRenderId = function () {
  11680. this._renderId++;
  11681. };
  11682. Scene.prototype._updatePointerPosition = function (evt) {
  11683. var canvasRect = this._engine.getRenderingCanvasClientRect();
  11684. this._pointerX = evt.clientX - canvasRect.left;
  11685. this._pointerY = evt.clientY - canvasRect.top;
  11686. if (this.cameraToUseForPointers) {
  11687. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  11688. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  11689. }
  11690. };
  11691. // Pointers handling
  11692. Scene.prototype.attachControl = function () {
  11693. var _this = this;
  11694. var spritePredicate = function (sprite) {
  11695. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPickTriggers;
  11696. };
  11697. this._onPointerMove = function (evt) {
  11698. var canvas = _this._engine.getRenderingCanvas();
  11699. _this._updatePointerPosition(evt);
  11700. // Meshes
  11701. 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);
  11702. if (pickResult.hit && pickResult.pickedMesh) {
  11703. _this._meshUnderPointer = pickResult.pickedMesh;
  11704. _this.setPointerOverMesh(pickResult.pickedMesh);
  11705. if (_this._meshUnderPointer.actionManager && _this._meshUnderPointer.actionManager.hasPointerTriggers) {
  11706. canvas.style.cursor = "pointer";
  11707. }
  11708. else {
  11709. canvas.style.cursor = "";
  11710. }
  11711. }
  11712. else {
  11713. // Sprites
  11714. pickResult = _this.pickSprite(_this._pointerX, _this._pointerY, spritePredicate, false, _this.cameraToUseForPointers);
  11715. if (pickResult.hit && pickResult.pickedSprite) {
  11716. canvas.style.cursor = "pointer";
  11717. return;
  11718. }
  11719. // Restore pointer
  11720. _this.setPointerOverMesh(null);
  11721. canvas.style.cursor = "";
  11722. _this._meshUnderPointer = null;
  11723. }
  11724. };
  11725. this._onPointerDown = function (evt) {
  11726. _this._updatePointerPosition(evt);
  11727. var predicate = null;
  11728. // Meshes
  11729. if (!_this.onPointerDown) {
  11730. predicate = function (mesh) {
  11731. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  11732. };
  11733. }
  11734. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  11735. if (pickResult.hit && pickResult.pickedMesh) {
  11736. if (pickResult.pickedMesh.actionManager) {
  11737. switch (evt.button) {
  11738. case 0:
  11739. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  11740. break;
  11741. case 1:
  11742. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  11743. break;
  11744. case 2:
  11745. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  11746. break;
  11747. }
  11748. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  11749. }
  11750. }
  11751. if (_this.onPointerDown) {
  11752. _this.onPointerDown(evt, pickResult);
  11753. }
  11754. // Sprites
  11755. if (_this.spriteManagers.length > 0) {
  11756. pickResult = _this.pickSprite(_this._pointerX, _this._pointerY, spritePredicate, false, _this.cameraToUseForPointers);
  11757. if (pickResult.hit && pickResult.pickedSprite) {
  11758. if (pickResult.pickedSprite.actionManager) {
  11759. switch (evt.button) {
  11760. case 0:
  11761. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  11762. break;
  11763. case 1:
  11764. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  11765. break;
  11766. case 2:
  11767. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  11768. break;
  11769. }
  11770. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  11771. }
  11772. }
  11773. }
  11774. };
  11775. this._onPointerUp = function (evt) {
  11776. var predicate = null;
  11777. _this._updatePointerPosition(evt);
  11778. if (!_this.onPointerUp) {
  11779. predicate = function (mesh) {
  11780. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickUpTrigger);
  11781. };
  11782. }
  11783. // Meshes
  11784. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  11785. if (pickResult.hit && pickResult.pickedMesh) {
  11786. if (pickResult.pickedMesh.actionManager) {
  11787. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  11788. }
  11789. }
  11790. if (_this.onPointerUp) {
  11791. _this.onPointerUp(evt, pickResult);
  11792. }
  11793. // Sprites
  11794. if (_this.spriteManagers.length > 0) {
  11795. pickResult = _this.pickSprite(_this._pointerX, _this._pointerY, spritePredicate, false, _this.cameraToUseForPointers);
  11796. if (pickResult.hit && pickResult.pickedSprite) {
  11797. if (pickResult.pickedSprite.actionManager) {
  11798. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  11799. }
  11800. }
  11801. }
  11802. };
  11803. this._onKeyDown = function (evt) {
  11804. if (_this.actionManager) {
  11805. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  11806. }
  11807. };
  11808. this._onKeyUp = function (evt) {
  11809. if (_this.actionManager) {
  11810. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  11811. }
  11812. };
  11813. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  11814. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  11815. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  11816. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
  11817. // Wheel
  11818. this._engine.getRenderingCanvas().addEventListener('mousewheel', this._onPointerMove, false);
  11819. this._engine.getRenderingCanvas().addEventListener('DOMMouseScroll', this._onPointerMove, false);
  11820. BABYLON.Tools.RegisterTopRootEvents([
  11821. { name: "keydown", handler: this._onKeyDown },
  11822. { name: "keyup", handler: this._onKeyUp }
  11823. ]);
  11824. };
  11825. Scene.prototype.detachControl = function () {
  11826. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  11827. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  11828. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  11829. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
  11830. // Wheel
  11831. this._engine.getRenderingCanvas().removeEventListener('mousewheel', this._onPointerMove);
  11832. this._engine.getRenderingCanvas().removeEventListener('DOMMouseScroll', this._onPointerMove);
  11833. BABYLON.Tools.UnregisterTopRootEvents([
  11834. { name: "keydown", handler: this._onKeyDown },
  11835. { name: "keyup", handler: this._onKeyUp }
  11836. ]);
  11837. };
  11838. // Ready
  11839. Scene.prototype.isReady = function () {
  11840. if (this._pendingData.length > 0) {
  11841. return false;
  11842. }
  11843. var index;
  11844. for (index = 0; index < this._geometries.length; index++) {
  11845. var geometry = this._geometries[index];
  11846. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  11847. return false;
  11848. }
  11849. }
  11850. for (index = 0; index < this.meshes.length; index++) {
  11851. var mesh = this.meshes[index];
  11852. if (!mesh.isReady()) {
  11853. return false;
  11854. }
  11855. var mat = mesh.material;
  11856. if (mat) {
  11857. if (!mat.isReady(mesh)) {
  11858. return false;
  11859. }
  11860. }
  11861. }
  11862. return true;
  11863. };
  11864. Scene.prototype.resetCachedMaterial = function () {
  11865. this._cachedMaterial = null;
  11866. };
  11867. Scene.prototype.registerBeforeRender = function (func) {
  11868. this._onBeforeRenderCallbacks.push(func);
  11869. };
  11870. Scene.prototype.unregisterBeforeRender = function (func) {
  11871. var index = this._onBeforeRenderCallbacks.indexOf(func);
  11872. if (index > -1) {
  11873. this._onBeforeRenderCallbacks.splice(index, 1);
  11874. }
  11875. };
  11876. Scene.prototype.registerAfterRender = function (func) {
  11877. this._onAfterRenderCallbacks.push(func);
  11878. };
  11879. Scene.prototype.unregisterAfterRender = function (func) {
  11880. var index = this._onAfterRenderCallbacks.indexOf(func);
  11881. if (index > -1) {
  11882. this._onAfterRenderCallbacks.splice(index, 1);
  11883. }
  11884. };
  11885. Scene.prototype._addPendingData = function (data) {
  11886. this._pendingData.push(data);
  11887. };
  11888. Scene.prototype._removePendingData = function (data) {
  11889. var index = this._pendingData.indexOf(data);
  11890. if (index !== -1) {
  11891. this._pendingData.splice(index, 1);
  11892. }
  11893. };
  11894. Scene.prototype.getWaitingItemsCount = function () {
  11895. return this._pendingData.length;
  11896. };
  11897. /**
  11898. * Registers a function to be executed when the scene is ready.
  11899. * @param {Function} func - the function to be executed.
  11900. */
  11901. Scene.prototype.executeWhenReady = function (func) {
  11902. var _this = this;
  11903. this._onReadyCallbacks.push(func);
  11904. if (this._executeWhenReadyTimeoutId !== -1) {
  11905. return;
  11906. }
  11907. this._executeWhenReadyTimeoutId = setTimeout(function () {
  11908. _this._checkIsReady();
  11909. }, 150);
  11910. };
  11911. Scene.prototype._checkIsReady = function () {
  11912. var _this = this;
  11913. if (this.isReady()) {
  11914. this._onReadyCallbacks.forEach(function (func) {
  11915. func();
  11916. });
  11917. this._onReadyCallbacks = [];
  11918. this._executeWhenReadyTimeoutId = -1;
  11919. return;
  11920. }
  11921. this._executeWhenReadyTimeoutId = setTimeout(function () {
  11922. _this._checkIsReady();
  11923. }, 150);
  11924. };
  11925. // Animations
  11926. /**
  11927. * Will start the animation sequence of a given target
  11928. * @param target - the target
  11929. * @param {number} from - from which frame should animation start
  11930. * @param {number} to - till which frame should animation run.
  11931. * @param {boolean} [loop] - should the animation loop
  11932. * @param {number} [speedRatio] - the speed in which to run the animation
  11933. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  11934. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  11935. * @return {BABYLON.Animatable} the animatable object created for this animation
  11936. * @see BABYLON.Animatable
  11937. * @see http://doc.babylonjs.com/page.php?p=22081
  11938. */
  11939. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  11940. if (speedRatio === void 0) { speedRatio = 1.0; }
  11941. this.stopAnimation(target);
  11942. if (!animatable) {
  11943. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  11944. }
  11945. // Local animations
  11946. if (target.animations) {
  11947. animatable.appendAnimations(target, target.animations);
  11948. }
  11949. // Children animations
  11950. if (target.getAnimatables) {
  11951. var animatables = target.getAnimatables();
  11952. for (var index = 0; index < animatables.length; index++) {
  11953. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  11954. }
  11955. }
  11956. return animatable;
  11957. };
  11958. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  11959. if (speedRatio === undefined) {
  11960. speedRatio = 1.0;
  11961. }
  11962. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  11963. return animatable;
  11964. };
  11965. Scene.prototype.getAnimatableByTarget = function (target) {
  11966. for (var index = 0; index < this._activeAnimatables.length; index++) {
  11967. if (this._activeAnimatables[index].target === target) {
  11968. return this._activeAnimatables[index];
  11969. }
  11970. }
  11971. return null;
  11972. };
  11973. /**
  11974. * Will stop the animation of the given target
  11975. * @param target - the target
  11976. * @see beginAnimation
  11977. */
  11978. Scene.prototype.stopAnimation = function (target) {
  11979. var animatable = this.getAnimatableByTarget(target);
  11980. if (animatable) {
  11981. animatable.stop();
  11982. }
  11983. };
  11984. Scene.prototype._animate = function () {
  11985. if (!this.animationsEnabled) {
  11986. return;
  11987. }
  11988. if (!this._animationStartDate) {
  11989. this._animationStartDate = BABYLON.Tools.Now;
  11990. }
  11991. // Getting time
  11992. var now = BABYLON.Tools.Now;
  11993. var delay = now - this._animationStartDate;
  11994. for (var index = 0; index < this._activeAnimatables.length; index++) {
  11995. this._activeAnimatables[index]._animate(delay);
  11996. }
  11997. };
  11998. // Matrix
  11999. Scene.prototype.getViewMatrix = function () {
  12000. return this._viewMatrix;
  12001. };
  12002. Scene.prototype.getProjectionMatrix = function () {
  12003. return this._projectionMatrix;
  12004. };
  12005. Scene.prototype.getTransformMatrix = function () {
  12006. return this._transformMatrix;
  12007. };
  12008. Scene.prototype.setTransformMatrix = function (view, projection) {
  12009. this._viewMatrix = view;
  12010. this._projectionMatrix = projection;
  12011. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  12012. };
  12013. // Methods
  12014. Scene.prototype.addMesh = function (newMesh) {
  12015. newMesh.uniqueId = this._uniqueIdCounter++;
  12016. var position = this.meshes.push(newMesh);
  12017. //notify the collision coordinator
  12018. this.collisionCoordinator.onMeshAdded(newMesh);
  12019. if (this.onNewMeshAdded) {
  12020. this.onNewMeshAdded(newMesh, position, this);
  12021. }
  12022. };
  12023. Scene.prototype.removeMesh = function (toRemove) {
  12024. var index = this.meshes.indexOf(toRemove);
  12025. if (index !== -1) {
  12026. // Remove from the scene if mesh found
  12027. this.meshes.splice(index, 1);
  12028. }
  12029. //notify the collision coordinator
  12030. this.collisionCoordinator.onMeshRemoved(toRemove);
  12031. if (this.onMeshRemoved) {
  12032. this.onMeshRemoved(toRemove);
  12033. }
  12034. return index;
  12035. };
  12036. Scene.prototype.removeSkeleton = function (toRemove) {
  12037. var index = this.skeletons.indexOf(toRemove);
  12038. if (index !== -1) {
  12039. // Remove from the scene if mesh found
  12040. this.skeletons.splice(index, 1);
  12041. }
  12042. return index;
  12043. };
  12044. Scene.prototype.removeLight = function (toRemove) {
  12045. var index = this.lights.indexOf(toRemove);
  12046. if (index !== -1) {
  12047. // Remove from the scene if mesh found
  12048. this.lights.splice(index, 1);
  12049. }
  12050. if (this.onLightRemoved) {
  12051. this.onLightRemoved(toRemove);
  12052. }
  12053. return index;
  12054. };
  12055. Scene.prototype.removeCamera = function (toRemove) {
  12056. var index = this.cameras.indexOf(toRemove);
  12057. if (index !== -1) {
  12058. // Remove from the scene if mesh found
  12059. this.cameras.splice(index, 1);
  12060. }
  12061. // Remove from activeCameras
  12062. var index2 = this.activeCameras.indexOf(toRemove);
  12063. if (index2 !== -1) {
  12064. // Remove from the scene if mesh found
  12065. this.activeCameras.splice(index2, 1);
  12066. }
  12067. // Reset the activeCamera
  12068. if (this.activeCamera === toRemove) {
  12069. if (this.cameras.length > 0) {
  12070. this.activeCamera = this.cameras[0];
  12071. }
  12072. else {
  12073. this.activeCamera = null;
  12074. }
  12075. }
  12076. if (this.onCameraRemoved) {
  12077. this.onCameraRemoved(toRemove);
  12078. }
  12079. return index;
  12080. };
  12081. Scene.prototype.addLight = function (newLight) {
  12082. newLight.uniqueId = this._uniqueIdCounter++;
  12083. var position = this.lights.push(newLight);
  12084. if (this.onNewLightAdded) {
  12085. this.onNewLightAdded(newLight, position, this);
  12086. }
  12087. };
  12088. Scene.prototype.addCamera = function (newCamera) {
  12089. newCamera.uniqueId = this._uniqueIdCounter++;
  12090. var position = this.cameras.push(newCamera);
  12091. if (this.onNewCameraAdded) {
  12092. this.onNewCameraAdded(newCamera, position, this);
  12093. }
  12094. };
  12095. /**
  12096. * sets the active camera of the scene using its ID
  12097. * @param {string} id - the camera's ID
  12098. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  12099. * @see activeCamera
  12100. */
  12101. Scene.prototype.setActiveCameraByID = function (id) {
  12102. var camera = this.getCameraByID(id);
  12103. if (camera) {
  12104. this.activeCamera = camera;
  12105. return camera;
  12106. }
  12107. return null;
  12108. };
  12109. /**
  12110. * sets the active camera of the scene using its name
  12111. * @param {string} name - the camera's name
  12112. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  12113. * @see activeCamera
  12114. */
  12115. Scene.prototype.setActiveCameraByName = function (name) {
  12116. var camera = this.getCameraByName(name);
  12117. if (camera) {
  12118. this.activeCamera = camera;
  12119. return camera;
  12120. }
  12121. return null;
  12122. };
  12123. /**
  12124. * get a material using its id
  12125. * @param {string} the material's ID
  12126. * @return {BABYLON.Material|null} the material or null if none found.
  12127. */
  12128. Scene.prototype.getMaterialByID = function (id) {
  12129. for (var index = 0; index < this.materials.length; index++) {
  12130. if (this.materials[index].id === id) {
  12131. return this.materials[index];
  12132. }
  12133. }
  12134. return null;
  12135. };
  12136. /**
  12137. * get a material using its name
  12138. * @param {string} the material's name
  12139. * @return {BABYLON.Material|null} the material or null if none found.
  12140. */
  12141. Scene.prototype.getMaterialByName = function (name) {
  12142. for (var index = 0; index < this.materials.length; index++) {
  12143. if (this.materials[index].name === name) {
  12144. return this.materials[index];
  12145. }
  12146. }
  12147. return null;
  12148. };
  12149. Scene.prototype.getLensFlareSystemByName = function (name) {
  12150. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  12151. if (this.lensFlareSystems[index].name === name) {
  12152. return this.lensFlareSystems[index];
  12153. }
  12154. }
  12155. return null;
  12156. };
  12157. Scene.prototype.getCameraByID = function (id) {
  12158. for (var index = 0; index < this.cameras.length; index++) {
  12159. if (this.cameras[index].id === id) {
  12160. return this.cameras[index];
  12161. }
  12162. }
  12163. return null;
  12164. };
  12165. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  12166. for (var index = 0; index < this.cameras.length; index++) {
  12167. if (this.cameras[index].uniqueId === uniqueId) {
  12168. return this.cameras[index];
  12169. }
  12170. }
  12171. return null;
  12172. };
  12173. /**
  12174. * get a camera using its name
  12175. * @param {string} the camera's name
  12176. * @return {BABYLON.Camera|null} the camera or null if none found.
  12177. */
  12178. Scene.prototype.getCameraByName = function (name) {
  12179. for (var index = 0; index < this.cameras.length; index++) {
  12180. if (this.cameras[index].name === name) {
  12181. return this.cameras[index];
  12182. }
  12183. }
  12184. return null;
  12185. };
  12186. /**
  12187. * get a light node using its name
  12188. * @param {string} the light's name
  12189. * @return {BABYLON.Light|null} the light or null if none found.
  12190. */
  12191. Scene.prototype.getLightByName = function (name) {
  12192. for (var index = 0; index < this.lights.length; index++) {
  12193. if (this.lights[index].name === name) {
  12194. return this.lights[index];
  12195. }
  12196. }
  12197. return null;
  12198. };
  12199. /**
  12200. * get a light node using its ID
  12201. * @param {string} the light's id
  12202. * @return {BABYLON.Light|null} the light or null if none found.
  12203. */
  12204. Scene.prototype.getLightByID = function (id) {
  12205. for (var index = 0; index < this.lights.length; index++) {
  12206. if (this.lights[index].id === id) {
  12207. return this.lights[index];
  12208. }
  12209. }
  12210. return null;
  12211. };
  12212. /**
  12213. * get a light node using its scene-generated unique ID
  12214. * @param {number} the light's unique id
  12215. * @return {BABYLON.Light|null} the light or null if none found.
  12216. */
  12217. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  12218. for (var index = 0; index < this.lights.length; index++) {
  12219. if (this.lights[index].uniqueId === uniqueId) {
  12220. return this.lights[index];
  12221. }
  12222. }
  12223. return null;
  12224. };
  12225. /**
  12226. * get a geometry using its ID
  12227. * @param {string} the geometry's id
  12228. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  12229. */
  12230. Scene.prototype.getGeometryByID = function (id) {
  12231. for (var index = 0; index < this._geometries.length; index++) {
  12232. if (this._geometries[index].id === id) {
  12233. return this._geometries[index];
  12234. }
  12235. }
  12236. return null;
  12237. };
  12238. /**
  12239. * add a new geometry to this scene.
  12240. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  12241. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  12242. * @return {boolean} was the geometry added or not
  12243. */
  12244. Scene.prototype.pushGeometry = function (geometry, force) {
  12245. if (!force && this.getGeometryByID(geometry.id)) {
  12246. return false;
  12247. }
  12248. this._geometries.push(geometry);
  12249. //notify the collision coordinator
  12250. this.collisionCoordinator.onGeometryAdded(geometry);
  12251. if (this.onGeometryAdded) {
  12252. this.onGeometryAdded(geometry);
  12253. }
  12254. return true;
  12255. };
  12256. /**
  12257. * Removes an existing geometry
  12258. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  12259. * @return {boolean} was the geometry removed or not
  12260. */
  12261. Scene.prototype.removeGeometry = function (geometry) {
  12262. var index = this._geometries.indexOf(geometry);
  12263. if (index > -1) {
  12264. this._geometries.splice(index, 1);
  12265. //notify the collision coordinator
  12266. this.collisionCoordinator.onGeometryDeleted(geometry);
  12267. if (this.onGeometryRemoved) {
  12268. this.onGeometryRemoved(geometry);
  12269. }
  12270. return true;
  12271. }
  12272. return false;
  12273. };
  12274. Scene.prototype.getGeometries = function () {
  12275. return this._geometries;
  12276. };
  12277. /**
  12278. * Get the first added mesh found of a given ID
  12279. * @param {string} id - the id to search for
  12280. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  12281. */
  12282. Scene.prototype.getMeshByID = function (id) {
  12283. for (var index = 0; index < this.meshes.length; index++) {
  12284. if (this.meshes[index].id === id) {
  12285. return this.meshes[index];
  12286. }
  12287. }
  12288. return null;
  12289. };
  12290. /**
  12291. * Get a mesh with its auto-generated unique id
  12292. * @param {number} uniqueId - the unique id to search for
  12293. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  12294. */
  12295. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  12296. for (var index = 0; index < this.meshes.length; index++) {
  12297. if (this.meshes[index].uniqueId === uniqueId) {
  12298. return this.meshes[index];
  12299. }
  12300. }
  12301. return null;
  12302. };
  12303. /**
  12304. * Get a the last added mesh found of a given ID
  12305. * @param {string} id - the id to search for
  12306. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  12307. */
  12308. Scene.prototype.getLastMeshByID = function (id) {
  12309. for (var index = this.meshes.length - 1; index >= 0; index--) {
  12310. if (this.meshes[index].id === id) {
  12311. return this.meshes[index];
  12312. }
  12313. }
  12314. return null;
  12315. };
  12316. /**
  12317. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  12318. * @param {string} id - the id to search for
  12319. * @return {BABYLON.Node|null} the node found or null if not found at all.
  12320. */
  12321. Scene.prototype.getLastEntryByID = function (id) {
  12322. var index;
  12323. for (index = this.meshes.length - 1; index >= 0; index--) {
  12324. if (this.meshes[index].id === id) {
  12325. return this.meshes[index];
  12326. }
  12327. }
  12328. for (index = this.cameras.length - 1; index >= 0; index--) {
  12329. if (this.cameras[index].id === id) {
  12330. return this.cameras[index];
  12331. }
  12332. }
  12333. for (index = this.lights.length - 1; index >= 0; index--) {
  12334. if (this.lights[index].id === id) {
  12335. return this.lights[index];
  12336. }
  12337. }
  12338. return null;
  12339. };
  12340. Scene.prototype.getNodeByID = function (id) {
  12341. var mesh = this.getMeshByID(id);
  12342. if (mesh) {
  12343. return mesh;
  12344. }
  12345. var light = this.getLightByID(id);
  12346. if (light) {
  12347. return light;
  12348. }
  12349. return this.getCameraByID(id);
  12350. };
  12351. Scene.prototype.getNodeByName = function (name) {
  12352. var mesh = this.getMeshByName(name);
  12353. if (mesh) {
  12354. return mesh;
  12355. }
  12356. var light = this.getLightByName(name);
  12357. if (light) {
  12358. return light;
  12359. }
  12360. return this.getCameraByName(name);
  12361. };
  12362. Scene.prototype.getMeshByName = function (name) {
  12363. for (var index = 0; index < this.meshes.length; index++) {
  12364. if (this.meshes[index].name === name) {
  12365. return this.meshes[index];
  12366. }
  12367. }
  12368. return null;
  12369. };
  12370. Scene.prototype.getSoundByName = function (name) {
  12371. var index;
  12372. if (BABYLON.AudioEngine) {
  12373. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  12374. if (this.mainSoundTrack.soundCollection[index].name === name) {
  12375. return this.mainSoundTrack.soundCollection[index];
  12376. }
  12377. }
  12378. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  12379. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  12380. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  12381. return this.soundTracks[sdIndex].soundCollection[index];
  12382. }
  12383. }
  12384. }
  12385. }
  12386. return null;
  12387. };
  12388. Scene.prototype.getLastSkeletonByID = function (id) {
  12389. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  12390. if (this.skeletons[index].id === id) {
  12391. return this.skeletons[index];
  12392. }
  12393. }
  12394. return null;
  12395. };
  12396. Scene.prototype.getSkeletonById = function (id) {
  12397. for (var index = 0; index < this.skeletons.length; index++) {
  12398. if (this.skeletons[index].id === id) {
  12399. return this.skeletons[index];
  12400. }
  12401. }
  12402. return null;
  12403. };
  12404. Scene.prototype.getSkeletonByName = function (name) {
  12405. for (var index = 0; index < this.skeletons.length; index++) {
  12406. if (this.skeletons[index].name === name) {
  12407. return this.skeletons[index];
  12408. }
  12409. }
  12410. return null;
  12411. };
  12412. Scene.prototype.isActiveMesh = function (mesh) {
  12413. return (this._activeMeshes.indexOf(mesh) !== -1);
  12414. };
  12415. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  12416. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  12417. var material = subMesh.getMaterial();
  12418. if (mesh.showSubMeshesBoundingBox) {
  12419. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  12420. }
  12421. if (material) {
  12422. // Render targets
  12423. if (material.getRenderTargetTextures) {
  12424. if (this._processedMaterials.indexOf(material) === -1) {
  12425. this._processedMaterials.push(material);
  12426. this._renderTargets.concat(material.getRenderTargetTextures());
  12427. }
  12428. }
  12429. // Dispatch
  12430. this._activeIndices += subMesh.indexCount;
  12431. this._renderingManager.dispatch(subMesh);
  12432. }
  12433. }
  12434. };
  12435. Scene.prototype._evaluateActiveMeshes = function () {
  12436. this.activeCamera._activeMeshes.reset();
  12437. this._activeMeshes.reset();
  12438. this._renderingManager.reset();
  12439. this._processedMaterials.reset();
  12440. this._activeParticleSystems.reset();
  12441. this._activeSkeletons.reset();
  12442. this._softwareSkinnedMeshes.reset();
  12443. this._boundingBoxRenderer.reset();
  12444. this._edgesRenderers.reset();
  12445. if (!this._frustumPlanes) {
  12446. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  12447. }
  12448. else {
  12449. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  12450. }
  12451. // Meshes
  12452. var meshes;
  12453. var len;
  12454. if (this._selectionOctree) {
  12455. var selection = this._selectionOctree.select(this._frustumPlanes);
  12456. meshes = selection.data;
  12457. len = selection.length;
  12458. }
  12459. else {
  12460. len = this.meshes.length;
  12461. meshes = this.meshes;
  12462. }
  12463. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  12464. var mesh = meshes[meshIndex];
  12465. if (mesh.isBlocked) {
  12466. continue;
  12467. }
  12468. this._totalVertices += mesh.getTotalVertices();
  12469. if (!mesh.isReady() || !mesh.isEnabled()) {
  12470. continue;
  12471. }
  12472. mesh.computeWorldMatrix();
  12473. // Intersections
  12474. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  12475. this._meshesForIntersections.pushNoDuplicate(mesh);
  12476. }
  12477. // Switch to current LOD
  12478. var meshLOD = mesh.getLOD(this.activeCamera);
  12479. if (!meshLOD) {
  12480. continue;
  12481. }
  12482. mesh._preActivate();
  12483. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  12484. this._activeMeshes.push(mesh);
  12485. this.activeCamera._activeMeshes.push(mesh);
  12486. mesh._activate(this._renderId);
  12487. this._activeMesh(meshLOD);
  12488. }
  12489. }
  12490. // Particle systems
  12491. var beforeParticlesDate = BABYLON.Tools.Now;
  12492. if (this.particlesEnabled) {
  12493. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  12494. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  12495. var particleSystem = this.particleSystems[particleIndex];
  12496. if (!particleSystem.isStarted()) {
  12497. continue;
  12498. }
  12499. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  12500. this._activeParticleSystems.push(particleSystem);
  12501. particleSystem.animate();
  12502. }
  12503. }
  12504. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  12505. }
  12506. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  12507. };
  12508. Scene.prototype._activeMesh = function (mesh) {
  12509. if (mesh.skeleton && this.skeletonsEnabled) {
  12510. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  12511. if (!mesh.computeBonesUsingShaders) {
  12512. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  12513. }
  12514. }
  12515. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  12516. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  12517. }
  12518. if (mesh._edgesRenderer) {
  12519. this._edgesRenderers.push(mesh._edgesRenderer);
  12520. }
  12521. if (mesh && mesh.subMeshes) {
  12522. // Submeshes Octrees
  12523. var len;
  12524. var subMeshes;
  12525. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  12526. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  12527. len = intersections.length;
  12528. subMeshes = intersections.data;
  12529. }
  12530. else {
  12531. subMeshes = mesh.subMeshes;
  12532. len = subMeshes.length;
  12533. }
  12534. for (var subIndex = 0; subIndex < len; subIndex++) {
  12535. var subMesh = subMeshes[subIndex];
  12536. this._evaluateSubMesh(subMesh, mesh);
  12537. }
  12538. }
  12539. };
  12540. Scene.prototype.updateTransformMatrix = function (force) {
  12541. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  12542. };
  12543. Scene.prototype._renderForCamera = function (camera) {
  12544. var engine = this._engine;
  12545. this.activeCamera = camera;
  12546. if (!this.activeCamera)
  12547. throw new Error("Active camera not set");
  12548. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  12549. // Viewport
  12550. engine.setViewport(this.activeCamera.viewport);
  12551. // Camera
  12552. this.resetCachedMaterial();
  12553. this._renderId++;
  12554. this.updateTransformMatrix();
  12555. if (this.beforeCameraRender) {
  12556. this.beforeCameraRender(this.activeCamera);
  12557. }
  12558. // Meshes
  12559. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  12560. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  12561. this._evaluateActiveMeshes();
  12562. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  12563. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  12564. // Skeletons
  12565. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  12566. var skeleton = this._activeSkeletons.data[skeletonIndex];
  12567. skeleton.prepare();
  12568. }
  12569. // Software skinning
  12570. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  12571. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  12572. mesh.applySkeleton(mesh.skeleton);
  12573. }
  12574. // Render targets
  12575. var beforeRenderTargetDate = BABYLON.Tools.Now;
  12576. if (this.renderTargetsEnabled) {
  12577. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  12578. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  12579. var renderTarget = this._renderTargets.data[renderIndex];
  12580. if (renderTarget._shouldRender()) {
  12581. this._renderId++;
  12582. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  12583. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  12584. }
  12585. }
  12586. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  12587. this._renderId++;
  12588. }
  12589. if (this._renderTargets.length > 0) {
  12590. engine.restoreDefaultFramebuffer();
  12591. }
  12592. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  12593. // Prepare Frame
  12594. this.postProcessManager._prepareFrame();
  12595. var beforeRenderDate = BABYLON.Tools.Now;
  12596. // Backgrounds
  12597. var layerIndex;
  12598. var layer;
  12599. if (this.layers.length) {
  12600. engine.setDepthBuffer(false);
  12601. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  12602. layer = this.layers[layerIndex];
  12603. if (layer.isBackground) {
  12604. layer.render();
  12605. }
  12606. }
  12607. engine.setDepthBuffer(true);
  12608. }
  12609. // Render
  12610. BABYLON.Tools.StartPerformanceCounter("Main render");
  12611. this._renderingManager.render(null, null, true, true);
  12612. BABYLON.Tools.EndPerformanceCounter("Main render");
  12613. // Bounding boxes
  12614. this._boundingBoxRenderer.render();
  12615. // Edges
  12616. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  12617. this._edgesRenderers.data[edgesRendererIndex].render();
  12618. }
  12619. // Lens flares
  12620. if (this.lensFlaresEnabled) {
  12621. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  12622. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  12623. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  12624. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  12625. lensFlareSystem.render();
  12626. }
  12627. }
  12628. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  12629. }
  12630. // Foregrounds
  12631. if (this.layers.length) {
  12632. engine.setDepthBuffer(false);
  12633. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  12634. layer = this.layers[layerIndex];
  12635. if (!layer.isBackground) {
  12636. layer.render();
  12637. }
  12638. }
  12639. engine.setDepthBuffer(true);
  12640. }
  12641. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  12642. // Finalize frame
  12643. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  12644. // Update camera
  12645. this.activeCamera._updateFromScene();
  12646. // Reset some special arrays
  12647. this._renderTargets.reset();
  12648. if (this.afterCameraRender) {
  12649. this.afterCameraRender(this.activeCamera);
  12650. }
  12651. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  12652. };
  12653. Scene.prototype._processSubCameras = function (camera) {
  12654. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  12655. this._renderForCamera(camera);
  12656. return;
  12657. }
  12658. // rig cameras
  12659. for (var index = 0; index < camera._rigCameras.length; index++) {
  12660. this._renderForCamera(camera._rigCameras[index]);
  12661. }
  12662. this.activeCamera = camera;
  12663. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  12664. // Update camera
  12665. this.activeCamera._updateFromScene();
  12666. };
  12667. Scene.prototype._checkIntersections = function () {
  12668. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  12669. var sourceMesh = this._meshesForIntersections.data[index];
  12670. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  12671. var action = sourceMesh.actionManager.actions[actionIndex];
  12672. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  12673. var parameters = action.getTriggerParameter();
  12674. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  12675. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  12676. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  12677. if (areIntersecting && currentIntersectionInProgress === -1) {
  12678. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  12679. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  12680. sourceMesh._intersectionsInProgress.push(otherMesh);
  12681. }
  12682. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  12683. sourceMesh._intersectionsInProgress.push(otherMesh);
  12684. }
  12685. }
  12686. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  12687. //They intersected, and now they don't.
  12688. //is this trigger an exit trigger? execute an event.
  12689. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  12690. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  12691. }
  12692. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  12693. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  12694. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  12695. }
  12696. }
  12697. }
  12698. }
  12699. }
  12700. };
  12701. Scene.prototype.render = function () {
  12702. var startDate = BABYLON.Tools.Now;
  12703. this._particlesDuration = 0;
  12704. this._spritesDuration = 0;
  12705. this._activeParticles = 0;
  12706. this._renderDuration = 0;
  12707. this._renderTargetsDuration = 0;
  12708. this._evaluateActiveMeshesDuration = 0;
  12709. this._totalVertices = 0;
  12710. this._activeIndices = 0;
  12711. this._activeBones = 0;
  12712. this.getEngine().resetDrawCalls();
  12713. this._meshesForIntersections.reset();
  12714. this.resetCachedMaterial();
  12715. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  12716. // Actions
  12717. if (this.actionManager) {
  12718. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  12719. }
  12720. //Simplification Queue
  12721. if (this.simplificationQueue && !this.simplificationQueue.running) {
  12722. this.simplificationQueue.executeNext();
  12723. }
  12724. // Animations
  12725. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  12726. this._animationRatio = deltaTime * (60.0 / 1000.0);
  12727. this._animate();
  12728. // Physics
  12729. if (this._physicsEngine) {
  12730. BABYLON.Tools.StartPerformanceCounter("Physics");
  12731. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  12732. BABYLON.Tools.EndPerformanceCounter("Physics");
  12733. }
  12734. // Before render
  12735. if (this.beforeRender) {
  12736. this.beforeRender();
  12737. }
  12738. var callbackIndex;
  12739. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  12740. this._onBeforeRenderCallbacks[callbackIndex]();
  12741. }
  12742. // Customs render targets
  12743. var beforeRenderTargetDate = BABYLON.Tools.Now;
  12744. var engine = this.getEngine();
  12745. var currentActiveCamera = this.activeCamera;
  12746. if (this.renderTargetsEnabled) {
  12747. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  12748. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  12749. var renderTarget = this.customRenderTargets[customIndex];
  12750. if (renderTarget._shouldRender()) {
  12751. this._renderId++;
  12752. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  12753. if (!this.activeCamera)
  12754. throw new Error("Active camera not set");
  12755. // Viewport
  12756. engine.setViewport(this.activeCamera.viewport);
  12757. // Camera
  12758. this.updateTransformMatrix();
  12759. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  12760. }
  12761. }
  12762. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  12763. this._renderId++;
  12764. }
  12765. if (this.customRenderTargets.length > 0) {
  12766. engine.restoreDefaultFramebuffer();
  12767. }
  12768. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  12769. this.activeCamera = currentActiveCamera;
  12770. // Procedural textures
  12771. if (this.proceduralTexturesEnabled) {
  12772. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  12773. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  12774. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  12775. if (proceduralTexture._shouldRender()) {
  12776. proceduralTexture.render();
  12777. }
  12778. }
  12779. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  12780. }
  12781. // Clear
  12782. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  12783. // Shadows
  12784. if (this.shadowsEnabled) {
  12785. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  12786. var light = this.lights[lightIndex];
  12787. var shadowGenerator = light.getShadowGenerator();
  12788. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  12789. this._renderTargets.push(shadowGenerator.getShadowMap());
  12790. }
  12791. }
  12792. }
  12793. // Depth renderer
  12794. if (this._depthRenderer) {
  12795. this._renderTargets.push(this._depthRenderer.getDepthMap());
  12796. }
  12797. // RenderPipeline
  12798. this.postProcessRenderPipelineManager.update();
  12799. // Multi-cameras?
  12800. if (this.activeCameras.length > 0) {
  12801. var currentRenderId = this._renderId;
  12802. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  12803. this._renderId = currentRenderId;
  12804. this._processSubCameras(this.activeCameras[cameraIndex]);
  12805. }
  12806. }
  12807. else {
  12808. if (!this.activeCamera) {
  12809. throw new Error("No camera defined");
  12810. }
  12811. this._processSubCameras(this.activeCamera);
  12812. }
  12813. // Intersection checks
  12814. this._checkIntersections();
  12815. // Update the audio listener attached to the camera
  12816. if (BABYLON.AudioEngine) {
  12817. this._updateAudioParameters();
  12818. }
  12819. // After render
  12820. if (this.afterRender) {
  12821. this.afterRender();
  12822. }
  12823. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  12824. this._onAfterRenderCallbacks[callbackIndex]();
  12825. }
  12826. // Cleaning
  12827. for (var index = 0; index < this._toBeDisposed.length; index++) {
  12828. this._toBeDisposed.data[index].dispose();
  12829. this._toBeDisposed[index] = null;
  12830. }
  12831. this._toBeDisposed.reset();
  12832. if (this.dumpNextRenderTargets) {
  12833. this.dumpNextRenderTargets = false;
  12834. }
  12835. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  12836. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  12837. };
  12838. Scene.prototype._updateAudioParameters = function () {
  12839. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  12840. return;
  12841. }
  12842. var listeningCamera;
  12843. var audioEngine = BABYLON.Engine.audioEngine;
  12844. if (this.activeCameras.length > 0) {
  12845. listeningCamera = this.activeCameras[0];
  12846. }
  12847. else {
  12848. listeningCamera = this.activeCamera;
  12849. }
  12850. if (listeningCamera && audioEngine.canUseWebAudio) {
  12851. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  12852. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  12853. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  12854. cameraDirection.normalize();
  12855. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  12856. var i;
  12857. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  12858. var sound = this.mainSoundTrack.soundCollection[i];
  12859. if (sound.useCustomAttenuation) {
  12860. sound.updateDistanceFromListener();
  12861. }
  12862. }
  12863. for (i = 0; i < this.soundTracks.length; i++) {
  12864. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  12865. sound = this.soundTracks[i].soundCollection[j];
  12866. if (sound.useCustomAttenuation) {
  12867. sound.updateDistanceFromListener();
  12868. }
  12869. }
  12870. }
  12871. }
  12872. };
  12873. Object.defineProperty(Scene.prototype, "audioEnabled", {
  12874. // Audio
  12875. get: function () {
  12876. return this._audioEnabled;
  12877. },
  12878. set: function (value) {
  12879. this._audioEnabled = value;
  12880. if (BABYLON.AudioEngine) {
  12881. if (this._audioEnabled) {
  12882. this._enableAudio();
  12883. }
  12884. else {
  12885. this._disableAudio();
  12886. }
  12887. }
  12888. },
  12889. enumerable: true,
  12890. configurable: true
  12891. });
  12892. Scene.prototype._disableAudio = function () {
  12893. var i;
  12894. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  12895. this.mainSoundTrack.soundCollection[i].pause();
  12896. }
  12897. for (i = 0; i < this.soundTracks.length; i++) {
  12898. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  12899. this.soundTracks[i].soundCollection[j].pause();
  12900. }
  12901. }
  12902. };
  12903. Scene.prototype._enableAudio = function () {
  12904. var i;
  12905. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  12906. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  12907. this.mainSoundTrack.soundCollection[i].play();
  12908. }
  12909. }
  12910. for (i = 0; i < this.soundTracks.length; i++) {
  12911. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  12912. if (this.soundTracks[i].soundCollection[j].isPaused) {
  12913. this.soundTracks[i].soundCollection[j].play();
  12914. }
  12915. }
  12916. }
  12917. };
  12918. Object.defineProperty(Scene.prototype, "headphone", {
  12919. get: function () {
  12920. return this._headphone;
  12921. },
  12922. set: function (value) {
  12923. this._headphone = value;
  12924. if (BABYLON.AudioEngine) {
  12925. if (this._headphone) {
  12926. this._switchAudioModeForHeadphones();
  12927. }
  12928. else {
  12929. this._switchAudioModeForNormalSpeakers();
  12930. }
  12931. }
  12932. },
  12933. enumerable: true,
  12934. configurable: true
  12935. });
  12936. Scene.prototype._switchAudioModeForHeadphones = function () {
  12937. this.mainSoundTrack.switchPanningModelToHRTF();
  12938. for (var i = 0; i < this.soundTracks.length; i++) {
  12939. this.soundTracks[i].switchPanningModelToHRTF();
  12940. }
  12941. };
  12942. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  12943. this.mainSoundTrack.switchPanningModelToEqualPower();
  12944. for (var i = 0; i < this.soundTracks.length; i++) {
  12945. this.soundTracks[i].switchPanningModelToEqualPower();
  12946. }
  12947. };
  12948. Scene.prototype.enableDepthRenderer = function () {
  12949. if (this._depthRenderer) {
  12950. return this._depthRenderer;
  12951. }
  12952. this._depthRenderer = new BABYLON.DepthRenderer(this);
  12953. return this._depthRenderer;
  12954. };
  12955. Scene.prototype.disableDepthRenderer = function () {
  12956. if (!this._depthRenderer) {
  12957. return;
  12958. }
  12959. this._depthRenderer.dispose();
  12960. this._depthRenderer = null;
  12961. };
  12962. Scene.prototype.dispose = function () {
  12963. this.beforeRender = null;
  12964. this.afterRender = null;
  12965. this.skeletons = [];
  12966. this._boundingBoxRenderer.dispose();
  12967. if (this._depthRenderer) {
  12968. this._depthRenderer.dispose();
  12969. }
  12970. // Debug layer
  12971. this.debugLayer.hide();
  12972. // Events
  12973. if (this.onDispose) {
  12974. this.onDispose();
  12975. }
  12976. this._onBeforeRenderCallbacks = [];
  12977. this._onAfterRenderCallbacks = [];
  12978. this.detachControl();
  12979. // Release sounds & sounds tracks
  12980. if (BABYLON.AudioEngine) {
  12981. this.disposeSounds();
  12982. }
  12983. // Detach cameras
  12984. var canvas = this._engine.getRenderingCanvas();
  12985. var index;
  12986. for (index = 0; index < this.cameras.length; index++) {
  12987. this.cameras[index].detachControl(canvas);
  12988. }
  12989. // Release lights
  12990. while (this.lights.length) {
  12991. this.lights[0].dispose();
  12992. }
  12993. // Release meshes
  12994. while (this.meshes.length) {
  12995. this.meshes[0].dispose(true);
  12996. }
  12997. // Release cameras
  12998. while (this.cameras.length) {
  12999. this.cameras[0].dispose();
  13000. }
  13001. // Release materials
  13002. while (this.materials.length) {
  13003. this.materials[0].dispose();
  13004. }
  13005. // Release particles
  13006. while (this.particleSystems.length) {
  13007. this.particleSystems[0].dispose();
  13008. }
  13009. // Release sprites
  13010. while (this.spriteManagers.length) {
  13011. this.spriteManagers[0].dispose();
  13012. }
  13013. // Release layers
  13014. while (this.layers.length) {
  13015. this.layers[0].dispose();
  13016. }
  13017. // Release textures
  13018. while (this.textures.length) {
  13019. this.textures[0].dispose();
  13020. }
  13021. // Post-processes
  13022. this.postProcessManager.dispose();
  13023. // Physics
  13024. if (this._physicsEngine) {
  13025. this.disablePhysicsEngine();
  13026. }
  13027. // Remove from engine
  13028. index = this._engine.scenes.indexOf(this);
  13029. if (index > -1) {
  13030. this._engine.scenes.splice(index, 1);
  13031. }
  13032. this._engine.wipeCaches();
  13033. };
  13034. // Release sounds & sounds tracks
  13035. Scene.prototype.disposeSounds = function () {
  13036. this.mainSoundTrack.dispose();
  13037. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  13038. this.soundTracks[scIndex].dispose();
  13039. }
  13040. };
  13041. // Octrees
  13042. Scene.prototype.getWorldExtends = function () {
  13043. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13044. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  13045. for (var index = 0; index < this.meshes.length; index++) {
  13046. var mesh = this.meshes[index];
  13047. mesh.computeWorldMatrix(true);
  13048. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  13049. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  13050. BABYLON.Tools.CheckExtends(minBox, min, max);
  13051. BABYLON.Tools.CheckExtends(maxBox, min, max);
  13052. }
  13053. return {
  13054. min: min,
  13055. max: max
  13056. };
  13057. };
  13058. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  13059. if (maxCapacity === void 0) { maxCapacity = 64; }
  13060. if (maxDepth === void 0) { maxDepth = 2; }
  13061. if (!this._selectionOctree) {
  13062. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  13063. }
  13064. var worldExtends = this.getWorldExtends();
  13065. // Update octree
  13066. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  13067. return this._selectionOctree;
  13068. };
  13069. // Picking
  13070. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  13071. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  13072. var engine = this._engine;
  13073. if (!camera) {
  13074. if (!this.activeCamera)
  13075. throw new Error("Active camera not set");
  13076. camera = this.activeCamera;
  13077. }
  13078. var cameraViewport = camera.viewport;
  13079. var viewport = cameraViewport.toGlobal(engine);
  13080. // Moving coordinates to local viewport world
  13081. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  13082. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  13083. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  13084. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  13085. };
  13086. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  13087. var engine = this._engine;
  13088. if (!camera) {
  13089. if (!this.activeCamera)
  13090. throw new Error("Active camera not set");
  13091. camera = this.activeCamera;
  13092. }
  13093. var cameraViewport = camera.viewport;
  13094. var viewport = cameraViewport.toGlobal(engine);
  13095. var identity = BABYLON.Matrix.Identity();
  13096. // Moving coordinates to local viewport world
  13097. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  13098. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  13099. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  13100. };
  13101. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  13102. var pickingInfo = null;
  13103. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  13104. var mesh = this.meshes[meshIndex];
  13105. if (predicate) {
  13106. if (!predicate(mesh)) {
  13107. continue;
  13108. }
  13109. }
  13110. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  13111. continue;
  13112. }
  13113. var world = mesh.getWorldMatrix();
  13114. var ray = rayFunction(world);
  13115. var result = mesh.intersects(ray, fastCheck);
  13116. if (!result || !result.hit)
  13117. continue;
  13118. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  13119. continue;
  13120. pickingInfo = result;
  13121. if (fastCheck) {
  13122. break;
  13123. }
  13124. }
  13125. return pickingInfo || new BABYLON.PickingInfo();
  13126. };
  13127. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  13128. var pickingInfo = null;
  13129. camera = camera || this.activeCamera;
  13130. if (this.spriteManagers.length > 0) {
  13131. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  13132. var spriteManager = this.spriteManagers[spriteIndex];
  13133. if (!spriteManager.isPickable) {
  13134. continue;
  13135. }
  13136. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  13137. if (!result || !result.hit)
  13138. continue;
  13139. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  13140. continue;
  13141. pickingInfo = result;
  13142. if (fastCheck) {
  13143. break;
  13144. }
  13145. }
  13146. }
  13147. return pickingInfo || new BABYLON.PickingInfo();
  13148. };
  13149. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  13150. var _this = this;
  13151. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  13152. /// <param name="x">X position on screen</param>
  13153. /// <param name="y">Y position on screen</param>
  13154. /// <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>
  13155. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  13156. /// <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>
  13157. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  13158. };
  13159. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  13160. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  13161. /// <param name="x">X position on screen</param>
  13162. /// <param name="y">Y position on screen</param>
  13163. /// <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>
  13164. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  13165. /// <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>
  13166. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  13167. };
  13168. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  13169. var _this = this;
  13170. return this._internalPick(function (world) {
  13171. if (!_this._pickWithRayInverseMatrix) {
  13172. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  13173. }
  13174. world.invertToRef(_this._pickWithRayInverseMatrix);
  13175. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  13176. }, predicate, fastCheck);
  13177. };
  13178. Scene.prototype.setPointerOverMesh = function (mesh) {
  13179. if (this._pointerOverMesh === mesh) {
  13180. return;
  13181. }
  13182. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  13183. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  13184. }
  13185. this._pointerOverMesh = mesh;
  13186. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  13187. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  13188. }
  13189. };
  13190. Scene.prototype.getPointerOverMesh = function () {
  13191. return this._pointerOverMesh;
  13192. };
  13193. // Physics
  13194. Scene.prototype.getPhysicsEngine = function () {
  13195. return this._physicsEngine;
  13196. };
  13197. /**
  13198. * Enables physics to the current scene
  13199. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  13200. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  13201. * @return {boolean} was the physics engine initialized
  13202. */
  13203. Scene.prototype.enablePhysics = function (gravity, plugin) {
  13204. if (this._physicsEngine) {
  13205. return true;
  13206. }
  13207. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  13208. if (!this._physicsEngine.isSupported()) {
  13209. this._physicsEngine = null;
  13210. return false;
  13211. }
  13212. this._physicsEngine._initialize(gravity);
  13213. return true;
  13214. };
  13215. Scene.prototype.disablePhysicsEngine = function () {
  13216. if (!this._physicsEngine) {
  13217. return;
  13218. }
  13219. this._physicsEngine.dispose();
  13220. this._physicsEngine = undefined;
  13221. };
  13222. Scene.prototype.isPhysicsEnabled = function () {
  13223. return this._physicsEngine !== undefined;
  13224. };
  13225. /**
  13226. * Sets the gravity of the physics engine (and NOT of the scene)
  13227. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  13228. */
  13229. Scene.prototype.setGravity = function (gravity) {
  13230. if (!this._physicsEngine) {
  13231. return;
  13232. }
  13233. this._physicsEngine._setGravity(gravity);
  13234. };
  13235. Scene.prototype.createCompoundImpostor = function (parts, options) {
  13236. if (parts.parts) {
  13237. options = parts;
  13238. parts = parts.parts;
  13239. }
  13240. if (!this._physicsEngine) {
  13241. return null;
  13242. }
  13243. for (var index = 0; index < parts.length; index++) {
  13244. var mesh = parts[index].mesh;
  13245. mesh._physicImpostor = parts[index].impostor;
  13246. mesh._physicsMass = options.mass / parts.length;
  13247. mesh._physicsFriction = options.friction;
  13248. mesh._physicRestitution = options.restitution;
  13249. }
  13250. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  13251. };
  13252. Scene.prototype.deleteCompoundImpostor = function (compound) {
  13253. for (var index = 0; index < compound.parts.length; index++) {
  13254. var mesh = compound.parts[index].mesh;
  13255. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  13256. this._physicsEngine._unregisterMesh(mesh);
  13257. }
  13258. };
  13259. // Misc.
  13260. Scene.prototype.createDefaultCameraOrLight = function () {
  13261. // Light
  13262. if (this.lights.length === 0) {
  13263. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  13264. }
  13265. // Camera
  13266. if (!this.activeCamera) {
  13267. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  13268. // Compute position
  13269. var worldExtends = this.getWorldExtends();
  13270. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  13271. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  13272. camera.setTarget(worldCenter);
  13273. this.activeCamera = camera;
  13274. }
  13275. };
  13276. // Tags
  13277. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  13278. if (tagsQuery === undefined) {
  13279. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  13280. return list;
  13281. }
  13282. var listByTags = [];
  13283. forEach = forEach || (function (item) { return; });
  13284. for (var i in list) {
  13285. var item = list[i];
  13286. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  13287. listByTags.push(item);
  13288. forEach(item);
  13289. }
  13290. }
  13291. return listByTags;
  13292. };
  13293. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  13294. return this._getByTags(this.meshes, tagsQuery, forEach);
  13295. };
  13296. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  13297. return this._getByTags(this.cameras, tagsQuery, forEach);
  13298. };
  13299. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  13300. return this._getByTags(this.lights, tagsQuery, forEach);
  13301. };
  13302. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  13303. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  13304. };
  13305. // Statics
  13306. Scene._FOGMODE_NONE = 0;
  13307. Scene._FOGMODE_EXP = 1;
  13308. Scene._FOGMODE_EXP2 = 2;
  13309. Scene._FOGMODE_LINEAR = 3;
  13310. Scene.MinDeltaTime = 1.0;
  13311. Scene.MaxDeltaTime = 1000.0;
  13312. return Scene;
  13313. })();
  13314. BABYLON.Scene = Scene;
  13315. })(BABYLON || (BABYLON = {}));
  13316. var BABYLON;
  13317. (function (BABYLON) {
  13318. var VertexBuffer = (function () {
  13319. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  13320. if (engine instanceof BABYLON.Mesh) {
  13321. this._engine = engine.getScene().getEngine();
  13322. }
  13323. else {
  13324. this._engine = engine;
  13325. }
  13326. this._updatable = updatable;
  13327. this._data = data;
  13328. if (!postponeInternalCreation) {
  13329. this.create();
  13330. }
  13331. this._kind = kind;
  13332. if (stride) {
  13333. this._strideSize = stride;
  13334. return;
  13335. }
  13336. // Deduce stride from kind
  13337. switch (kind) {
  13338. case VertexBuffer.PositionKind:
  13339. this._strideSize = 3;
  13340. break;
  13341. case VertexBuffer.NormalKind:
  13342. this._strideSize = 3;
  13343. break;
  13344. case VertexBuffer.UVKind:
  13345. case VertexBuffer.UV2Kind:
  13346. case VertexBuffer.UV3Kind:
  13347. case VertexBuffer.UV4Kind:
  13348. case VertexBuffer.UV5Kind:
  13349. case VertexBuffer.UV6Kind:
  13350. this._strideSize = 2;
  13351. break;
  13352. case VertexBuffer.ColorKind:
  13353. this._strideSize = 4;
  13354. break;
  13355. case VertexBuffer.MatricesIndicesKind:
  13356. this._strideSize = 4;
  13357. break;
  13358. case VertexBuffer.MatricesWeightsKind:
  13359. this._strideSize = 4;
  13360. break;
  13361. }
  13362. }
  13363. // Properties
  13364. VertexBuffer.prototype.isUpdatable = function () {
  13365. return this._updatable;
  13366. };
  13367. VertexBuffer.prototype.getData = function () {
  13368. return this._data;
  13369. };
  13370. VertexBuffer.prototype.getBuffer = function () {
  13371. return this._buffer;
  13372. };
  13373. VertexBuffer.prototype.getStrideSize = function () {
  13374. return this._strideSize;
  13375. };
  13376. // Methods
  13377. VertexBuffer.prototype.create = function (data) {
  13378. if (!data && this._buffer) {
  13379. return; // nothing to do
  13380. }
  13381. data = data || this._data;
  13382. if (!this._buffer) {
  13383. if (this._updatable) {
  13384. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  13385. }
  13386. else {
  13387. this._buffer = this._engine.createVertexBuffer(data);
  13388. }
  13389. }
  13390. if (this._updatable) {
  13391. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  13392. this._data = data;
  13393. }
  13394. };
  13395. VertexBuffer.prototype.update = function (data) {
  13396. this.create(data);
  13397. };
  13398. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  13399. if (!this._buffer) {
  13400. return;
  13401. }
  13402. if (this._updatable) {
  13403. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  13404. this._data = null;
  13405. }
  13406. };
  13407. VertexBuffer.prototype.dispose = function () {
  13408. if (!this._buffer) {
  13409. return;
  13410. }
  13411. if (this._engine._releaseBuffer(this._buffer)) {
  13412. this._buffer = null;
  13413. }
  13414. };
  13415. Object.defineProperty(VertexBuffer, "PositionKind", {
  13416. get: function () {
  13417. return VertexBuffer._PositionKind;
  13418. },
  13419. enumerable: true,
  13420. configurable: true
  13421. });
  13422. Object.defineProperty(VertexBuffer, "NormalKind", {
  13423. get: function () {
  13424. return VertexBuffer._NormalKind;
  13425. },
  13426. enumerable: true,
  13427. configurable: true
  13428. });
  13429. Object.defineProperty(VertexBuffer, "UVKind", {
  13430. get: function () {
  13431. return VertexBuffer._UVKind;
  13432. },
  13433. enumerable: true,
  13434. configurable: true
  13435. });
  13436. Object.defineProperty(VertexBuffer, "UV2Kind", {
  13437. get: function () {
  13438. return VertexBuffer._UV2Kind;
  13439. },
  13440. enumerable: true,
  13441. configurable: true
  13442. });
  13443. Object.defineProperty(VertexBuffer, "UV3Kind", {
  13444. get: function () {
  13445. return VertexBuffer._UV3Kind;
  13446. },
  13447. enumerable: true,
  13448. configurable: true
  13449. });
  13450. Object.defineProperty(VertexBuffer, "UV4Kind", {
  13451. get: function () {
  13452. return VertexBuffer._UV4Kind;
  13453. },
  13454. enumerable: true,
  13455. configurable: true
  13456. });
  13457. Object.defineProperty(VertexBuffer, "UV5Kind", {
  13458. get: function () {
  13459. return VertexBuffer._UV5Kind;
  13460. },
  13461. enumerable: true,
  13462. configurable: true
  13463. });
  13464. Object.defineProperty(VertexBuffer, "UV6Kind", {
  13465. get: function () {
  13466. return VertexBuffer._UV6Kind;
  13467. },
  13468. enumerable: true,
  13469. configurable: true
  13470. });
  13471. Object.defineProperty(VertexBuffer, "ColorKind", {
  13472. get: function () {
  13473. return VertexBuffer._ColorKind;
  13474. },
  13475. enumerable: true,
  13476. configurable: true
  13477. });
  13478. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  13479. get: function () {
  13480. return VertexBuffer._MatricesIndicesKind;
  13481. },
  13482. enumerable: true,
  13483. configurable: true
  13484. });
  13485. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  13486. get: function () {
  13487. return VertexBuffer._MatricesWeightsKind;
  13488. },
  13489. enumerable: true,
  13490. configurable: true
  13491. });
  13492. // Enums
  13493. VertexBuffer._PositionKind = "position";
  13494. VertexBuffer._NormalKind = "normal";
  13495. VertexBuffer._UVKind = "uv";
  13496. VertexBuffer._UV2Kind = "uv2";
  13497. VertexBuffer._UV3Kind = "uv3";
  13498. VertexBuffer._UV4Kind = "uv4";
  13499. VertexBuffer._UV5Kind = "uv5";
  13500. VertexBuffer._UV6Kind = "uv6";
  13501. VertexBuffer._ColorKind = "color";
  13502. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  13503. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  13504. return VertexBuffer;
  13505. })();
  13506. BABYLON.VertexBuffer = VertexBuffer;
  13507. })(BABYLON || (BABYLON = {}));
  13508. var BABYLON;
  13509. (function (BABYLON) {
  13510. /**
  13511. * Creates an instance based on a source mesh.
  13512. */
  13513. var InstancedMesh = (function (_super) {
  13514. __extends(InstancedMesh, _super);
  13515. function InstancedMesh(name, source) {
  13516. _super.call(this, name, source.getScene());
  13517. source.instances.push(this);
  13518. this._sourceMesh = source;
  13519. this.position.copyFrom(source.position);
  13520. this.rotation.copyFrom(source.rotation);
  13521. this.scaling.copyFrom(source.scaling);
  13522. if (source.rotationQuaternion) {
  13523. this.rotationQuaternion = source.rotationQuaternion.clone();
  13524. }
  13525. this.infiniteDistance = source.infiniteDistance;
  13526. this.setPivotMatrix(source.getPivotMatrix());
  13527. this.refreshBoundingInfo();
  13528. this._syncSubMeshes();
  13529. }
  13530. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  13531. // Methods
  13532. get: function () {
  13533. return this._sourceMesh.receiveShadows;
  13534. },
  13535. enumerable: true,
  13536. configurable: true
  13537. });
  13538. Object.defineProperty(InstancedMesh.prototype, "material", {
  13539. get: function () {
  13540. return this._sourceMesh.material;
  13541. },
  13542. enumerable: true,
  13543. configurable: true
  13544. });
  13545. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  13546. get: function () {
  13547. return this._sourceMesh.visibility;
  13548. },
  13549. enumerable: true,
  13550. configurable: true
  13551. });
  13552. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  13553. get: function () {
  13554. return this._sourceMesh.skeleton;
  13555. },
  13556. enumerable: true,
  13557. configurable: true
  13558. });
  13559. InstancedMesh.prototype.getTotalVertices = function () {
  13560. return this._sourceMesh.getTotalVertices();
  13561. };
  13562. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  13563. get: function () {
  13564. return this._sourceMesh;
  13565. },
  13566. enumerable: true,
  13567. configurable: true
  13568. });
  13569. InstancedMesh.prototype.getVerticesData = function (kind) {
  13570. return this._sourceMesh.getVerticesData(kind);
  13571. };
  13572. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  13573. return this._sourceMesh.isVerticesDataPresent(kind);
  13574. };
  13575. InstancedMesh.prototype.getIndices = function () {
  13576. return this._sourceMesh.getIndices();
  13577. };
  13578. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  13579. get: function () {
  13580. return this._sourceMesh._positions;
  13581. },
  13582. enumerable: true,
  13583. configurable: true
  13584. });
  13585. InstancedMesh.prototype.refreshBoundingInfo = function () {
  13586. var meshBB = this._sourceMesh.getBoundingInfo();
  13587. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  13588. this._updateBoundingInfo();
  13589. };
  13590. InstancedMesh.prototype._preActivate = function () {
  13591. if (this._currentLOD) {
  13592. this._currentLOD._preActivate();
  13593. }
  13594. };
  13595. InstancedMesh.prototype._activate = function (renderId) {
  13596. if (this._currentLOD) {
  13597. this._currentLOD._registerInstanceForRenderId(this, renderId);
  13598. }
  13599. };
  13600. InstancedMesh.prototype.getLOD = function (camera) {
  13601. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  13602. if (this._currentLOD === this.sourceMesh) {
  13603. return this;
  13604. }
  13605. return this._currentLOD;
  13606. };
  13607. InstancedMesh.prototype._syncSubMeshes = function () {
  13608. this.releaseSubMeshes();
  13609. if (this._sourceMesh.subMeshes) {
  13610. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  13611. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  13612. }
  13613. }
  13614. };
  13615. InstancedMesh.prototype._generatePointsArray = function () {
  13616. return this._sourceMesh._generatePointsArray();
  13617. };
  13618. // Clone
  13619. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  13620. var result = this._sourceMesh.createInstance(name);
  13621. // Deep copy
  13622. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  13623. // Bounding info
  13624. this.refreshBoundingInfo();
  13625. // Parent
  13626. if (newParent) {
  13627. result.parent = newParent;
  13628. }
  13629. if (!doNotCloneChildren) {
  13630. // Children
  13631. for (var index = 0; index < this.getScene().meshes.length; index++) {
  13632. var mesh = this.getScene().meshes[index];
  13633. if (mesh.parent === this) {
  13634. mesh.clone(mesh.name, result);
  13635. }
  13636. }
  13637. }
  13638. result.computeWorldMatrix(true);
  13639. return result;
  13640. };
  13641. // Dispoe
  13642. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  13643. // Remove from mesh
  13644. var index = this._sourceMesh.instances.indexOf(this);
  13645. this._sourceMesh.instances.splice(index, 1);
  13646. _super.prototype.dispose.call(this, doNotRecurse);
  13647. };
  13648. return InstancedMesh;
  13649. })(BABYLON.AbstractMesh);
  13650. BABYLON.InstancedMesh = InstancedMesh;
  13651. })(BABYLON || (BABYLON = {}));
  13652. var BABYLON;
  13653. (function (BABYLON) {
  13654. var _InstancesBatch = (function () {
  13655. function _InstancesBatch() {
  13656. this.mustReturn = false;
  13657. this.visibleInstances = new Array();
  13658. this.renderSelf = new Array();
  13659. }
  13660. return _InstancesBatch;
  13661. })();
  13662. BABYLON._InstancesBatch = _InstancesBatch;
  13663. var Mesh = (function (_super) {
  13664. __extends(Mesh, _super);
  13665. /**
  13666. * @constructor
  13667. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  13668. * @param {Scene} scene - The scene to add this mesh to.
  13669. * @param {Node} parent - The parent of this mesh, if it has one
  13670. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  13671. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  13672. * When false, achieved by calling a clone(), also passing False.
  13673. * This will make creation of children, recursive.
  13674. */
  13675. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  13676. if (parent === void 0) { parent = null; }
  13677. _super.call(this, name, scene);
  13678. // Members
  13679. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  13680. this.instances = new Array();
  13681. this._LODLevels = new Array();
  13682. this._onBeforeRenderCallbacks = new Array();
  13683. this._onAfterRenderCallbacks = new Array();
  13684. this._visibleInstances = {};
  13685. this._renderIdForInstances = new Array();
  13686. this._batchCache = new _InstancesBatch();
  13687. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  13688. this._sideOrientation = Mesh._DEFAULTSIDE;
  13689. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  13690. if (source) {
  13691. // Geometry
  13692. if (source._geometry) {
  13693. source._geometry.applyToMesh(this);
  13694. }
  13695. // Deep copy
  13696. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], []);
  13697. this.id = name + "." + source.id;
  13698. // Material
  13699. this.material = source.material;
  13700. var index;
  13701. if (!doNotCloneChildren) {
  13702. // Children
  13703. for (index = 0; index < scene.meshes.length; index++) {
  13704. var mesh = scene.meshes[index];
  13705. if (mesh.parent === source) {
  13706. // doNotCloneChildren is always going to be False
  13707. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  13708. }
  13709. }
  13710. }
  13711. // Particles
  13712. for (index = 0; index < scene.particleSystems.length; index++) {
  13713. var system = scene.particleSystems[index];
  13714. if (system.emitter === source) {
  13715. system.clone(system.name, this);
  13716. }
  13717. }
  13718. this.computeWorldMatrix(true);
  13719. }
  13720. // Parent
  13721. if (parent !== null) {
  13722. this.parent = parent;
  13723. }
  13724. }
  13725. Object.defineProperty(Mesh, "FRONTSIDE", {
  13726. get: function () {
  13727. return Mesh._FRONTSIDE;
  13728. },
  13729. enumerable: true,
  13730. configurable: true
  13731. });
  13732. Object.defineProperty(Mesh, "BACKSIDE", {
  13733. get: function () {
  13734. return Mesh._BACKSIDE;
  13735. },
  13736. enumerable: true,
  13737. configurable: true
  13738. });
  13739. Object.defineProperty(Mesh, "DOUBLESIDE", {
  13740. get: function () {
  13741. return Mesh._DOUBLESIDE;
  13742. },
  13743. enumerable: true,
  13744. configurable: true
  13745. });
  13746. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  13747. get: function () {
  13748. return Mesh._DEFAULTSIDE;
  13749. },
  13750. enumerable: true,
  13751. configurable: true
  13752. });
  13753. Object.defineProperty(Mesh, "NO_CAP", {
  13754. get: function () {
  13755. return Mesh._NO_CAP;
  13756. },
  13757. enumerable: true,
  13758. configurable: true
  13759. });
  13760. Object.defineProperty(Mesh, "CAP_START", {
  13761. get: function () {
  13762. return Mesh._CAP_START;
  13763. },
  13764. enumerable: true,
  13765. configurable: true
  13766. });
  13767. Object.defineProperty(Mesh, "CAP_END", {
  13768. get: function () {
  13769. return Mesh._CAP_END;
  13770. },
  13771. enumerable: true,
  13772. configurable: true
  13773. });
  13774. Object.defineProperty(Mesh, "CAP_ALL", {
  13775. get: function () {
  13776. return Mesh._CAP_ALL;
  13777. },
  13778. enumerable: true,
  13779. configurable: true
  13780. });
  13781. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  13782. // Methods
  13783. get: function () {
  13784. return this._LODLevels.length > 0;
  13785. },
  13786. enumerable: true,
  13787. configurable: true
  13788. });
  13789. Mesh.prototype._sortLODLevels = function () {
  13790. this._LODLevels.sort(function (a, b) {
  13791. if (a.distance < b.distance) {
  13792. return 1;
  13793. }
  13794. if (a.distance > b.distance) {
  13795. return -1;
  13796. }
  13797. return 0;
  13798. });
  13799. };
  13800. /**
  13801. * Add a mesh as LOD level triggered at the given distance.
  13802. * @param {number} distance - the distance from the center of the object to show this level
  13803. * @param {BABYLON.Mesh} mesh - the mesh to be added as LOD level
  13804. * @return {BABYLON.Mesh} this mesh (for chaining)
  13805. */
  13806. Mesh.prototype.addLODLevel = function (distance, mesh) {
  13807. if (mesh && mesh._masterMesh) {
  13808. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  13809. return this;
  13810. }
  13811. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  13812. this._LODLevels.push(level);
  13813. if (mesh) {
  13814. mesh._masterMesh = this;
  13815. }
  13816. this._sortLODLevels();
  13817. return this;
  13818. };
  13819. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  13820. for (var index = 0; index < this._LODLevels.length; index++) {
  13821. var level = this._LODLevels[index];
  13822. if (level.distance === distance) {
  13823. return level.mesh;
  13824. }
  13825. }
  13826. return null;
  13827. };
  13828. /**
  13829. * Remove a mesh from the LOD array
  13830. * @param {BABYLON.Mesh} mesh - the mesh to be removed.
  13831. * @return {BABYLON.Mesh} this mesh (for chaining)
  13832. */
  13833. Mesh.prototype.removeLODLevel = function (mesh) {
  13834. for (var index = 0; index < this._LODLevels.length; index++) {
  13835. if (this._LODLevels[index].mesh === mesh) {
  13836. this._LODLevels.splice(index, 1);
  13837. if (mesh) {
  13838. mesh._masterMesh = null;
  13839. }
  13840. }
  13841. }
  13842. this._sortLODLevels();
  13843. return this;
  13844. };
  13845. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  13846. if (!this._LODLevels || this._LODLevels.length === 0) {
  13847. return this;
  13848. }
  13849. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  13850. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  13851. if (this.onLODLevelSelection) {
  13852. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  13853. }
  13854. return this;
  13855. }
  13856. for (var index = 0; index < this._LODLevels.length; index++) {
  13857. var level = this._LODLevels[index];
  13858. if (level.distance < distanceToCamera) {
  13859. if (level.mesh) {
  13860. level.mesh._preActivate();
  13861. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  13862. }
  13863. if (this.onLODLevelSelection) {
  13864. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  13865. }
  13866. return level.mesh;
  13867. }
  13868. }
  13869. if (this.onLODLevelSelection) {
  13870. this.onLODLevelSelection(distanceToCamera, this, this);
  13871. }
  13872. return this;
  13873. };
  13874. Object.defineProperty(Mesh.prototype, "geometry", {
  13875. get: function () {
  13876. return this._geometry;
  13877. },
  13878. enumerable: true,
  13879. configurable: true
  13880. });
  13881. Mesh.prototype.getTotalVertices = function () {
  13882. if (!this._geometry) {
  13883. return 0;
  13884. }
  13885. return this._geometry.getTotalVertices();
  13886. };
  13887. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  13888. if (!this._geometry) {
  13889. return null;
  13890. }
  13891. return this._geometry.getVerticesData(kind, copyWhenShared);
  13892. };
  13893. Mesh.prototype.getVertexBuffer = function (kind) {
  13894. if (!this._geometry) {
  13895. return undefined;
  13896. }
  13897. return this._geometry.getVertexBuffer(kind);
  13898. };
  13899. Mesh.prototype.isVerticesDataPresent = function (kind) {
  13900. if (!this._geometry) {
  13901. if (this._delayInfo) {
  13902. return this._delayInfo.indexOf(kind) !== -1;
  13903. }
  13904. return false;
  13905. }
  13906. return this._geometry.isVerticesDataPresent(kind);
  13907. };
  13908. Mesh.prototype.getVerticesDataKinds = function () {
  13909. if (!this._geometry) {
  13910. var result = [];
  13911. if (this._delayInfo) {
  13912. for (var kind in this._delayInfo) {
  13913. result.push(kind);
  13914. }
  13915. }
  13916. return result;
  13917. }
  13918. return this._geometry.getVerticesDataKinds();
  13919. };
  13920. Mesh.prototype.getTotalIndices = function () {
  13921. if (!this._geometry) {
  13922. return 0;
  13923. }
  13924. return this._geometry.getTotalIndices();
  13925. };
  13926. Mesh.prototype.getIndices = function (copyWhenShared) {
  13927. if (!this._geometry) {
  13928. return [];
  13929. }
  13930. return this._geometry.getIndices(copyWhenShared);
  13931. };
  13932. Object.defineProperty(Mesh.prototype, "isBlocked", {
  13933. get: function () {
  13934. return this._masterMesh !== null && this._masterMesh !== undefined;
  13935. },
  13936. enumerable: true,
  13937. configurable: true
  13938. });
  13939. Mesh.prototype.isReady = function () {
  13940. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  13941. return false;
  13942. }
  13943. return _super.prototype.isReady.call(this);
  13944. };
  13945. Mesh.prototype.isDisposed = function () {
  13946. return this._isDisposed;
  13947. };
  13948. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  13949. get: function () {
  13950. return this._sideOrientation;
  13951. },
  13952. set: function (sideO) {
  13953. this._sideOrientation = sideO;
  13954. },
  13955. enumerable: true,
  13956. configurable: true
  13957. });
  13958. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  13959. get: function () {
  13960. return this._areNormalsFrozen;
  13961. },
  13962. enumerable: true,
  13963. configurable: true
  13964. });
  13965. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  13966. Mesh.prototype.freezeNormals = function () {
  13967. this._areNormalsFrozen = true;
  13968. };
  13969. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  13970. Mesh.prototype.unfreezeNormals = function () {
  13971. this._areNormalsFrozen = false;
  13972. };
  13973. // Methods
  13974. Mesh.prototype._preActivate = function () {
  13975. var sceneRenderId = this.getScene().getRenderId();
  13976. if (this._preActivateId === sceneRenderId) {
  13977. return;
  13978. }
  13979. this._preActivateId = sceneRenderId;
  13980. this._visibleInstances = null;
  13981. };
  13982. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  13983. if (!this._visibleInstances) {
  13984. this._visibleInstances = {};
  13985. this._visibleInstances.defaultRenderId = renderId;
  13986. this._visibleInstances.selfDefaultRenderId = this._renderId;
  13987. }
  13988. if (!this._visibleInstances[renderId]) {
  13989. this._visibleInstances[renderId] = new Array();
  13990. }
  13991. this._visibleInstances[renderId].push(instance);
  13992. };
  13993. Mesh.prototype.refreshBoundingInfo = function () {
  13994. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13995. if (data) {
  13996. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  13997. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  13998. }
  13999. if (this.subMeshes) {
  14000. for (var index = 0; index < this.subMeshes.length; index++) {
  14001. this.subMeshes[index].refreshBoundingInfo();
  14002. }
  14003. }
  14004. this._updateBoundingInfo();
  14005. };
  14006. Mesh.prototype._createGlobalSubMesh = function () {
  14007. var totalVertices = this.getTotalVertices();
  14008. if (!totalVertices || !this.getIndices()) {
  14009. return null;
  14010. }
  14011. this.releaseSubMeshes();
  14012. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  14013. };
  14014. Mesh.prototype.subdivide = function (count) {
  14015. if (count < 1) {
  14016. return;
  14017. }
  14018. var totalIndices = this.getTotalIndices();
  14019. var subdivisionSize = (totalIndices / count) | 0;
  14020. var offset = 0;
  14021. // Ensure that subdivisionSize is a multiple of 3
  14022. while (subdivisionSize % 3 !== 0) {
  14023. subdivisionSize++;
  14024. }
  14025. this.releaseSubMeshes();
  14026. for (var index = 0; index < count; index++) {
  14027. if (offset >= totalIndices) {
  14028. break;
  14029. }
  14030. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  14031. offset += subdivisionSize;
  14032. }
  14033. this.synchronizeInstances();
  14034. };
  14035. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  14036. if (!this._geometry) {
  14037. var vertexData = new BABYLON.VertexData();
  14038. vertexData.set(data, kind);
  14039. var scene = this.getScene();
  14040. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  14041. }
  14042. else {
  14043. this._geometry.setVerticesData(kind, data, updatable, stride);
  14044. }
  14045. };
  14046. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  14047. if (!this._geometry) {
  14048. return;
  14049. }
  14050. if (!makeItUnique) {
  14051. this._geometry.updateVerticesData(kind, data, updateExtends);
  14052. }
  14053. else {
  14054. this.makeGeometryUnique();
  14055. this.updateVerticesData(kind, data, updateExtends, false);
  14056. }
  14057. };
  14058. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  14059. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  14060. if (!this._geometry) {
  14061. return;
  14062. }
  14063. if (!makeItUnique) {
  14064. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  14065. }
  14066. else {
  14067. this.makeGeometryUnique();
  14068. this.updateVerticesDataDirectly(kind, data, offset, false);
  14069. }
  14070. };
  14071. // Mesh positions update function :
  14072. // updates the mesh positions according to the positionFunction returned values.
  14073. // The positionFunction argument must be a javascript function accepting the mesh "positions" array as parameter.
  14074. // This dedicated positionFunction computes new mesh positions according to the given mesh type.
  14075. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  14076. if (computeNormals === void 0) { computeNormals = true; }
  14077. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14078. positionFunction(positions);
  14079. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  14080. if (computeNormals) {
  14081. var indices = this.getIndices();
  14082. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14083. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  14084. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  14085. }
  14086. };
  14087. Mesh.prototype.makeGeometryUnique = function () {
  14088. if (!this._geometry) {
  14089. return;
  14090. }
  14091. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  14092. geometry.applyToMesh(this);
  14093. };
  14094. Mesh.prototype.setIndices = function (indices, totalVertices) {
  14095. if (!this._geometry) {
  14096. var vertexData = new BABYLON.VertexData();
  14097. vertexData.indices = indices;
  14098. var scene = this.getScene();
  14099. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  14100. }
  14101. else {
  14102. this._geometry.setIndices(indices, totalVertices);
  14103. }
  14104. };
  14105. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  14106. var engine = this.getScene().getEngine();
  14107. // Wireframe
  14108. var indexToBind;
  14109. switch (fillMode) {
  14110. case BABYLON.Material.PointFillMode:
  14111. indexToBind = null;
  14112. break;
  14113. case BABYLON.Material.WireFrameFillMode:
  14114. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  14115. break;
  14116. default:
  14117. case BABYLON.Material.TriangleFillMode:
  14118. indexToBind = this._geometry.getIndexBuffer();
  14119. break;
  14120. }
  14121. // VBOs
  14122. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  14123. };
  14124. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  14125. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  14126. return;
  14127. }
  14128. var engine = this.getScene().getEngine();
  14129. // Draw order
  14130. switch (fillMode) {
  14131. case BABYLON.Material.PointFillMode:
  14132. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  14133. break;
  14134. case BABYLON.Material.WireFrameFillMode:
  14135. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  14136. break;
  14137. default:
  14138. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  14139. }
  14140. };
  14141. Mesh.prototype.registerBeforeRender = function (func) {
  14142. this._onBeforeRenderCallbacks.push(func);
  14143. };
  14144. Mesh.prototype.unregisterBeforeRender = function (func) {
  14145. var index = this._onBeforeRenderCallbacks.indexOf(func);
  14146. if (index > -1) {
  14147. this._onBeforeRenderCallbacks.splice(index, 1);
  14148. }
  14149. };
  14150. Mesh.prototype.registerAfterRender = function (func) {
  14151. this._onAfterRenderCallbacks.push(func);
  14152. };
  14153. Mesh.prototype.unregisterAfterRender = function (func) {
  14154. var index = this._onAfterRenderCallbacks.indexOf(func);
  14155. if (index > -1) {
  14156. this._onAfterRenderCallbacks.splice(index, 1);
  14157. }
  14158. };
  14159. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  14160. var scene = this.getScene();
  14161. this._batchCache.mustReturn = false;
  14162. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  14163. this._batchCache.visibleInstances[subMeshId] = null;
  14164. if (this._visibleInstances) {
  14165. var currentRenderId = scene.getRenderId();
  14166. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  14167. var selfRenderId = this._renderId;
  14168. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  14169. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  14170. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  14171. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  14172. }
  14173. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  14174. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  14175. this._batchCache.mustReturn = true;
  14176. return this._batchCache;
  14177. }
  14178. if (currentRenderId !== selfRenderId) {
  14179. this._batchCache.renderSelf[subMeshId] = false;
  14180. }
  14181. }
  14182. this._renderIdForInstances[subMeshId] = currentRenderId;
  14183. }
  14184. return this._batchCache;
  14185. };
  14186. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  14187. var visibleInstances = batch.visibleInstances[subMesh._id];
  14188. var matricesCount = visibleInstances.length + 1;
  14189. var bufferSize = matricesCount * 16 * 4;
  14190. while (this._instancesBufferSize < bufferSize) {
  14191. this._instancesBufferSize *= 2;
  14192. }
  14193. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  14194. if (this._worldMatricesInstancesBuffer) {
  14195. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  14196. }
  14197. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  14198. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  14199. }
  14200. var offset = 0;
  14201. var instancesCount = 0;
  14202. var world = this.getWorldMatrix();
  14203. if (batch.renderSelf[subMesh._id]) {
  14204. world.copyToArray(this._worldMatricesInstancesArray, offset);
  14205. offset += 16;
  14206. instancesCount++;
  14207. }
  14208. if (visibleInstances) {
  14209. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  14210. var instance = visibleInstances[instanceIndex];
  14211. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  14212. offset += 16;
  14213. instancesCount++;
  14214. }
  14215. }
  14216. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  14217. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  14218. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  14219. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  14220. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  14221. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  14222. this._draw(subMesh, fillMode, instancesCount);
  14223. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  14224. };
  14225. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  14226. var scene = this.getScene();
  14227. var engine = scene.getEngine();
  14228. if (hardwareInstancedRendering) {
  14229. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  14230. }
  14231. else {
  14232. if (batch.renderSelf[subMesh._id]) {
  14233. // Draw
  14234. if (onBeforeDraw) {
  14235. onBeforeDraw(false, this.getWorldMatrix());
  14236. }
  14237. this._draw(subMesh, fillMode);
  14238. }
  14239. if (batch.visibleInstances[subMesh._id]) {
  14240. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  14241. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  14242. // World
  14243. var world = instance.getWorldMatrix();
  14244. if (onBeforeDraw) {
  14245. onBeforeDraw(true, world);
  14246. }
  14247. // Draw
  14248. this._draw(subMesh, fillMode);
  14249. }
  14250. }
  14251. }
  14252. };
  14253. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  14254. var scene = this.getScene();
  14255. // Managing instances
  14256. var batch = this._getInstancesRenderList(subMesh._id);
  14257. if (batch.mustReturn) {
  14258. return;
  14259. }
  14260. // Checking geometry state
  14261. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  14262. return;
  14263. }
  14264. var callbackIndex;
  14265. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  14266. this._onBeforeRenderCallbacks[callbackIndex](this);
  14267. }
  14268. var engine = scene.getEngine();
  14269. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  14270. // Material
  14271. var effectiveMaterial = subMesh.getMaterial();
  14272. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  14273. return;
  14274. }
  14275. // Outline - step 1
  14276. var savedDepthWrite = engine.getDepthWrite();
  14277. if (this.renderOutline) {
  14278. engine.setDepthWrite(false);
  14279. scene.getOutlineRenderer().render(subMesh, batch);
  14280. engine.setDepthWrite(savedDepthWrite);
  14281. }
  14282. effectiveMaterial._preBind();
  14283. var effect = effectiveMaterial.getEffect();
  14284. // Bind
  14285. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  14286. this._bind(subMesh, effect, fillMode);
  14287. var world = this.getWorldMatrix();
  14288. effectiveMaterial.bind(world, this);
  14289. // Alpha mode
  14290. if (enableAlphaMode) {
  14291. engine.setAlphaMode(effectiveMaterial.alphaMode);
  14292. }
  14293. // Draw
  14294. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  14295. if (isInstance) {
  14296. effectiveMaterial.bindOnlyWorldMatrix(world);
  14297. }
  14298. });
  14299. // Unbind
  14300. effectiveMaterial.unbind();
  14301. // Outline - step 2
  14302. if (this.renderOutline && savedDepthWrite) {
  14303. engine.setDepthWrite(true);
  14304. engine.setColorWrite(false);
  14305. scene.getOutlineRenderer().render(subMesh, batch);
  14306. engine.setColorWrite(true);
  14307. }
  14308. // Overlay
  14309. if (this.renderOverlay) {
  14310. var currentMode = engine.getAlphaMode();
  14311. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  14312. scene.getOutlineRenderer().render(subMesh, batch, true);
  14313. engine.setAlphaMode(currentMode);
  14314. }
  14315. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  14316. this._onAfterRenderCallbacks[callbackIndex](this);
  14317. }
  14318. };
  14319. Mesh.prototype.getEmittedParticleSystems = function () {
  14320. var results = new Array();
  14321. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  14322. var particleSystem = this.getScene().particleSystems[index];
  14323. if (particleSystem.emitter === this) {
  14324. results.push(particleSystem);
  14325. }
  14326. }
  14327. return results;
  14328. };
  14329. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  14330. var results = new Array();
  14331. var descendants = this.getDescendants();
  14332. descendants.push(this);
  14333. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  14334. var particleSystem = this.getScene().particleSystems[index];
  14335. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  14336. results.push(particleSystem);
  14337. }
  14338. }
  14339. return results;
  14340. };
  14341. Mesh.prototype.getChildren = function () {
  14342. var results = [];
  14343. for (var index = 0; index < this.getScene().meshes.length; index++) {
  14344. var mesh = this.getScene().meshes[index];
  14345. if (mesh.parent === this) {
  14346. results.push(mesh);
  14347. }
  14348. }
  14349. return results;
  14350. };
  14351. Mesh.prototype._checkDelayState = function () {
  14352. var _this = this;
  14353. var that = this;
  14354. var scene = this.getScene();
  14355. if (this._geometry) {
  14356. this._geometry.load(scene);
  14357. }
  14358. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  14359. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  14360. scene._addPendingData(that);
  14361. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  14362. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  14363. if (data instanceof ArrayBuffer) {
  14364. _this._delayLoadingFunction(data, _this);
  14365. }
  14366. else {
  14367. _this._delayLoadingFunction(JSON.parse(data), _this);
  14368. }
  14369. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  14370. scene._removePendingData(_this);
  14371. }, function () { }, scene.database, getBinaryData);
  14372. }
  14373. };
  14374. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  14375. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  14376. return false;
  14377. }
  14378. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  14379. return false;
  14380. }
  14381. this._checkDelayState();
  14382. return true;
  14383. };
  14384. Mesh.prototype.setMaterialByID = function (id) {
  14385. var materials = this.getScene().materials;
  14386. var index;
  14387. for (index = 0; index < materials.length; index++) {
  14388. if (materials[index].id === id) {
  14389. this.material = materials[index];
  14390. return;
  14391. }
  14392. }
  14393. // Multi
  14394. var multiMaterials = this.getScene().multiMaterials;
  14395. for (index = 0; index < multiMaterials.length; index++) {
  14396. if (multiMaterials[index].id === id) {
  14397. this.material = multiMaterials[index];
  14398. return;
  14399. }
  14400. }
  14401. };
  14402. Mesh.prototype.getAnimatables = function () {
  14403. var results = [];
  14404. if (this.material) {
  14405. results.push(this.material);
  14406. }
  14407. if (this.skeleton) {
  14408. results.push(this.skeleton);
  14409. }
  14410. return results;
  14411. };
  14412. // Geometry
  14413. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  14414. // Position
  14415. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  14416. return;
  14417. }
  14418. this._resetPointsArrayCache();
  14419. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14420. var temp = [];
  14421. var index;
  14422. for (index = 0; index < data.length; index += 3) {
  14423. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  14424. }
  14425. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  14426. // Normals
  14427. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  14428. return;
  14429. }
  14430. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14431. temp = [];
  14432. for (index = 0; index < data.length; index += 3) {
  14433. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  14434. }
  14435. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  14436. // flip faces?
  14437. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  14438. this.flipFaces();
  14439. }
  14440. };
  14441. // Will apply current transform to mesh and reset world matrix
  14442. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  14443. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  14444. this.scaling.copyFromFloats(1, 1, 1);
  14445. this.position.copyFromFloats(0, 0, 0);
  14446. this.rotation.copyFromFloats(0, 0, 0);
  14447. //only if quaternion is already set
  14448. if (this.rotationQuaternion) {
  14449. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  14450. }
  14451. this._worldMatrix = BABYLON.Matrix.Identity();
  14452. };
  14453. // Cache
  14454. Mesh.prototype._resetPointsArrayCache = function () {
  14455. this._positions = null;
  14456. };
  14457. Mesh.prototype._generatePointsArray = function () {
  14458. if (this._positions)
  14459. return true;
  14460. this._positions = [];
  14461. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14462. if (!data) {
  14463. return false;
  14464. }
  14465. for (var index = 0; index < data.length; index += 3) {
  14466. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  14467. }
  14468. return true;
  14469. };
  14470. // Clone
  14471. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  14472. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  14473. };
  14474. // Dispose
  14475. Mesh.prototype.dispose = function (doNotRecurse) {
  14476. if (this._geometry) {
  14477. this._geometry.releaseForMesh(this, true);
  14478. }
  14479. // Instances
  14480. if (this._worldMatricesInstancesBuffer) {
  14481. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  14482. this._worldMatricesInstancesBuffer = null;
  14483. }
  14484. while (this.instances.length) {
  14485. this.instances[0].dispose();
  14486. }
  14487. _super.prototype.dispose.call(this, doNotRecurse);
  14488. };
  14489. // Geometric tools
  14490. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  14491. var _this = this;
  14492. var scene = this.getScene();
  14493. var onload = function (img) {
  14494. // Getting height map data
  14495. var canvas = document.createElement("canvas");
  14496. var context = canvas.getContext("2d");
  14497. var heightMapWidth = img.width;
  14498. var heightMapHeight = img.height;
  14499. canvas.width = heightMapWidth;
  14500. canvas.height = heightMapHeight;
  14501. context.drawImage(img, 0, 0);
  14502. // Create VertexData from map data
  14503. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  14504. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  14505. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  14506. //execute success callback, if set
  14507. if (onSuccess) {
  14508. onSuccess(_this);
  14509. }
  14510. };
  14511. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  14512. };
  14513. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  14514. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  14515. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  14516. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  14517. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  14518. return;
  14519. }
  14520. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14521. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14522. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  14523. var position = BABYLON.Vector3.Zero();
  14524. var normal = BABYLON.Vector3.Zero();
  14525. var uv = BABYLON.Vector2.Zero();
  14526. for (var index = 0; index < positions.length; index += 3) {
  14527. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  14528. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  14529. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  14530. // Compute height
  14531. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  14532. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  14533. var pos = (u + v * heightMapWidth) * 4;
  14534. var r = buffer[pos] / 255.0;
  14535. var g = buffer[pos + 1] / 255.0;
  14536. var b = buffer[pos + 2] / 255.0;
  14537. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  14538. normal.normalize();
  14539. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  14540. position = position.add(normal);
  14541. position.toArray(positions, index);
  14542. }
  14543. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  14544. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  14545. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  14546. };
  14547. Mesh.prototype.convertToFlatShadedMesh = function () {
  14548. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  14549. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  14550. var kinds = this.getVerticesDataKinds();
  14551. var vbs = [];
  14552. var data = [];
  14553. var newdata = [];
  14554. var updatableNormals = false;
  14555. var kindIndex;
  14556. var kind;
  14557. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  14558. kind = kinds[kindIndex];
  14559. var vertexBuffer = this.getVertexBuffer(kind);
  14560. if (kind === BABYLON.VertexBuffer.NormalKind) {
  14561. updatableNormals = vertexBuffer.isUpdatable();
  14562. kinds.splice(kindIndex, 1);
  14563. kindIndex--;
  14564. continue;
  14565. }
  14566. vbs[kind] = vertexBuffer;
  14567. data[kind] = vbs[kind].getData();
  14568. newdata[kind] = [];
  14569. }
  14570. // Save previous submeshes
  14571. var previousSubmeshes = this.subMeshes.slice(0);
  14572. var indices = this.getIndices();
  14573. var totalIndices = this.getTotalIndices();
  14574. // Generating unique vertices per face
  14575. var index;
  14576. for (index = 0; index < totalIndices; index++) {
  14577. var vertexIndex = indices[index];
  14578. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  14579. kind = kinds[kindIndex];
  14580. var stride = vbs[kind].getStrideSize();
  14581. for (var offset = 0; offset < stride; offset++) {
  14582. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  14583. }
  14584. }
  14585. }
  14586. // Updating faces & normal
  14587. var normals = [];
  14588. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  14589. for (index = 0; index < totalIndices; index += 3) {
  14590. indices[index] = index;
  14591. indices[index + 1] = index + 1;
  14592. indices[index + 2] = index + 2;
  14593. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  14594. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  14595. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  14596. var p1p2 = p1.subtract(p2);
  14597. var p3p2 = p3.subtract(p2);
  14598. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  14599. // Store same normals for every vertex
  14600. for (var localIndex = 0; localIndex < 3; localIndex++) {
  14601. normals.push(normal.x);
  14602. normals.push(normal.y);
  14603. normals.push(normal.z);
  14604. }
  14605. }
  14606. this.setIndices(indices);
  14607. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  14608. // Updating vertex buffers
  14609. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  14610. kind = kinds[kindIndex];
  14611. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  14612. }
  14613. // Updating submeshes
  14614. this.releaseSubMeshes();
  14615. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  14616. var previousOne = previousSubmeshes[submeshIndex];
  14617. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  14618. }
  14619. this.synchronizeInstances();
  14620. };
  14621. // will inverse faces orientations, and invert normals too if specified
  14622. Mesh.prototype.flipFaces = function (flipNormals) {
  14623. if (flipNormals === void 0) { flipNormals = false; }
  14624. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  14625. var i;
  14626. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  14627. for (i = 0; i < vertex_data.normals.length; i++) {
  14628. vertex_data.normals[i] *= -1;
  14629. }
  14630. }
  14631. var temp;
  14632. for (i = 0; i < vertex_data.indices.length; i += 3) {
  14633. // reassign indices
  14634. temp = vertex_data.indices[i + 1];
  14635. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  14636. vertex_data.indices[i + 2] = temp;
  14637. }
  14638. vertex_data.applyToMesh(this);
  14639. };
  14640. // Instances
  14641. Mesh.prototype.createInstance = function (name) {
  14642. return new BABYLON.InstancedMesh(name, this);
  14643. };
  14644. Mesh.prototype.synchronizeInstances = function () {
  14645. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  14646. var instance = this.instances[instanceIndex];
  14647. instance._syncSubMeshes();
  14648. }
  14649. };
  14650. /**
  14651. * Simplify the mesh according to the given array of settings.
  14652. * Function will return immediately and will simplify async.
  14653. * @param settings a collection of simplification settings.
  14654. * @param parallelProcessing should all levels calculate parallel or one after the other.
  14655. * @param type the type of simplification to run.
  14656. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  14657. */
  14658. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  14659. if (parallelProcessing === void 0) { parallelProcessing = true; }
  14660. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  14661. this.getScene().simplificationQueue.addTask({
  14662. settings: settings,
  14663. parallelProcessing: parallelProcessing,
  14664. mesh: this,
  14665. simplificationType: simplificationType,
  14666. successCallback: successCallback
  14667. });
  14668. };
  14669. /**
  14670. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  14671. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  14672. * This should be used together with the simplification to avoid disappearing triangles.
  14673. * @param successCallback an optional success callback to be called after the optimization finished.
  14674. */
  14675. Mesh.prototype.optimizeIndices = function (successCallback) {
  14676. var _this = this;
  14677. var indices = this.getIndices();
  14678. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14679. var vectorPositions = [];
  14680. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  14681. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  14682. }
  14683. var dupes = [];
  14684. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  14685. var realPos = vectorPositions.length - 1 - iteration;
  14686. var testedPosition = vectorPositions[realPos];
  14687. for (var j = 0; j < realPos; ++j) {
  14688. var againstPosition = vectorPositions[j];
  14689. if (testedPosition.equals(againstPosition)) {
  14690. dupes[realPos] = j;
  14691. break;
  14692. }
  14693. }
  14694. }, function () {
  14695. for (var i = 0; i < indices.length; ++i) {
  14696. indices[i] = dupes[indices[i]] || indices[i];
  14697. }
  14698. //indices are now reordered
  14699. var originalSubMeshes = _this.subMeshes.slice(0);
  14700. _this.setIndices(indices);
  14701. _this.subMeshes = originalSubMeshes;
  14702. if (successCallback) {
  14703. successCallback(_this);
  14704. }
  14705. });
  14706. };
  14707. // Statics
  14708. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  14709. return BABYLON.MeshBuilder.CreateRibbon(name, {
  14710. pathArray: pathArray,
  14711. closeArray: closeArray,
  14712. closePath: closePath,
  14713. offset: offset,
  14714. updatable: updatable,
  14715. sideOrientation: sideOrientation,
  14716. instance: instance
  14717. }, scene);
  14718. };
  14719. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  14720. var options = {
  14721. radius: radius,
  14722. tessellation: tessellation,
  14723. sideOrientation: sideOrientation,
  14724. updatable: updatable
  14725. };
  14726. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  14727. };
  14728. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  14729. var options = {
  14730. size: size,
  14731. sideOrientation: sideOrientation,
  14732. updatable: updatable
  14733. };
  14734. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  14735. };
  14736. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  14737. var options = {
  14738. segments: segments,
  14739. diameterX: diameter,
  14740. diameterY: diameter,
  14741. diameterZ: diameter,
  14742. sideOrientation: sideOrientation,
  14743. updatable: updatable
  14744. };
  14745. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  14746. };
  14747. // Cylinder and cone
  14748. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  14749. var options = {
  14750. height: height,
  14751. diameterTop: diameterTop,
  14752. diameterBottom: diameterBottom,
  14753. tessellation: tessellation,
  14754. subdivisions: subdivisions,
  14755. sideOrientation: sideOrientation,
  14756. updatable: updatable
  14757. };
  14758. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  14759. };
  14760. // Torus (Code from SharpDX.org)
  14761. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  14762. var options = {
  14763. diameter: diameter,
  14764. thickness: thickness,
  14765. tessellation: tessellation,
  14766. sideOrientation: sideOrientation,
  14767. updatable: updatable
  14768. };
  14769. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  14770. };
  14771. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  14772. var options = {
  14773. radius: radius,
  14774. tube: tube,
  14775. radialSegments: radialSegments,
  14776. tubularSegments: tubularSegments,
  14777. p: p,
  14778. q: q,
  14779. sideOrientation: sideOrientation,
  14780. updatable: updatable
  14781. };
  14782. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  14783. };
  14784. // Lines
  14785. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  14786. var options = {
  14787. points: points,
  14788. updatable: updatable,
  14789. instance: instance
  14790. };
  14791. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  14792. };
  14793. // Dashed Lines
  14794. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  14795. var options = {
  14796. points: points,
  14797. dashSize: dashSize,
  14798. gapSize: gapSize,
  14799. dashNb: dashNb,
  14800. updatable: updatable
  14801. };
  14802. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  14803. };
  14804. // Extrusion
  14805. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  14806. var options = {
  14807. shape: shape,
  14808. path: path,
  14809. scale: scale,
  14810. rotation: rotation,
  14811. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  14812. sideOrientation: sideOrientation,
  14813. instance: instance,
  14814. updatable: updatable
  14815. };
  14816. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  14817. };
  14818. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  14819. var options = {
  14820. shape: shape,
  14821. path: path,
  14822. scaleFunction: scaleFunction,
  14823. rotationFunction: rotationFunction,
  14824. ribbonCloseArray: ribbonCloseArray,
  14825. ribbonClosePath: ribbonClosePath,
  14826. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  14827. sideOrientation: sideOrientation,
  14828. instance: instance,
  14829. updatable: updatable
  14830. };
  14831. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  14832. };
  14833. // Lathe
  14834. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  14835. var options = {
  14836. shape: shape,
  14837. radius: radius,
  14838. tesselation: tessellation,
  14839. sideOrientation: sideOrientation,
  14840. updatable: updatable
  14841. };
  14842. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  14843. };
  14844. // Plane & ground
  14845. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  14846. var options = {
  14847. size: size,
  14848. width: size,
  14849. height: size,
  14850. sideOrientation: sideOrientation,
  14851. updatable: updatable
  14852. };
  14853. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  14854. };
  14855. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  14856. var options = {
  14857. width: width,
  14858. height: height,
  14859. subdivisions: subdivisions,
  14860. updatable: updatable
  14861. };
  14862. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  14863. };
  14864. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  14865. var options = {
  14866. xmin: xmin,
  14867. zmin: zmin,
  14868. xmax: xmax,
  14869. zmax: zmax,
  14870. subdivisions: subdivisions,
  14871. precision: precision,
  14872. updatable: updatable
  14873. };
  14874. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  14875. };
  14876. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  14877. var options = {
  14878. width: width,
  14879. height: height,
  14880. subdivisions: subdivisions,
  14881. minHeight: minHeight,
  14882. maxHeight: maxHeight,
  14883. updatable: updatable,
  14884. onReady: onReady
  14885. };
  14886. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  14887. };
  14888. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  14889. var options = {
  14890. path: path,
  14891. radius: radius,
  14892. tessellation: tessellation,
  14893. radiusFunction: radiusFunction,
  14894. arc: 1,
  14895. cap: cap,
  14896. updatable: updatable,
  14897. sideOrientation: sideOrientation,
  14898. instance: instance
  14899. };
  14900. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  14901. };
  14902. Mesh.CreatePolyhedron = function (name, options, scene) {
  14903. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  14904. };
  14905. // Decals
  14906. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  14907. var options = {
  14908. position: position,
  14909. normal: normal,
  14910. size: size,
  14911. angle: angle
  14912. };
  14913. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  14914. };
  14915. // Skeletons
  14916. /**
  14917. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  14918. */
  14919. Mesh.prototype.setPositionsForCPUSkinning = function () {
  14920. var source;
  14921. if (!this._sourcePositions) {
  14922. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14923. this._sourcePositions = new Float32Array(source);
  14924. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  14925. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  14926. }
  14927. }
  14928. return this._sourcePositions;
  14929. };
  14930. /**
  14931. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  14932. */
  14933. Mesh.prototype.setNormalsForCPUSkinning = function () {
  14934. var source;
  14935. if (!this._sourceNormals) {
  14936. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14937. this._sourceNormals = new Float32Array(source);
  14938. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  14939. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  14940. }
  14941. }
  14942. return this._sourceNormals;
  14943. };
  14944. /**
  14945. * Update the vertex buffers by applying transformation from the bones
  14946. * @param {skeleton} skeleton to apply
  14947. */
  14948. Mesh.prototype.applySkeleton = function (skeleton) {
  14949. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  14950. return this;
  14951. }
  14952. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  14953. return this;
  14954. }
  14955. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  14956. return this;
  14957. }
  14958. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  14959. return this;
  14960. }
  14961. if (!this._sourcePositions) {
  14962. this.setPositionsForCPUSkinning();
  14963. }
  14964. if (!this._sourceNormals) {
  14965. this.setNormalsForCPUSkinning();
  14966. }
  14967. // positionsData checks for not being Float32Array will only pass at most once
  14968. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14969. if (!(positionsData instanceof Float32Array)) {
  14970. positionsData = new Float32Array(positionsData);
  14971. }
  14972. // normalsData checks for not being Float32Array will only pass at most once
  14973. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14974. if (!(normalsData instanceof Float32Array)) {
  14975. normalsData = new Float32Array(normalsData);
  14976. }
  14977. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  14978. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  14979. var skeletonMatrices = skeleton.getTransformMatrices();
  14980. var tempVector3 = BABYLON.Vector3.Zero();
  14981. var finalMatrix = new BABYLON.Matrix();
  14982. var tempMatrix = new BABYLON.Matrix();
  14983. for (var index = 0; index < positionsData.length; index += 3) {
  14984. var index4 = (index / 3) * 4;
  14985. var matricesWeight0 = matricesWeightsData[index4];
  14986. var matricesWeight1 = matricesWeightsData[index4 + 1];
  14987. var matricesWeight2 = matricesWeightsData[index4 + 2];
  14988. var matricesWeight3 = matricesWeightsData[index4 + 3];
  14989. if (matricesWeight0 > 0) {
  14990. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[index4] * 16, matricesWeight0, tempMatrix);
  14991. finalMatrix.addToSelf(tempMatrix);
  14992. }
  14993. if (matricesWeight1 > 0) {
  14994. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[index4 + 1] * 16, matricesWeight1, tempMatrix);
  14995. finalMatrix.addToSelf(tempMatrix);
  14996. }
  14997. if (matricesWeight2 > 0) {
  14998. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[index4 + 2] * 16, matricesWeight2, tempMatrix);
  14999. finalMatrix.addToSelf(tempMatrix);
  15000. }
  15001. if (matricesWeight3 > 0) {
  15002. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[index4 + 3] * 16, matricesWeight3, tempMatrix);
  15003. finalMatrix.addToSelf(tempMatrix);
  15004. }
  15005. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  15006. tempVector3.toArray(positionsData, index);
  15007. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  15008. tempVector3.toArray(normalsData, index);
  15009. finalMatrix.reset();
  15010. }
  15011. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  15012. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  15013. return this;
  15014. };
  15015. // Tools
  15016. Mesh.MinMax = function (meshes) {
  15017. var minVector = null;
  15018. var maxVector = null;
  15019. for (var i in meshes) {
  15020. var mesh = meshes[i];
  15021. var boundingBox = mesh.getBoundingInfo().boundingBox;
  15022. if (!minVector) {
  15023. minVector = boundingBox.minimumWorld;
  15024. maxVector = boundingBox.maximumWorld;
  15025. continue;
  15026. }
  15027. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  15028. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  15029. }
  15030. return {
  15031. min: minVector,
  15032. max: maxVector
  15033. };
  15034. };
  15035. Mesh.Center = function (meshesOrMinMaxVector) {
  15036. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  15037. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  15038. };
  15039. /**
  15040. * Merge the array of meshes into a single mesh for performance reasons.
  15041. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  15042. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  15043. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  15044. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  15045. */
  15046. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  15047. if (disposeSource === void 0) { disposeSource = true; }
  15048. var index;
  15049. if (!allow32BitsIndices) {
  15050. var totalVertices = 0;
  15051. // Counting vertices
  15052. for (index = 0; index < meshes.length; index++) {
  15053. if (meshes[index]) {
  15054. totalVertices += meshes[index].getTotalVertices();
  15055. if (totalVertices > 65536) {
  15056. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  15057. return null;
  15058. }
  15059. }
  15060. }
  15061. }
  15062. // Merge
  15063. var vertexData;
  15064. var otherVertexData;
  15065. var source;
  15066. for (index = 0; index < meshes.length; index++) {
  15067. if (meshes[index]) {
  15068. meshes[index].computeWorldMatrix(true);
  15069. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  15070. otherVertexData.transform(meshes[index].getWorldMatrix());
  15071. if (vertexData) {
  15072. vertexData.merge(otherVertexData);
  15073. }
  15074. else {
  15075. vertexData = otherVertexData;
  15076. source = meshes[index];
  15077. }
  15078. }
  15079. }
  15080. if (!meshSubclass) {
  15081. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  15082. }
  15083. vertexData.applyToMesh(meshSubclass);
  15084. // Setting properties
  15085. meshSubclass.material = source.material;
  15086. meshSubclass.checkCollisions = source.checkCollisions;
  15087. // Cleaning
  15088. if (disposeSource) {
  15089. for (index = 0; index < meshes.length; index++) {
  15090. if (meshes[index]) {
  15091. meshes[index].dispose();
  15092. }
  15093. }
  15094. }
  15095. return meshSubclass;
  15096. };
  15097. // Consts
  15098. Mesh._FRONTSIDE = 0;
  15099. Mesh._BACKSIDE = 1;
  15100. Mesh._DOUBLESIDE = 2;
  15101. Mesh._DEFAULTSIDE = 0;
  15102. Mesh._NO_CAP = 0;
  15103. Mesh._CAP_START = 1;
  15104. Mesh._CAP_END = 2;
  15105. Mesh._CAP_ALL = 3;
  15106. return Mesh;
  15107. })(BABYLON.AbstractMesh);
  15108. BABYLON.Mesh = Mesh;
  15109. })(BABYLON || (BABYLON = {}));
  15110. var BABYLON;
  15111. (function (BABYLON) {
  15112. var SubMesh = (function () {
  15113. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  15114. if (createBoundingBox === void 0) { createBoundingBox = true; }
  15115. this.materialIndex = materialIndex;
  15116. this.verticesStart = verticesStart;
  15117. this.verticesCount = verticesCount;
  15118. this.indexStart = indexStart;
  15119. this.indexCount = indexCount;
  15120. this._renderId = 0;
  15121. this._mesh = mesh;
  15122. this._renderingMesh = renderingMesh || mesh;
  15123. mesh.subMeshes.push(this);
  15124. this._trianglePlanes = [];
  15125. this._id = mesh.subMeshes.length - 1;
  15126. if (createBoundingBox) {
  15127. this.refreshBoundingInfo();
  15128. mesh.computeWorldMatrix(true);
  15129. }
  15130. }
  15131. SubMesh.prototype.getBoundingInfo = function () {
  15132. return this._boundingInfo;
  15133. };
  15134. SubMesh.prototype.getMesh = function () {
  15135. return this._mesh;
  15136. };
  15137. SubMesh.prototype.getRenderingMesh = function () {
  15138. return this._renderingMesh;
  15139. };
  15140. SubMesh.prototype.getMaterial = function () {
  15141. var rootMaterial = this._renderingMesh.material;
  15142. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  15143. var multiMaterial = rootMaterial;
  15144. return multiMaterial.getSubMaterial(this.materialIndex);
  15145. }
  15146. if (!rootMaterial) {
  15147. return this._mesh.getScene().defaultMaterial;
  15148. }
  15149. return rootMaterial;
  15150. };
  15151. // Methods
  15152. SubMesh.prototype.refreshBoundingInfo = function () {
  15153. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15154. if (!data) {
  15155. this._boundingInfo = this._mesh._boundingInfo;
  15156. return;
  15157. }
  15158. var indices = this._renderingMesh.getIndices();
  15159. var extend;
  15160. //is this the only submesh?
  15161. if (this.indexStart === 0 && this.indexCount === indices.length) {
  15162. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  15163. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  15164. }
  15165. else {
  15166. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  15167. }
  15168. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  15169. };
  15170. SubMesh.prototype._checkCollision = function (collider) {
  15171. return this._boundingInfo._checkCollision(collider);
  15172. };
  15173. SubMesh.prototype.updateBoundingInfo = function (world) {
  15174. if (!this._boundingInfo) {
  15175. this.refreshBoundingInfo();
  15176. }
  15177. this._boundingInfo._update(world);
  15178. };
  15179. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  15180. return this._boundingInfo.isInFrustum(frustumPlanes);
  15181. };
  15182. SubMesh.prototype.render = function (enableAlphaMode) {
  15183. this._renderingMesh.render(this, enableAlphaMode);
  15184. };
  15185. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  15186. if (!this._linesIndexBuffer) {
  15187. var linesIndices = [];
  15188. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  15189. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  15190. }
  15191. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  15192. this.linesIndexCount = linesIndices.length;
  15193. }
  15194. return this._linesIndexBuffer;
  15195. };
  15196. SubMesh.prototype.canIntersects = function (ray) {
  15197. return ray.intersectsBox(this._boundingInfo.boundingBox);
  15198. };
  15199. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  15200. var intersectInfo = null;
  15201. // Triangles test
  15202. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  15203. var p0 = positions[indices[index]];
  15204. var p1 = positions[indices[index + 1]];
  15205. var p2 = positions[indices[index + 2]];
  15206. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  15207. if (currentIntersectInfo) {
  15208. if (currentIntersectInfo.distance < 0) {
  15209. continue;
  15210. }
  15211. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  15212. intersectInfo = currentIntersectInfo;
  15213. intersectInfo.faceId = index / 3;
  15214. if (fastCheck) {
  15215. break;
  15216. }
  15217. }
  15218. }
  15219. }
  15220. return intersectInfo;
  15221. };
  15222. // Clone
  15223. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  15224. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  15225. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  15226. return result;
  15227. };
  15228. // Dispose
  15229. SubMesh.prototype.dispose = function () {
  15230. if (this._linesIndexBuffer) {
  15231. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  15232. this._linesIndexBuffer = null;
  15233. }
  15234. // Remove from mesh
  15235. var index = this._mesh.subMeshes.indexOf(this);
  15236. this._mesh.subMeshes.splice(index, 1);
  15237. };
  15238. // Statics
  15239. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  15240. var minVertexIndex = Number.MAX_VALUE;
  15241. var maxVertexIndex = -Number.MAX_VALUE;
  15242. renderingMesh = renderingMesh || mesh;
  15243. var indices = renderingMesh.getIndices();
  15244. for (var index = startIndex; index < startIndex + indexCount; index++) {
  15245. var vertexIndex = indices[index];
  15246. if (vertexIndex < minVertexIndex)
  15247. minVertexIndex = vertexIndex;
  15248. if (vertexIndex > maxVertexIndex)
  15249. maxVertexIndex = vertexIndex;
  15250. }
  15251. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  15252. };
  15253. return SubMesh;
  15254. })();
  15255. BABYLON.SubMesh = SubMesh;
  15256. })(BABYLON || (BABYLON = {}));
  15257. var BABYLON;
  15258. (function (BABYLON) {
  15259. var MeshBuilder = (function () {
  15260. function MeshBuilder() {
  15261. }
  15262. MeshBuilder.CreateBox = function (name, options, scene) {
  15263. var box = new BABYLON.Mesh(name, scene);
  15264. var vertexData = BABYLON.VertexData.CreateBox(options);
  15265. vertexData.applyToMesh(box, options.updatable);
  15266. return box;
  15267. };
  15268. MeshBuilder.CreateSphere = function (name, options, scene) {
  15269. var sphere = new BABYLON.Mesh(name, scene);
  15270. var vertexData = BABYLON.VertexData.CreateSphere(options);
  15271. vertexData.applyToMesh(sphere, options.updatable);
  15272. return sphere;
  15273. };
  15274. MeshBuilder.CreateDisc = function (name, options, scene) {
  15275. var disc = new BABYLON.Mesh(name, scene);
  15276. var vertexData = BABYLON.VertexData.CreateDisc(options);
  15277. vertexData.applyToMesh(disc, options.updatable);
  15278. return disc;
  15279. };
  15280. MeshBuilder.CreateRibbon = function (name, options, scene) {
  15281. var pathArray = options.pathArray;
  15282. var closeArray = options.closeArray;
  15283. var closePath = options.closePath;
  15284. var offset = options.offset;
  15285. var sideOrientation = options.sideOrientation;
  15286. var instance = options.instance;
  15287. var updatable = options.updatable;
  15288. if (instance) {
  15289. // positionFunction : ribbon case
  15290. // only pathArray and sideOrientation parameters are taken into account for positions update
  15291. var positionFunction = function (positions) {
  15292. var minlg = pathArray[0].length;
  15293. var i = 0;
  15294. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  15295. for (var si = 1; si <= ns; si++) {
  15296. for (var p = 0; p < pathArray.length; p++) {
  15297. var path = pathArray[p];
  15298. var l = path.length;
  15299. minlg = (minlg < l) ? minlg : l;
  15300. var j = 0;
  15301. while (j < minlg) {
  15302. positions[i] = path[j].x;
  15303. positions[i + 1] = path[j].y;
  15304. positions[i + 2] = path[j].z;
  15305. j++;
  15306. i += 3;
  15307. }
  15308. if (instance._closePath) {
  15309. positions[i] = path[0].x;
  15310. positions[i + 1] = path[0].y;
  15311. positions[i + 2] = path[0].z;
  15312. i += 3;
  15313. }
  15314. }
  15315. }
  15316. };
  15317. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15318. positionFunction(positions);
  15319. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  15320. if (!(instance.areNormalsFrozen)) {
  15321. var indices = instance.getIndices();
  15322. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15323. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  15324. if (instance._closePath) {
  15325. var indexFirst = 0;
  15326. var indexLast = 0;
  15327. for (var p = 0; p < pathArray.length; p++) {
  15328. indexFirst = instance._idx[p] * 3;
  15329. if (p + 1 < pathArray.length) {
  15330. indexLast = (instance._idx[p + 1] - 1) * 3;
  15331. }
  15332. else {
  15333. indexLast = normals.length - 3;
  15334. }
  15335. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  15336. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  15337. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  15338. normals[indexLast] = normals[indexFirst];
  15339. normals[indexLast + 1] = normals[indexFirst + 1];
  15340. normals[indexLast + 2] = normals[indexFirst + 2];
  15341. }
  15342. }
  15343. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  15344. }
  15345. return instance;
  15346. }
  15347. else {
  15348. var ribbon = new BABYLON.Mesh(name, scene);
  15349. ribbon.sideOrientation = sideOrientation;
  15350. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  15351. if (closePath) {
  15352. ribbon._idx = vertexData._idx;
  15353. }
  15354. ribbon._closePath = closePath;
  15355. ribbon._closeArray = closeArray;
  15356. vertexData.applyToMesh(ribbon, updatable);
  15357. return ribbon;
  15358. }
  15359. };
  15360. MeshBuilder.CreateCylinder = function (name, options, scene) {
  15361. var cylinder = new BABYLON.Mesh(name, scene);
  15362. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  15363. vertexData.applyToMesh(cylinder, options.updatable);
  15364. return cylinder;
  15365. };
  15366. MeshBuilder.CreateTorus = function (name, options, scene) {
  15367. var torus = new BABYLON.Mesh(name, scene);
  15368. var vertexData = BABYLON.VertexData.CreateTorus(options);
  15369. vertexData.applyToMesh(torus, options.updatable);
  15370. return torus;
  15371. };
  15372. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  15373. var torusKnot = new BABYLON.Mesh(name, scene);
  15374. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  15375. vertexData.applyToMesh(torusKnot, options.updatable);
  15376. return torusKnot;
  15377. };
  15378. MeshBuilder.CreateLines = function (name, options, scene) {
  15379. var instance = options.instance;
  15380. var points = options.points;
  15381. if (instance) {
  15382. var positionFunction = function (positions) {
  15383. var i = 0;
  15384. for (var p = 0; p < points.length; p++) {
  15385. positions[i] = points[p].x;
  15386. positions[i + 1] = points[p].y;
  15387. positions[i + 2] = points[p].z;
  15388. i += 3;
  15389. }
  15390. };
  15391. instance.updateMeshPositions(positionFunction, false);
  15392. return instance;
  15393. }
  15394. // lines creation
  15395. var lines = new BABYLON.LinesMesh(name, scene);
  15396. var vertexData = BABYLON.VertexData.CreateLines(options);
  15397. vertexData.applyToMesh(lines, options.updatable);
  15398. return lines;
  15399. };
  15400. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  15401. var points = options.points;
  15402. var instance = options.instance;
  15403. var gapSize = options.gapSize;
  15404. var dashNb = options.dashNb;
  15405. var dashSize = options.dashSize;
  15406. if (instance) {
  15407. var positionFunction = function (positions) {
  15408. var curvect = BABYLON.Vector3.Zero();
  15409. var nbSeg = positions.length / 6;
  15410. var lg = 0;
  15411. var nb = 0;
  15412. var shft = 0;
  15413. var dashshft = 0;
  15414. var curshft = 0;
  15415. var p = 0;
  15416. var i = 0;
  15417. var j = 0;
  15418. for (i = 0; i < points.length - 1; i++) {
  15419. points[i + 1].subtractToRef(points[i], curvect);
  15420. lg += curvect.length();
  15421. }
  15422. shft = lg / nbSeg;
  15423. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  15424. for (i = 0; i < points.length - 1; i++) {
  15425. points[i + 1].subtractToRef(points[i], curvect);
  15426. nb = Math.floor(curvect.length() / shft);
  15427. curvect.normalize();
  15428. j = 0;
  15429. while (j < nb && p < positions.length) {
  15430. curshft = shft * j;
  15431. positions[p] = points[i].x + curshft * curvect.x;
  15432. positions[p + 1] = points[i].y + curshft * curvect.y;
  15433. positions[p + 2] = points[i].z + curshft * curvect.z;
  15434. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  15435. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  15436. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  15437. p += 6;
  15438. j++;
  15439. }
  15440. }
  15441. while (p < positions.length) {
  15442. positions[p] = points[i].x;
  15443. positions[p + 1] = points[i].y;
  15444. positions[p + 2] = points[i].z;
  15445. p += 3;
  15446. }
  15447. };
  15448. instance.updateMeshPositions(positionFunction, false);
  15449. return instance;
  15450. }
  15451. // dashed lines creation
  15452. var dashedLines = new BABYLON.LinesMesh(name, scene);
  15453. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  15454. vertexData.applyToMesh(dashedLines, options.updatable);
  15455. dashedLines.dashSize = dashSize;
  15456. dashedLines.gapSize = gapSize;
  15457. return dashedLines;
  15458. };
  15459. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  15460. var path = options.path;
  15461. var shape = options.shape;
  15462. var scale = options.scale || 1;
  15463. var rotation = options.rotation || 0;
  15464. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  15465. var updatable = options.updatable;
  15466. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  15467. var instance = options.instance;
  15468. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance);
  15469. };
  15470. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  15471. var path = options.path;
  15472. var shape = options.shape;
  15473. var scaleFunction = options.scaleFunction || (function () { return 1; });
  15474. var rotationFunction = options.rotationFunction || (function () { return 0; });
  15475. var ribbonCloseArray = options.ribbonCloseArray || false;
  15476. var ribbonClosePath = options.ribbonClosePath || false;
  15477. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  15478. var updatable = options.updatable;
  15479. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  15480. var instance = options.instance;
  15481. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance);
  15482. };
  15483. MeshBuilder.CreateLathe = function (name, options, scene) {
  15484. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  15485. var closed = (options.closed === undefined) ? true : options.closed;
  15486. var shape = options.shape;
  15487. var radius = options.radius || 1;
  15488. var tessellation = options.tessellation || 64;
  15489. var updatable = options.updatable;
  15490. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  15491. var pi2 = Math.PI * 2;
  15492. var shapeLathe = new Array();
  15493. // first rotatable point
  15494. var i = 0;
  15495. while (shape[i].x === 0) {
  15496. i++;
  15497. }
  15498. var pt = shape[i];
  15499. for (i = 0; i < shape.length; i++) {
  15500. shapeLathe.push(shape[i].subtract(pt));
  15501. }
  15502. // circle path
  15503. var step = pi2 / tessellation * arc;
  15504. var rotated;
  15505. var path = new Array();
  15506. ;
  15507. for (i = 0; i <= tessellation; i++) {
  15508. rotated = new BABYLON.Vector3(Math.cos(i * step) * radius, 0, Math.sin(i * step) * radius);
  15509. path.push(rotated);
  15510. }
  15511. if (closed) {
  15512. path.push(path[0]);
  15513. }
  15514. // extrusion
  15515. var scaleFunction = function () { return 1; };
  15516. var rotateFunction = function () { return 0; };
  15517. var lathe = BABYLON.Mesh.ExtrudeShapeCustom(name, shapeLathe, path, scaleFunction, rotateFunction, closed, false, BABYLON.Mesh.NO_CAP, scene, updatable, sideOrientation);
  15518. return lathe;
  15519. };
  15520. MeshBuilder.CreatePlane = function (name, options, scene) {
  15521. var plane = new BABYLON.Mesh(name, scene);
  15522. var vertexData = BABYLON.VertexData.CreatePlane(options);
  15523. vertexData.applyToMesh(plane, options.updatable);
  15524. if (options.sourcePlane) {
  15525. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  15526. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  15527. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  15528. plane.rotate(vectorProduct, product);
  15529. }
  15530. return plane;
  15531. };
  15532. MeshBuilder.CreateGround = function (name, options, scene) {
  15533. var ground = new BABYLON.GroundMesh(name, scene);
  15534. ground._setReady(false);
  15535. ground._subdivisions = options.subdivisions || 1;
  15536. var vertexData = BABYLON.VertexData.CreateGround(options);
  15537. vertexData.applyToMesh(ground, options.updatable);
  15538. ground._setReady(true);
  15539. return ground;
  15540. };
  15541. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  15542. var tiledGround = new BABYLON.Mesh(name, scene);
  15543. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  15544. vertexData.applyToMesh(tiledGround, options.updatable);
  15545. return tiledGround;
  15546. };
  15547. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  15548. var width = options.width || 10;
  15549. var height = options.height || 10;
  15550. var subdivisions = options.subdivisions || 1;
  15551. var minHeight = options.minHeight;
  15552. var maxHeight = options.maxHeight || 10;
  15553. var updatable = options.updatable;
  15554. var onReady = options.onReady;
  15555. var ground = new BABYLON.GroundMesh(name, scene);
  15556. ground._subdivisions = subdivisions;
  15557. ground._setReady(false);
  15558. var onload = function (img) {
  15559. // Getting height map data
  15560. var canvas = document.createElement("canvas");
  15561. var context = canvas.getContext("2d");
  15562. var bufferWidth = img.width;
  15563. var bufferHeight = img.height;
  15564. canvas.width = bufferWidth;
  15565. canvas.height = bufferHeight;
  15566. context.drawImage(img, 0, 0);
  15567. // Create VertexData from map data
  15568. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  15569. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  15570. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  15571. width: width, height: height,
  15572. subdivisions: subdivisions,
  15573. minHeight: minHeight, maxHeight: maxHeight,
  15574. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  15575. });
  15576. vertexData.applyToMesh(ground, updatable);
  15577. ground._setReady(true);
  15578. //execute ready callback, if set
  15579. if (onReady) {
  15580. onReady(ground);
  15581. }
  15582. };
  15583. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  15584. return ground;
  15585. };
  15586. MeshBuilder.CreateTube = function (name, options, scene) {
  15587. var path = options.path;
  15588. var radius = options.radius || 1;
  15589. var tessellation = options.tessellation || 64;
  15590. var radiusFunction = options.radiusFunction;
  15591. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  15592. var updatable = options.updatable;
  15593. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  15594. var instance = options.instance;
  15595. options.arc = (options.arc <= 0 || options.arc > 1) ? 1 : options.arc || 1;
  15596. // tube geometry
  15597. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  15598. var tangents = path3D.getTangents();
  15599. var normals = path3D.getNormals();
  15600. var distances = path3D.getDistances();
  15601. var pi2 = Math.PI * 2;
  15602. var step = pi2 / tessellation * arc;
  15603. var returnRadius = function () { return radius; };
  15604. var radiusFunctionFinal = radiusFunction || returnRadius;
  15605. var circlePath;
  15606. var rad;
  15607. var normal;
  15608. var rotated;
  15609. var rotationMatrix = BABYLON.Matrix.Zero();
  15610. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  15611. for (var i = 0; i < path.length; i++) {
  15612. rad = radiusFunctionFinal(i, distances[i]); // current radius
  15613. circlePath = Array(); // current circle array
  15614. normal = normals[i]; // current normal
  15615. for (var t = 0; t < tessellation; t++) {
  15616. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  15617. rotated = BABYLON.Vector3.TransformCoordinates(normal, rotationMatrix).scaleInPlace(rad).add(path[i]);
  15618. circlePath.push(rotated);
  15619. }
  15620. circlePaths[index] = circlePath;
  15621. index++;
  15622. }
  15623. // cap
  15624. var capPath = function (nbPoints, pathIndex) {
  15625. var pointCap = Array();
  15626. for (var i = 0; i < nbPoints; i++) {
  15627. pointCap.push(path[pathIndex]);
  15628. }
  15629. return pointCap;
  15630. };
  15631. switch (cap) {
  15632. case BABYLON.Mesh.NO_CAP:
  15633. break;
  15634. case BABYLON.Mesh.CAP_START:
  15635. circlePaths[0] = capPath(tessellation, 0);
  15636. circlePaths[1] = circlePaths[2].slice(0);
  15637. break;
  15638. case BABYLON.Mesh.CAP_END:
  15639. circlePaths[index] = circlePaths[index - 1].slice(0);
  15640. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  15641. break;
  15642. case BABYLON.Mesh.CAP_ALL:
  15643. circlePaths[0] = capPath(tessellation, 0);
  15644. circlePaths[1] = circlePaths[2].slice(0);
  15645. circlePaths[index] = circlePaths[index - 1].slice(0);
  15646. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  15647. break;
  15648. default:
  15649. break;
  15650. }
  15651. return circlePaths;
  15652. };
  15653. var path3D;
  15654. var pathArray;
  15655. if (instance) {
  15656. var arc = options.arc || instance.arc;
  15657. path3D = (instance.path3D).update(path);
  15658. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  15659. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  15660. instance.path3D = path3D;
  15661. instance.pathArray = pathArray;
  15662. instance.arc = arc;
  15663. return instance;
  15664. }
  15665. // tube creation
  15666. path3D = new BABYLON.Path3D(path);
  15667. var newPathArray = new Array();
  15668. cap = (cap < 0 || cap > 3) ? 0 : cap;
  15669. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  15670. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation }, scene);
  15671. tube.pathArray = pathArray;
  15672. tube.path3D = path3D;
  15673. tube.tessellation = tessellation;
  15674. tube.cap = cap;
  15675. tube.arc = options.arc;
  15676. return tube;
  15677. };
  15678. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  15679. var polyhedron = new BABYLON.Mesh(name, scene);
  15680. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  15681. vertexData.applyToMesh(polyhedron, options.updatable);
  15682. return polyhedron;
  15683. };
  15684. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  15685. var indices = sourceMesh.getIndices();
  15686. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15687. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15688. var position = options.position || BABYLON.Vector3.Zero();
  15689. var normal = options.normal || BABYLON.Vector3.Up();
  15690. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  15691. var angle = options.angle || 0;
  15692. // Getting correct rotation
  15693. if (!normal) {
  15694. var target = new BABYLON.Vector3(0, 0, 1);
  15695. var camera = sourceMesh.getScene().activeCamera;
  15696. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  15697. normal = camera.globalPosition.subtract(cameraWorldTarget);
  15698. }
  15699. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  15700. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  15701. var pitch = Math.atan2(normal.y, len);
  15702. // Matrix
  15703. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  15704. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  15705. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  15706. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  15707. var vertexData = new BABYLON.VertexData();
  15708. vertexData.indices = [];
  15709. vertexData.positions = [];
  15710. vertexData.normals = [];
  15711. vertexData.uvs = [];
  15712. var currentVertexDataIndex = 0;
  15713. var extractDecalVector3 = function (indexId) {
  15714. var vertexId = indices[indexId];
  15715. var result = new BABYLON.PositionNormalVertex();
  15716. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  15717. // Send vector to decal local world
  15718. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  15719. // Get normal
  15720. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  15721. return result;
  15722. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  15723. var clip = function (vertices, axis) {
  15724. if (vertices.length === 0) {
  15725. return vertices;
  15726. }
  15727. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  15728. var clipVertices = function (v0, v1) {
  15729. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  15730. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  15731. };
  15732. var result = new Array();
  15733. for (var index = 0; index < vertices.length; index += 3) {
  15734. var v1Out;
  15735. var v2Out;
  15736. var v3Out;
  15737. var total = 0;
  15738. var nV1, nV2, nV3, nV4;
  15739. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  15740. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  15741. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  15742. v1Out = d1 > 0;
  15743. v2Out = d2 > 0;
  15744. v3Out = d3 > 0;
  15745. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  15746. switch (total) {
  15747. case 0:
  15748. result.push(vertices[index]);
  15749. result.push(vertices[index + 1]);
  15750. result.push(vertices[index + 2]);
  15751. break;
  15752. case 1:
  15753. if (v1Out) {
  15754. nV1 = vertices[index + 1];
  15755. nV2 = vertices[index + 2];
  15756. nV3 = clipVertices(vertices[index], nV1);
  15757. nV4 = clipVertices(vertices[index], nV2);
  15758. }
  15759. if (v2Out) {
  15760. nV1 = vertices[index];
  15761. nV2 = vertices[index + 2];
  15762. nV3 = clipVertices(vertices[index + 1], nV1);
  15763. nV4 = clipVertices(vertices[index + 1], nV2);
  15764. result.push(nV3);
  15765. result.push(nV2.clone());
  15766. result.push(nV1.clone());
  15767. result.push(nV2.clone());
  15768. result.push(nV3.clone());
  15769. result.push(nV4);
  15770. break;
  15771. }
  15772. if (v3Out) {
  15773. nV1 = vertices[index];
  15774. nV2 = vertices[index + 1];
  15775. nV3 = clipVertices(vertices[index + 2], nV1);
  15776. nV4 = clipVertices(vertices[index + 2], nV2);
  15777. }
  15778. result.push(nV1.clone());
  15779. result.push(nV2.clone());
  15780. result.push(nV3);
  15781. result.push(nV4);
  15782. result.push(nV3.clone());
  15783. result.push(nV2.clone());
  15784. break;
  15785. case 2:
  15786. if (!v1Out) {
  15787. nV1 = vertices[index].clone();
  15788. nV2 = clipVertices(nV1, vertices[index + 1]);
  15789. nV3 = clipVertices(nV1, vertices[index + 2]);
  15790. result.push(nV1);
  15791. result.push(nV2);
  15792. result.push(nV3);
  15793. }
  15794. if (!v2Out) {
  15795. nV1 = vertices[index + 1].clone();
  15796. nV2 = clipVertices(nV1, vertices[index + 2]);
  15797. nV3 = clipVertices(nV1, vertices[index]);
  15798. result.push(nV1);
  15799. result.push(nV2);
  15800. result.push(nV3);
  15801. }
  15802. if (!v3Out) {
  15803. nV1 = vertices[index + 2].clone();
  15804. nV2 = clipVertices(nV1, vertices[index]);
  15805. nV3 = clipVertices(nV1, vertices[index + 1]);
  15806. result.push(nV1);
  15807. result.push(nV2);
  15808. result.push(nV3);
  15809. }
  15810. break;
  15811. case 3:
  15812. break;
  15813. }
  15814. }
  15815. return result;
  15816. };
  15817. for (var index = 0; index < indices.length; index += 3) {
  15818. var faceVertices = new Array();
  15819. faceVertices.push(extractDecalVector3(index));
  15820. faceVertices.push(extractDecalVector3(index + 1));
  15821. faceVertices.push(extractDecalVector3(index + 2));
  15822. // Clip
  15823. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  15824. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  15825. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  15826. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  15827. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  15828. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  15829. if (faceVertices.length === 0) {
  15830. continue;
  15831. }
  15832. // Add UVs and get back to world
  15833. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  15834. var vertex = faceVertices[vIndex];
  15835. vertexData.indices.push(currentVertexDataIndex);
  15836. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  15837. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  15838. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  15839. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  15840. currentVertexDataIndex++;
  15841. }
  15842. }
  15843. // Return mesh
  15844. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  15845. vertexData.applyToMesh(decal);
  15846. decal.position = position.clone();
  15847. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  15848. return decal;
  15849. };
  15850. // Privates
  15851. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance) {
  15852. // extrusion geometry
  15853. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  15854. var tangents = path3D.getTangents();
  15855. var normals = path3D.getNormals();
  15856. var binormals = path3D.getBinormals();
  15857. var distances = path3D.getDistances();
  15858. var angle = 0;
  15859. var returnScale = function () { return scale; };
  15860. var returnRotation = function () { return rotation; };
  15861. var rotate = custom ? rotateFunction : returnRotation;
  15862. var scl = custom ? scaleFunction : returnScale;
  15863. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  15864. var rotationMatrix = BABYLON.Matrix.Zero();
  15865. for (var i = 0; i < curve.length; i++) {
  15866. var shapePath = new Array();
  15867. var angleStep = rotate(i, distances[i]);
  15868. var scaleRatio = scl(i, distances[i]);
  15869. for (var p = 0; p < shape.length; p++) {
  15870. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  15871. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  15872. var rotated = BABYLON.Vector3.TransformCoordinates(planed, rotationMatrix).scaleInPlace(scaleRatio).add(curve[i]);
  15873. shapePath.push(rotated);
  15874. }
  15875. shapePaths[index] = shapePath;
  15876. angle += angleStep;
  15877. index++;
  15878. }
  15879. // cap
  15880. var capPath = function (shapePath) {
  15881. var pointCap = Array();
  15882. var barycenter = BABYLON.Vector3.Zero();
  15883. var i;
  15884. for (i = 0; i < shapePath.length; i++) {
  15885. barycenter.addInPlace(shapePath[i]);
  15886. }
  15887. barycenter.scaleInPlace(1 / shapePath.length);
  15888. for (i = 0; i < shapePath.length; i++) {
  15889. pointCap.push(barycenter);
  15890. }
  15891. return pointCap;
  15892. };
  15893. switch (cap) {
  15894. case BABYLON.Mesh.NO_CAP:
  15895. break;
  15896. case BABYLON.Mesh.CAP_START:
  15897. shapePaths[0] = capPath(shapePaths[2]);
  15898. shapePaths[1] = shapePaths[2].slice(0);
  15899. break;
  15900. case BABYLON.Mesh.CAP_END:
  15901. shapePaths[index] = shapePaths[index - 1];
  15902. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  15903. break;
  15904. case BABYLON.Mesh.CAP_ALL:
  15905. shapePaths[0] = capPath(shapePaths[2]);
  15906. shapePaths[1] = shapePaths[2].slice(0);
  15907. shapePaths[index] = shapePaths[index - 1];
  15908. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  15909. break;
  15910. default:
  15911. break;
  15912. }
  15913. return shapePaths;
  15914. };
  15915. var path3D;
  15916. var pathArray;
  15917. if (instance) {
  15918. path3D = (instance.path3D).update(curve);
  15919. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  15920. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  15921. return instance;
  15922. }
  15923. // extruded shape creation
  15924. path3D = new BABYLON.Path3D(curve);
  15925. var newShapePaths = new Array();
  15926. cap = (cap < 0 || cap > 3) ? 0 : cap;
  15927. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  15928. var extrudedGeneric = BABYLON.Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  15929. extrudedGeneric.pathArray = pathArray;
  15930. extrudedGeneric.path3D = path3D;
  15931. extrudedGeneric.cap = cap;
  15932. return extrudedGeneric;
  15933. };
  15934. return MeshBuilder;
  15935. })();
  15936. BABYLON.MeshBuilder = MeshBuilder;
  15937. })(BABYLON || (BABYLON = {}));
  15938. var BABYLON;
  15939. (function (BABYLON) {
  15940. var BaseTexture = (function () {
  15941. function BaseTexture(scene) {
  15942. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  15943. this.hasAlpha = false;
  15944. this.getAlphaFromRGB = false;
  15945. this.level = 1;
  15946. this.isCube = false;
  15947. this.isRenderTarget = false;
  15948. this.animations = new Array();
  15949. this.coordinatesIndex = 0;
  15950. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  15951. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  15952. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  15953. this.anisotropicFilteringLevel = 4;
  15954. this._scene = scene;
  15955. this._scene.textures.push(this);
  15956. }
  15957. BaseTexture.prototype.getScene = function () {
  15958. return this._scene;
  15959. };
  15960. BaseTexture.prototype.getTextureMatrix = function () {
  15961. return null;
  15962. };
  15963. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  15964. return null;
  15965. };
  15966. BaseTexture.prototype.getInternalTexture = function () {
  15967. return this._texture;
  15968. };
  15969. BaseTexture.prototype.isReady = function () {
  15970. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  15971. return true;
  15972. }
  15973. if (this._texture) {
  15974. return this._texture.isReady;
  15975. }
  15976. return false;
  15977. };
  15978. BaseTexture.prototype.getSize = function () {
  15979. if (this._texture._width) {
  15980. return { width: this._texture._width, height: this._texture._height };
  15981. }
  15982. if (this._texture._size) {
  15983. return { width: this._texture._size, height: this._texture._size };
  15984. }
  15985. return { width: 0, height: 0 };
  15986. };
  15987. BaseTexture.prototype.getBaseSize = function () {
  15988. if (!this.isReady())
  15989. return { width: 0, height: 0 };
  15990. if (this._texture._size) {
  15991. return { width: this._texture._size, height: this._texture._size };
  15992. }
  15993. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  15994. };
  15995. BaseTexture.prototype.scale = function (ratio) {
  15996. };
  15997. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  15998. get: function () {
  15999. return false;
  16000. },
  16001. enumerable: true,
  16002. configurable: true
  16003. });
  16004. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  16005. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  16006. for (var index = 0; index < texturesCache.length; index++) {
  16007. var texturesCacheEntry = texturesCache[index];
  16008. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  16009. texturesCache.splice(index, 1);
  16010. return;
  16011. }
  16012. }
  16013. };
  16014. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  16015. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  16016. for (var index = 0; index < texturesCache.length; index++) {
  16017. var texturesCacheEntry = texturesCache[index];
  16018. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  16019. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  16020. texturesCacheEntry.references++;
  16021. return texturesCacheEntry;
  16022. }
  16023. }
  16024. }
  16025. return null;
  16026. };
  16027. BaseTexture.prototype.delayLoad = function () {
  16028. };
  16029. BaseTexture.prototype.clone = function () {
  16030. return null;
  16031. };
  16032. BaseTexture.prototype.releaseInternalTexture = function () {
  16033. if (this._texture) {
  16034. this._scene.getEngine().releaseInternalTexture(this._texture);
  16035. delete this._texture;
  16036. }
  16037. };
  16038. BaseTexture.prototype.dispose = function () {
  16039. // Animations
  16040. this.getScene().stopAnimation(this);
  16041. // Remove from scene
  16042. var index = this._scene.textures.indexOf(this);
  16043. if (index >= 0) {
  16044. this._scene.textures.splice(index, 1);
  16045. }
  16046. if (this._texture === undefined) {
  16047. return;
  16048. }
  16049. // Callback
  16050. if (this.onDispose) {
  16051. this.onDispose();
  16052. }
  16053. };
  16054. return BaseTexture;
  16055. })();
  16056. BABYLON.BaseTexture = BaseTexture;
  16057. })(BABYLON || (BABYLON = {}));
  16058. var BABYLON;
  16059. (function (BABYLON) {
  16060. var Texture = (function (_super) {
  16061. __extends(Texture, _super);
  16062. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  16063. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  16064. if (onLoad === void 0) { onLoad = null; }
  16065. if (onError === void 0) { onError = null; }
  16066. if (buffer === void 0) { buffer = null; }
  16067. if (deleteBuffer === void 0) { deleteBuffer = false; }
  16068. _super.call(this, scene);
  16069. this.uOffset = 0;
  16070. this.vOffset = 0;
  16071. this.uScale = 1.0;
  16072. this.vScale = 1.0;
  16073. this.uAng = 0;
  16074. this.vAng = 0;
  16075. this.wAng = 0;
  16076. this.name = url;
  16077. this.url = url;
  16078. this._noMipmap = noMipmap;
  16079. this._invertY = invertY;
  16080. this._samplingMode = samplingMode;
  16081. this._buffer = buffer;
  16082. this._deleteBuffer = deleteBuffer;
  16083. if (!url) {
  16084. return;
  16085. }
  16086. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  16087. if (!this._texture) {
  16088. if (!scene.useDelayedTextureLoading) {
  16089. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  16090. if (deleteBuffer) {
  16091. delete this._buffer;
  16092. }
  16093. }
  16094. else {
  16095. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  16096. }
  16097. }
  16098. else {
  16099. BABYLON.Tools.SetImmediate(function () {
  16100. if (onLoad) {
  16101. onLoad();
  16102. }
  16103. });
  16104. }
  16105. }
  16106. Texture.prototype.delayLoad = function () {
  16107. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16108. return;
  16109. }
  16110. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  16111. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  16112. if (!this._texture) {
  16113. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  16114. if (this._deleteBuffer) {
  16115. delete this._buffer;
  16116. }
  16117. }
  16118. };
  16119. Texture.prototype.updateSamplingMode = function (samplingMode) {
  16120. if (!this._texture) {
  16121. return;
  16122. }
  16123. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  16124. };
  16125. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  16126. x *= this.uScale;
  16127. y *= this.vScale;
  16128. x -= 0.5 * this.uScale;
  16129. y -= 0.5 * this.vScale;
  16130. z -= 0.5;
  16131. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  16132. t.x += 0.5 * this.uScale + this.uOffset;
  16133. t.y += 0.5 * this.vScale + this.vOffset;
  16134. t.z += 0.5;
  16135. };
  16136. Texture.prototype.getTextureMatrix = function () {
  16137. if (this.uOffset === this._cachedUOffset &&
  16138. this.vOffset === this._cachedVOffset &&
  16139. this.uScale === this._cachedUScale &&
  16140. this.vScale === this._cachedVScale &&
  16141. this.uAng === this._cachedUAng &&
  16142. this.vAng === this._cachedVAng &&
  16143. this.wAng === this._cachedWAng) {
  16144. return this._cachedTextureMatrix;
  16145. }
  16146. this._cachedUOffset = this.uOffset;
  16147. this._cachedVOffset = this.vOffset;
  16148. this._cachedUScale = this.uScale;
  16149. this._cachedVScale = this.vScale;
  16150. this._cachedUAng = this.uAng;
  16151. this._cachedVAng = this.vAng;
  16152. this._cachedWAng = this.wAng;
  16153. if (!this._cachedTextureMatrix) {
  16154. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  16155. this._rowGenerationMatrix = new BABYLON.Matrix();
  16156. this._t0 = BABYLON.Vector3.Zero();
  16157. this._t1 = BABYLON.Vector3.Zero();
  16158. this._t2 = BABYLON.Vector3.Zero();
  16159. }
  16160. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  16161. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  16162. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  16163. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  16164. this._t1.subtractInPlace(this._t0);
  16165. this._t2.subtractInPlace(this._t0);
  16166. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16167. this._cachedTextureMatrix.m[0] = this._t1.x;
  16168. this._cachedTextureMatrix.m[1] = this._t1.y;
  16169. this._cachedTextureMatrix.m[2] = this._t1.z;
  16170. this._cachedTextureMatrix.m[4] = this._t2.x;
  16171. this._cachedTextureMatrix.m[5] = this._t2.y;
  16172. this._cachedTextureMatrix.m[6] = this._t2.z;
  16173. this._cachedTextureMatrix.m[8] = this._t0.x;
  16174. this._cachedTextureMatrix.m[9] = this._t0.y;
  16175. this._cachedTextureMatrix.m[10] = this._t0.z;
  16176. return this._cachedTextureMatrix;
  16177. };
  16178. Texture.prototype.getReflectionTextureMatrix = function () {
  16179. if (this.uOffset === this._cachedUOffset &&
  16180. this.vOffset === this._cachedVOffset &&
  16181. this.uScale === this._cachedUScale &&
  16182. this.vScale === this._cachedVScale &&
  16183. this.coordinatesMode === this._cachedCoordinatesMode) {
  16184. return this._cachedTextureMatrix;
  16185. }
  16186. if (!this._cachedTextureMatrix) {
  16187. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  16188. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  16189. }
  16190. this._cachedCoordinatesMode = this.coordinatesMode;
  16191. switch (this.coordinatesMode) {
  16192. case Texture.PLANAR_MODE:
  16193. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16194. this._cachedTextureMatrix[0] = this.uScale;
  16195. this._cachedTextureMatrix[5] = this.vScale;
  16196. this._cachedTextureMatrix[12] = this.uOffset;
  16197. this._cachedTextureMatrix[13] = this.vOffset;
  16198. break;
  16199. case Texture.PROJECTION_MODE:
  16200. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  16201. this._projectionModeMatrix.m[0] = 0.5;
  16202. this._projectionModeMatrix.m[5] = -0.5;
  16203. this._projectionModeMatrix.m[10] = 0.0;
  16204. this._projectionModeMatrix.m[12] = 0.5;
  16205. this._projectionModeMatrix.m[13] = 0.5;
  16206. this._projectionModeMatrix.m[14] = 1.0;
  16207. this._projectionModeMatrix.m[15] = 1.0;
  16208. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  16209. break;
  16210. default:
  16211. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16212. break;
  16213. }
  16214. return this._cachedTextureMatrix;
  16215. };
  16216. Texture.prototype.clone = function () {
  16217. var newTexture = new Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  16218. // Base texture
  16219. newTexture.hasAlpha = this.hasAlpha;
  16220. newTexture.level = this.level;
  16221. newTexture.wrapU = this.wrapU;
  16222. newTexture.wrapV = this.wrapV;
  16223. newTexture.coordinatesIndex = this.coordinatesIndex;
  16224. newTexture.coordinatesMode = this.coordinatesMode;
  16225. // Texture
  16226. newTexture.uOffset = this.uOffset;
  16227. newTexture.vOffset = this.vOffset;
  16228. newTexture.uScale = this.uScale;
  16229. newTexture.vScale = this.vScale;
  16230. newTexture.uAng = this.uAng;
  16231. newTexture.vAng = this.vAng;
  16232. newTexture.wAng = this.wAng;
  16233. return newTexture;
  16234. };
  16235. // Statics
  16236. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  16237. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  16238. if (onLoad === void 0) { onLoad = null; }
  16239. if (onError === void 0) { onError = null; }
  16240. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  16241. };
  16242. // Constants
  16243. Texture.NEAREST_SAMPLINGMODE = 1;
  16244. Texture.BILINEAR_SAMPLINGMODE = 2;
  16245. Texture.TRILINEAR_SAMPLINGMODE = 3;
  16246. Texture.EXPLICIT_MODE = 0;
  16247. Texture.SPHERICAL_MODE = 1;
  16248. Texture.PLANAR_MODE = 2;
  16249. Texture.CUBIC_MODE = 3;
  16250. Texture.PROJECTION_MODE = 4;
  16251. Texture.SKYBOX_MODE = 5;
  16252. Texture.INVCUBIC_MODE = 6;
  16253. Texture.EQUIRECTANGULAR_MODE = 7;
  16254. Texture.CLAMP_ADDRESSMODE = 0;
  16255. Texture.WRAP_ADDRESSMODE = 1;
  16256. Texture.MIRROR_ADDRESSMODE = 2;
  16257. return Texture;
  16258. })(BABYLON.BaseTexture);
  16259. BABYLON.Texture = Texture;
  16260. })(BABYLON || (BABYLON = {}));
  16261. var BABYLON;
  16262. (function (BABYLON) {
  16263. var CubeTexture = (function (_super) {
  16264. __extends(CubeTexture, _super);
  16265. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  16266. _super.call(this, scene);
  16267. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  16268. this.name = rootUrl;
  16269. this.url = rootUrl;
  16270. this._noMipmap = noMipmap;
  16271. this.hasAlpha = false;
  16272. if (!rootUrl) {
  16273. return;
  16274. }
  16275. this._texture = this._getFromCache(rootUrl, noMipmap);
  16276. if (!extensions) {
  16277. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  16278. }
  16279. this._extensions = extensions;
  16280. if (!this._texture) {
  16281. if (!scene.useDelayedTextureLoading) {
  16282. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  16283. }
  16284. else {
  16285. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  16286. }
  16287. }
  16288. this.isCube = true;
  16289. this._textureMatrix = BABYLON.Matrix.Identity();
  16290. }
  16291. CubeTexture.prototype.clone = function () {
  16292. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  16293. // Base texture
  16294. newTexture.level = this.level;
  16295. newTexture.wrapU = this.wrapU;
  16296. newTexture.wrapV = this.wrapV;
  16297. newTexture.coordinatesIndex = this.coordinatesIndex;
  16298. newTexture.coordinatesMode = this.coordinatesMode;
  16299. return newTexture;
  16300. };
  16301. // Methods
  16302. CubeTexture.prototype.delayLoad = function () {
  16303. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16304. return;
  16305. }
  16306. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  16307. this._texture = this._getFromCache(this.url, this._noMipmap);
  16308. if (!this._texture) {
  16309. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  16310. }
  16311. };
  16312. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  16313. return this._textureMatrix;
  16314. };
  16315. return CubeTexture;
  16316. })(BABYLON.BaseTexture);
  16317. BABYLON.CubeTexture = CubeTexture;
  16318. })(BABYLON || (BABYLON = {}));
  16319. var BABYLON;
  16320. (function (BABYLON) {
  16321. var RenderTargetTexture = (function (_super) {
  16322. __extends(RenderTargetTexture, _super);
  16323. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube) {
  16324. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  16325. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  16326. if (isCube === void 0) { isCube = false; }
  16327. _super.call(this, null, scene, !generateMipMaps);
  16328. this.isCube = isCube;
  16329. this.renderList = new Array();
  16330. this.renderParticles = true;
  16331. this.renderSprites = false;
  16332. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  16333. this._currentRefreshId = -1;
  16334. this._refreshRate = 1;
  16335. this.name = name;
  16336. this.isRenderTarget = true;
  16337. this._size = size;
  16338. this._generateMipMaps = generateMipMaps;
  16339. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  16340. if (isCube) {
  16341. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  16342. this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  16343. this._textureMatrix = BABYLON.Matrix.Identity();
  16344. }
  16345. else {
  16346. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  16347. }
  16348. // Rendering groups
  16349. this._renderingManager = new BABYLON.RenderingManager(scene);
  16350. }
  16351. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  16352. get: function () {
  16353. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  16354. },
  16355. enumerable: true,
  16356. configurable: true
  16357. });
  16358. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  16359. get: function () {
  16360. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  16361. },
  16362. enumerable: true,
  16363. configurable: true
  16364. });
  16365. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  16366. get: function () {
  16367. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  16368. },
  16369. enumerable: true,
  16370. configurable: true
  16371. });
  16372. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  16373. this._currentRefreshId = -1;
  16374. };
  16375. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  16376. get: function () {
  16377. return this._refreshRate;
  16378. },
  16379. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  16380. set: function (value) {
  16381. this._refreshRate = value;
  16382. this.resetRefreshCounter();
  16383. },
  16384. enumerable: true,
  16385. configurable: true
  16386. });
  16387. RenderTargetTexture.prototype._shouldRender = function () {
  16388. if (this._currentRefreshId === -1) {
  16389. this._currentRefreshId = 1;
  16390. return true;
  16391. }
  16392. if (this.refreshRate === this._currentRefreshId) {
  16393. this._currentRefreshId = 1;
  16394. return true;
  16395. }
  16396. this._currentRefreshId++;
  16397. return false;
  16398. };
  16399. RenderTargetTexture.prototype.isReady = function () {
  16400. if (!this.getScene().renderTargetsEnabled) {
  16401. return false;
  16402. }
  16403. return _super.prototype.isReady.call(this);
  16404. };
  16405. RenderTargetTexture.prototype.getRenderSize = function () {
  16406. return this._size;
  16407. };
  16408. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  16409. get: function () {
  16410. return true;
  16411. },
  16412. enumerable: true,
  16413. configurable: true
  16414. });
  16415. RenderTargetTexture.prototype.scale = function (ratio) {
  16416. var newSize = this._size * ratio;
  16417. this.resize(newSize, this._generateMipMaps);
  16418. };
  16419. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  16420. if (this.isCube) {
  16421. return this._textureMatrix;
  16422. }
  16423. return _super.prototype.getReflectionTextureMatrix.call(this);
  16424. };
  16425. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  16426. this.releaseInternalTexture();
  16427. if (this.isCube) {
  16428. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
  16429. }
  16430. else {
  16431. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  16432. }
  16433. };
  16434. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  16435. var scene = this.getScene();
  16436. if (this._waitingRenderList) {
  16437. this.renderList = [];
  16438. for (var index = 0; index < this._waitingRenderList.length; index++) {
  16439. var id = this._waitingRenderList[index];
  16440. this.renderList.push(scene.getMeshByID(id));
  16441. }
  16442. delete this._waitingRenderList;
  16443. }
  16444. if (this.renderList && this.renderList.length === 0) {
  16445. return;
  16446. }
  16447. // Prepare renderingManager
  16448. this._renderingManager.reset();
  16449. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  16450. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  16451. var mesh = currentRenderList[meshIndex];
  16452. if (mesh) {
  16453. if (!mesh.isReady()) {
  16454. // Reset _currentRefreshId
  16455. this.resetRefreshCounter();
  16456. continue;
  16457. }
  16458. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  16459. mesh._activate(scene.getRenderId());
  16460. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  16461. var subMesh = mesh.subMeshes[subIndex];
  16462. scene._activeIndices += subMesh.indexCount;
  16463. this._renderingManager.dispatch(subMesh);
  16464. }
  16465. }
  16466. }
  16467. }
  16468. if (this.isCube) {
  16469. for (var face = 0; face < 6; face++) {
  16470. this.renderToTarget(face, currentRenderList, useCameraPostProcess, dumpForDebug);
  16471. }
  16472. }
  16473. else {
  16474. this.renderToTarget(0, currentRenderList, useCameraPostProcess, dumpForDebug);
  16475. }
  16476. if (this.onAfterUnbind) {
  16477. this.onAfterUnbind();
  16478. }
  16479. scene.resetCachedMaterial();
  16480. };
  16481. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, useCameraPostProcess, dumpForDebug) {
  16482. var scene = this.getScene();
  16483. var engine = scene.getEngine();
  16484. // Bind
  16485. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  16486. if (this.isCube) {
  16487. engine.bindFramebuffer(this._texture, faceIndex);
  16488. }
  16489. else {
  16490. engine.bindFramebuffer(this._texture);
  16491. }
  16492. }
  16493. if (this.onBeforeRender) {
  16494. this.onBeforeRender(faceIndex);
  16495. }
  16496. // Clear
  16497. if (this.onClear) {
  16498. this.onClear(engine);
  16499. }
  16500. else {
  16501. engine.clear(scene.clearColor, true, true);
  16502. }
  16503. if (!this._doNotChangeAspectRatio) {
  16504. scene.updateTransformMatrix(true);
  16505. }
  16506. // Render
  16507. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  16508. if (useCameraPostProcess) {
  16509. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  16510. }
  16511. if (!this._doNotChangeAspectRatio) {
  16512. scene.updateTransformMatrix(true);
  16513. }
  16514. if (this.onAfterRender) {
  16515. this.onAfterRender(faceIndex);
  16516. }
  16517. // Dump ?
  16518. if (dumpForDebug) {
  16519. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  16520. }
  16521. // Unbind
  16522. if (!this.isCube || faceIndex === 5) {
  16523. if (this.isCube) {
  16524. if (faceIndex === 5) {
  16525. engine.generateMipMapsForCubemap(this._texture);
  16526. }
  16527. }
  16528. engine.unBindFramebuffer(this._texture, this.isCube);
  16529. }
  16530. };
  16531. RenderTargetTexture.prototype.clone = function () {
  16532. var textureSize = this.getSize();
  16533. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  16534. // Base texture
  16535. newTexture.hasAlpha = this.hasAlpha;
  16536. newTexture.level = this.level;
  16537. // RenderTarget Texture
  16538. newTexture.coordinatesMode = this.coordinatesMode;
  16539. newTexture.renderList = this.renderList.slice(0);
  16540. return newTexture;
  16541. };
  16542. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  16543. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  16544. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  16545. return RenderTargetTexture;
  16546. })(BABYLON.Texture);
  16547. BABYLON.RenderTargetTexture = RenderTargetTexture;
  16548. })(BABYLON || (BABYLON = {}));
  16549. var BABYLON;
  16550. (function (BABYLON) {
  16551. var ProceduralTexture = (function (_super) {
  16552. __extends(ProceduralTexture, _super);
  16553. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  16554. if (generateMipMaps === void 0) { generateMipMaps = true; }
  16555. _super.call(this, null, scene, !generateMipMaps);
  16556. this.isEnabled = true;
  16557. this._currentRefreshId = -1;
  16558. this._refreshRate = 1;
  16559. this._vertexDeclaration = [2];
  16560. this._vertexStrideSize = 2 * 4;
  16561. this._uniforms = new Array();
  16562. this._samplers = new Array();
  16563. this._textures = new Array();
  16564. this._floats = new Array();
  16565. this._floatsArrays = {};
  16566. this._colors3 = new Array();
  16567. this._colors4 = new Array();
  16568. this._vectors2 = new Array();
  16569. this._vectors3 = new Array();
  16570. this._matrices = new Array();
  16571. this._fallbackTextureUsed = false;
  16572. scene._proceduralTextures.push(this);
  16573. this.name = name;
  16574. this.isRenderTarget = true;
  16575. this._size = size;
  16576. this._generateMipMaps = generateMipMaps;
  16577. this.setFragment(fragment);
  16578. this._fallbackTexture = fallbackTexture;
  16579. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  16580. // VBO
  16581. var vertices = [];
  16582. vertices.push(1, 1);
  16583. vertices.push(-1, 1);
  16584. vertices.push(-1, -1);
  16585. vertices.push(1, -1);
  16586. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  16587. // Indices
  16588. var indices = [];
  16589. indices.push(0);
  16590. indices.push(1);
  16591. indices.push(2);
  16592. indices.push(0);
  16593. indices.push(2);
  16594. indices.push(3);
  16595. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  16596. }
  16597. ProceduralTexture.prototype.reset = function () {
  16598. if (this._effect === undefined) {
  16599. return;
  16600. }
  16601. var engine = this.getScene().getEngine();
  16602. engine._releaseEffect(this._effect);
  16603. };
  16604. ProceduralTexture.prototype.isReady = function () {
  16605. var _this = this;
  16606. var engine = this.getScene().getEngine();
  16607. var shaders;
  16608. if (!this._fragment) {
  16609. return false;
  16610. }
  16611. if (this._fallbackTextureUsed) {
  16612. return true;
  16613. }
  16614. if (this._fragment.fragmentElement !== undefined) {
  16615. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  16616. }
  16617. else {
  16618. shaders = { vertex: "procedural", fragment: this._fragment };
  16619. }
  16620. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  16621. _this.releaseInternalTexture();
  16622. if (_this._fallbackTexture) {
  16623. _this._texture = _this._fallbackTexture._texture;
  16624. _this._texture.references++;
  16625. }
  16626. _this._fallbackTextureUsed = true;
  16627. });
  16628. return this._effect.isReady();
  16629. };
  16630. ProceduralTexture.prototype.resetRefreshCounter = function () {
  16631. this._currentRefreshId = -1;
  16632. };
  16633. ProceduralTexture.prototype.setFragment = function (fragment) {
  16634. this._fragment = fragment;
  16635. };
  16636. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  16637. get: function () {
  16638. return this._refreshRate;
  16639. },
  16640. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  16641. set: function (value) {
  16642. this._refreshRate = value;
  16643. this.resetRefreshCounter();
  16644. },
  16645. enumerable: true,
  16646. configurable: true
  16647. });
  16648. ProceduralTexture.prototype._shouldRender = function () {
  16649. if (!this.isEnabled || !this.isReady() || !this._texture) {
  16650. return false;
  16651. }
  16652. if (this._fallbackTextureUsed) {
  16653. return false;
  16654. }
  16655. if (this._currentRefreshId === -1) {
  16656. this._currentRefreshId = 1;
  16657. return true;
  16658. }
  16659. if (this.refreshRate === this._currentRefreshId) {
  16660. this._currentRefreshId = 1;
  16661. return true;
  16662. }
  16663. this._currentRefreshId++;
  16664. return false;
  16665. };
  16666. ProceduralTexture.prototype.getRenderSize = function () {
  16667. return this._size;
  16668. };
  16669. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  16670. if (this._fallbackTextureUsed) {
  16671. return;
  16672. }
  16673. this.releaseInternalTexture();
  16674. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  16675. };
  16676. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  16677. if (this._uniforms.indexOf(uniformName) === -1) {
  16678. this._uniforms.push(uniformName);
  16679. }
  16680. };
  16681. ProceduralTexture.prototype.setTexture = function (name, texture) {
  16682. if (this._samplers.indexOf(name) === -1) {
  16683. this._samplers.push(name);
  16684. }
  16685. this._textures[name] = texture;
  16686. return this;
  16687. };
  16688. ProceduralTexture.prototype.setFloat = function (name, value) {
  16689. this._checkUniform(name);
  16690. this._floats[name] = value;
  16691. return this;
  16692. };
  16693. ProceduralTexture.prototype.setFloats = function (name, value) {
  16694. this._checkUniform(name);
  16695. this._floatsArrays[name] = value;
  16696. return this;
  16697. };
  16698. ProceduralTexture.prototype.setColor3 = function (name, value) {
  16699. this._checkUniform(name);
  16700. this._colors3[name] = value;
  16701. return this;
  16702. };
  16703. ProceduralTexture.prototype.setColor4 = function (name, value) {
  16704. this._checkUniform(name);
  16705. this._colors4[name] = value;
  16706. return this;
  16707. };
  16708. ProceduralTexture.prototype.setVector2 = function (name, value) {
  16709. this._checkUniform(name);
  16710. this._vectors2[name] = value;
  16711. return this;
  16712. };
  16713. ProceduralTexture.prototype.setVector3 = function (name, value) {
  16714. this._checkUniform(name);
  16715. this._vectors3[name] = value;
  16716. return this;
  16717. };
  16718. ProceduralTexture.prototype.setMatrix = function (name, value) {
  16719. this._checkUniform(name);
  16720. this._matrices[name] = value;
  16721. return this;
  16722. };
  16723. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  16724. var scene = this.getScene();
  16725. var engine = scene.getEngine();
  16726. engine.bindFramebuffer(this._texture);
  16727. // Clear
  16728. engine.clear(scene.clearColor, true, true);
  16729. // Render
  16730. engine.enableEffect(this._effect);
  16731. engine.setState(false);
  16732. // Texture
  16733. for (var name in this._textures) {
  16734. this._effect.setTexture(name, this._textures[name]);
  16735. }
  16736. // Float
  16737. for (name in this._floats) {
  16738. this._effect.setFloat(name, this._floats[name]);
  16739. }
  16740. // Floats
  16741. for (name in this._floatsArrays) {
  16742. this._effect.setArray(name, this._floatsArrays[name]);
  16743. }
  16744. // Color3
  16745. for (name in this._colors3) {
  16746. this._effect.setColor3(name, this._colors3[name]);
  16747. }
  16748. // Color4
  16749. for (name in this._colors4) {
  16750. var color = this._colors4[name];
  16751. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  16752. }
  16753. // Vector2
  16754. for (name in this._vectors2) {
  16755. this._effect.setVector2(name, this._vectors2[name]);
  16756. }
  16757. // Vector3
  16758. for (name in this._vectors3) {
  16759. this._effect.setVector3(name, this._vectors3[name]);
  16760. }
  16761. // Matrix
  16762. for (name in this._matrices) {
  16763. this._effect.setMatrix(name, this._matrices[name]);
  16764. }
  16765. // VBOs
  16766. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  16767. // Draw order
  16768. engine.draw(true, 0, 6);
  16769. // Unbind
  16770. engine.unBindFramebuffer(this._texture);
  16771. };
  16772. ProceduralTexture.prototype.clone = function () {
  16773. var textureSize = this.getSize();
  16774. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  16775. // Base texture
  16776. newTexture.hasAlpha = this.hasAlpha;
  16777. newTexture.level = this.level;
  16778. // RenderTarget Texture
  16779. newTexture.coordinatesMode = this.coordinatesMode;
  16780. return newTexture;
  16781. };
  16782. ProceduralTexture.prototype.dispose = function () {
  16783. var index = this.getScene()._proceduralTextures.indexOf(this);
  16784. if (index >= 0) {
  16785. this.getScene()._proceduralTextures.splice(index, 1);
  16786. }
  16787. _super.prototype.dispose.call(this);
  16788. };
  16789. return ProceduralTexture;
  16790. })(BABYLON.Texture);
  16791. BABYLON.ProceduralTexture = ProceduralTexture;
  16792. })(BABYLON || (BABYLON = {}));
  16793. var BABYLON;
  16794. (function (BABYLON) {
  16795. var MirrorTexture = (function (_super) {
  16796. __extends(MirrorTexture, _super);
  16797. function MirrorTexture(name, size, scene, generateMipMaps) {
  16798. var _this = this;
  16799. _super.call(this, name, size, scene, generateMipMaps, true);
  16800. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  16801. this._transformMatrix = BABYLON.Matrix.Zero();
  16802. this._mirrorMatrix = BABYLON.Matrix.Zero();
  16803. this.onBeforeRender = function () {
  16804. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  16805. _this._savedViewMatrix = scene.getViewMatrix();
  16806. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  16807. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  16808. scene.clipPlane = _this.mirrorPlane;
  16809. scene.getEngine().cullBackFaces = false;
  16810. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  16811. };
  16812. this.onAfterRender = function () {
  16813. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  16814. scene.getEngine().cullBackFaces = true;
  16815. scene._mirroredCameraPosition = null;
  16816. delete scene.clipPlane;
  16817. };
  16818. }
  16819. MirrorTexture.prototype.clone = function () {
  16820. var textureSize = this.getSize();
  16821. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  16822. // Base texture
  16823. newTexture.hasAlpha = this.hasAlpha;
  16824. newTexture.level = this.level;
  16825. // Mirror Texture
  16826. newTexture.mirrorPlane = this.mirrorPlane.clone();
  16827. newTexture.renderList = this.renderList.slice(0);
  16828. return newTexture;
  16829. };
  16830. return MirrorTexture;
  16831. })(BABYLON.RenderTargetTexture);
  16832. BABYLON.MirrorTexture = MirrorTexture;
  16833. })(BABYLON || (BABYLON = {}));
  16834. var BABYLON;
  16835. (function (BABYLON) {
  16836. var DynamicTexture = (function (_super) {
  16837. __extends(DynamicTexture, _super);
  16838. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  16839. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16840. _super.call(this, null, scene, !generateMipMaps);
  16841. this.name = name;
  16842. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  16843. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  16844. this._generateMipMaps = generateMipMaps;
  16845. if (options.getContext) {
  16846. this._canvas = options;
  16847. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  16848. }
  16849. else {
  16850. this._canvas = document.createElement("canvas");
  16851. if (options.width) {
  16852. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  16853. }
  16854. else {
  16855. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  16856. }
  16857. }
  16858. var textureSize = this.getSize();
  16859. this._canvas.width = textureSize.width;
  16860. this._canvas.height = textureSize.height;
  16861. this._context = this._canvas.getContext("2d");
  16862. }
  16863. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  16864. get: function () {
  16865. return true;
  16866. },
  16867. enumerable: true,
  16868. configurable: true
  16869. });
  16870. DynamicTexture.prototype.scale = function (ratio) {
  16871. var textureSize = this.getSize();
  16872. textureSize.width *= ratio;
  16873. textureSize.height *= ratio;
  16874. this._canvas.width = textureSize.width;
  16875. this._canvas.height = textureSize.height;
  16876. this.releaseInternalTexture();
  16877. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  16878. };
  16879. DynamicTexture.prototype.getContext = function () {
  16880. return this._context;
  16881. };
  16882. DynamicTexture.prototype.clear = function () {
  16883. var size = this.getSize();
  16884. this._context.fillRect(0, 0, size.width, size.height);
  16885. };
  16886. DynamicTexture.prototype.update = function (invertY) {
  16887. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  16888. };
  16889. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  16890. if (update === void 0) { update = true; }
  16891. var size = this.getSize();
  16892. if (clearColor) {
  16893. this._context.fillStyle = clearColor;
  16894. this._context.fillRect(0, 0, size.width, size.height);
  16895. }
  16896. this._context.font = font;
  16897. if (x === null) {
  16898. var textSize = this._context.measureText(text);
  16899. x = (size.width - textSize.width) / 2;
  16900. }
  16901. this._context.fillStyle = color;
  16902. this._context.fillText(text, x, y);
  16903. if (update) {
  16904. this.update(invertY);
  16905. }
  16906. };
  16907. DynamicTexture.prototype.clone = function () {
  16908. var textureSize = this.getSize();
  16909. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  16910. // Base texture
  16911. newTexture.hasAlpha = this.hasAlpha;
  16912. newTexture.level = this.level;
  16913. // Dynamic Texture
  16914. newTexture.wrapU = this.wrapU;
  16915. newTexture.wrapV = this.wrapV;
  16916. return newTexture;
  16917. };
  16918. return DynamicTexture;
  16919. })(BABYLON.Texture);
  16920. BABYLON.DynamicTexture = DynamicTexture;
  16921. })(BABYLON || (BABYLON = {}));
  16922. var BABYLON;
  16923. (function (BABYLON) {
  16924. var VideoTexture = (function (_super) {
  16925. __extends(VideoTexture, _super);
  16926. function VideoTexture(name, urls, scene, generateMipMaps, invertY, samplingMode) {
  16927. var _this = this;
  16928. if (generateMipMaps === void 0) { generateMipMaps = false; }
  16929. if (invertY === void 0) { invertY = false; }
  16930. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16931. _super.call(this, null, scene, !generateMipMaps, invertY);
  16932. this._autoLaunch = true;
  16933. this.name = name;
  16934. this.video = document.createElement("video");
  16935. this.video.autoplay = false;
  16936. this.video.loop = true;
  16937. this.video.addEventListener("canplaythrough", function () {
  16938. if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
  16939. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  16940. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  16941. }
  16942. else {
  16943. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  16944. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  16945. generateMipMaps = false;
  16946. }
  16947. _this._texture = scene.getEngine().createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, generateMipMaps, samplingMode, false);
  16948. _this._texture.isReady = true;
  16949. });
  16950. urls.forEach(function (url) {
  16951. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  16952. var source = document.createElement("source");
  16953. source.src = url;
  16954. _this.video.appendChild(source);
  16955. });
  16956. this._lastUpdate = BABYLON.Tools.Now;
  16957. }
  16958. VideoTexture.prototype.update = function () {
  16959. if (this._autoLaunch) {
  16960. this._autoLaunch = false;
  16961. this.video.play();
  16962. }
  16963. var now = BABYLON.Tools.Now;
  16964. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  16965. return false;
  16966. }
  16967. this._lastUpdate = now;
  16968. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  16969. return true;
  16970. };
  16971. return VideoTexture;
  16972. })(BABYLON.Texture);
  16973. BABYLON.VideoTexture = VideoTexture;
  16974. })(BABYLON || (BABYLON = {}));
  16975. var BABYLON;
  16976. (function (BABYLON) {
  16977. var CustomProceduralTexture = (function (_super) {
  16978. __extends(CustomProceduralTexture, _super);
  16979. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  16980. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  16981. this._animate = true;
  16982. this._time = 0;
  16983. this._texturePath = texturePath;
  16984. //Try to load json
  16985. this.loadJson(texturePath);
  16986. this.refreshRate = 1;
  16987. }
  16988. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  16989. var _this = this;
  16990. var that = this;
  16991. function noConfigFile() {
  16992. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  16993. try {
  16994. that.setFragment(that._texturePath);
  16995. }
  16996. catch (ex) {
  16997. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  16998. }
  16999. }
  17000. var configFileUrl = jsonUrl + "/config.json";
  17001. var xhr = new XMLHttpRequest();
  17002. xhr.open("GET", configFileUrl, true);
  17003. xhr.addEventListener("load", function () {
  17004. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  17005. try {
  17006. _this._config = JSON.parse(xhr.response);
  17007. _this.updateShaderUniforms();
  17008. _this.updateTextures();
  17009. _this.setFragment(_this._texturePath + "/custom");
  17010. _this._animate = _this._config.animate;
  17011. _this.refreshRate = _this._config.refreshrate;
  17012. }
  17013. catch (ex) {
  17014. noConfigFile();
  17015. }
  17016. }
  17017. else {
  17018. noConfigFile();
  17019. }
  17020. }, false);
  17021. xhr.addEventListener("error", function () {
  17022. noConfigFile();
  17023. }, false);
  17024. try {
  17025. xhr.send();
  17026. }
  17027. catch (ex) {
  17028. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  17029. }
  17030. };
  17031. CustomProceduralTexture.prototype.isReady = function () {
  17032. if (!_super.prototype.isReady.call(this)) {
  17033. return false;
  17034. }
  17035. for (var name in this._textures) {
  17036. var texture = this._textures[name];
  17037. if (!texture.isReady()) {
  17038. return false;
  17039. }
  17040. }
  17041. return true;
  17042. };
  17043. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  17044. if (this._animate) {
  17045. this._time += this.getScene().getAnimationRatio() * 0.03;
  17046. this.updateShaderUniforms();
  17047. }
  17048. _super.prototype.render.call(this, useCameraPostProcess);
  17049. };
  17050. CustomProceduralTexture.prototype.updateTextures = function () {
  17051. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  17052. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  17053. }
  17054. };
  17055. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  17056. if (this._config) {
  17057. for (var j = 0; j < this._config.uniforms.length; j++) {
  17058. var uniform = this._config.uniforms[j];
  17059. switch (uniform.type) {
  17060. case "float":
  17061. this.setFloat(uniform.name, uniform.value);
  17062. break;
  17063. case "color3":
  17064. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  17065. break;
  17066. case "color4":
  17067. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  17068. break;
  17069. case "vector2":
  17070. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  17071. break;
  17072. case "vector3":
  17073. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  17074. break;
  17075. }
  17076. }
  17077. }
  17078. this.setFloat("time", this._time);
  17079. };
  17080. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  17081. get: function () {
  17082. return this._animate;
  17083. },
  17084. set: function (value) {
  17085. this._animate = value;
  17086. },
  17087. enumerable: true,
  17088. configurable: true
  17089. });
  17090. return CustomProceduralTexture;
  17091. })(BABYLON.ProceduralTexture);
  17092. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  17093. })(BABYLON || (BABYLON = {}));
  17094. var BABYLON;
  17095. (function (BABYLON) {
  17096. var WoodProceduralTexture = (function (_super) {
  17097. __extends(WoodProceduralTexture, _super);
  17098. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17099. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  17100. this._ampScale = 100.0;
  17101. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  17102. this.updateShaderUniforms();
  17103. this.refreshRate = 0;
  17104. }
  17105. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  17106. this.setFloat("ampScale", this._ampScale);
  17107. this.setColor3("woodColor", this._woodColor);
  17108. };
  17109. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  17110. get: function () {
  17111. return this._ampScale;
  17112. },
  17113. set: function (value) {
  17114. this._ampScale = value;
  17115. this.updateShaderUniforms();
  17116. },
  17117. enumerable: true,
  17118. configurable: true
  17119. });
  17120. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  17121. get: function () {
  17122. return this._woodColor;
  17123. },
  17124. set: function (value) {
  17125. this._woodColor = value;
  17126. this.updateShaderUniforms();
  17127. },
  17128. enumerable: true,
  17129. configurable: true
  17130. });
  17131. return WoodProceduralTexture;
  17132. })(BABYLON.ProceduralTexture);
  17133. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  17134. var FireProceduralTexture = (function (_super) {
  17135. __extends(FireProceduralTexture, _super);
  17136. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17137. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  17138. this._time = 0.0;
  17139. this._speed = new BABYLON.Vector2(0.5, 0.3);
  17140. this._autoGenerateTime = true;
  17141. this._alphaThreshold = 0.5;
  17142. this._fireColors = FireProceduralTexture.RedFireColors;
  17143. this.updateShaderUniforms();
  17144. this.refreshRate = 1;
  17145. }
  17146. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  17147. this.setFloat("time", this._time);
  17148. this.setVector2("speed", this._speed);
  17149. this.setColor3("c1", this._fireColors[0]);
  17150. this.setColor3("c2", this._fireColors[1]);
  17151. this.setColor3("c3", this._fireColors[2]);
  17152. this.setColor3("c4", this._fireColors[3]);
  17153. this.setColor3("c5", this._fireColors[4]);
  17154. this.setColor3("c6", this._fireColors[5]);
  17155. this.setFloat("alphaThreshold", this._alphaThreshold);
  17156. };
  17157. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  17158. if (this._autoGenerateTime) {
  17159. this._time += this.getScene().getAnimationRatio() * 0.03;
  17160. this.updateShaderUniforms();
  17161. }
  17162. _super.prototype.render.call(this, useCameraPostProcess);
  17163. };
  17164. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  17165. get: function () {
  17166. return [
  17167. new BABYLON.Color3(0.5, 0.0, 1.0),
  17168. new BABYLON.Color3(0.9, 0.0, 1.0),
  17169. new BABYLON.Color3(0.2, 0.0, 1.0),
  17170. new BABYLON.Color3(1.0, 0.9, 1.0),
  17171. new BABYLON.Color3(0.1, 0.1, 1.0),
  17172. new BABYLON.Color3(0.9, 0.9, 1.0)
  17173. ];
  17174. },
  17175. enumerable: true,
  17176. configurable: true
  17177. });
  17178. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  17179. get: function () {
  17180. return [
  17181. new BABYLON.Color3(0.5, 1.0, 0.0),
  17182. new BABYLON.Color3(0.5, 1.0, 0.0),
  17183. new BABYLON.Color3(0.3, 0.4, 0.0),
  17184. new BABYLON.Color3(0.5, 1.0, 0.0),
  17185. new BABYLON.Color3(0.2, 0.0, 0.0),
  17186. new BABYLON.Color3(0.5, 1.0, 0.0)
  17187. ];
  17188. },
  17189. enumerable: true,
  17190. configurable: true
  17191. });
  17192. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  17193. get: function () {
  17194. return [
  17195. new BABYLON.Color3(0.5, 0.0, 0.1),
  17196. new BABYLON.Color3(0.9, 0.0, 0.0),
  17197. new BABYLON.Color3(0.2, 0.0, 0.0),
  17198. new BABYLON.Color3(1.0, 0.9, 0.0),
  17199. new BABYLON.Color3(0.1, 0.1, 0.1),
  17200. new BABYLON.Color3(0.9, 0.9, 0.9)
  17201. ];
  17202. },
  17203. enumerable: true,
  17204. configurable: true
  17205. });
  17206. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  17207. get: function () {
  17208. return [
  17209. new BABYLON.Color3(0.1, 0.0, 0.5),
  17210. new BABYLON.Color3(0.0, 0.0, 0.5),
  17211. new BABYLON.Color3(0.1, 0.0, 0.2),
  17212. new BABYLON.Color3(0.0, 0.0, 1.0),
  17213. new BABYLON.Color3(0.1, 0.2, 0.3),
  17214. new BABYLON.Color3(0.0, 0.2, 0.9)
  17215. ];
  17216. },
  17217. enumerable: true,
  17218. configurable: true
  17219. });
  17220. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  17221. get: function () {
  17222. return this._fireColors;
  17223. },
  17224. set: function (value) {
  17225. this._fireColors = value;
  17226. this.updateShaderUniforms();
  17227. },
  17228. enumerable: true,
  17229. configurable: true
  17230. });
  17231. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  17232. get: function () {
  17233. return this._time;
  17234. },
  17235. set: function (value) {
  17236. this._time = value;
  17237. this.updateShaderUniforms();
  17238. },
  17239. enumerable: true,
  17240. configurable: true
  17241. });
  17242. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  17243. get: function () {
  17244. return this._speed;
  17245. },
  17246. set: function (value) {
  17247. this._speed = value;
  17248. this.updateShaderUniforms();
  17249. },
  17250. enumerable: true,
  17251. configurable: true
  17252. });
  17253. Object.defineProperty(FireProceduralTexture.prototype, "alphaThreshold", {
  17254. get: function () {
  17255. return this._alphaThreshold;
  17256. },
  17257. set: function (value) {
  17258. this._alphaThreshold = value;
  17259. this.updateShaderUniforms();
  17260. },
  17261. enumerable: true,
  17262. configurable: true
  17263. });
  17264. return FireProceduralTexture;
  17265. })(BABYLON.ProceduralTexture);
  17266. BABYLON.FireProceduralTexture = FireProceduralTexture;
  17267. var CloudProceduralTexture = (function (_super) {
  17268. __extends(CloudProceduralTexture, _super);
  17269. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17270. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  17271. this._skyColor = new BABYLON.Color4(0.15, 0.68, 1.0, 1.0);
  17272. this._cloudColor = new BABYLON.Color4(1, 1, 1, 1.0);
  17273. this.updateShaderUniforms();
  17274. this.refreshRate = 0;
  17275. }
  17276. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  17277. this.setColor4("skyColor", this._skyColor);
  17278. this.setColor4("cloudColor", this._cloudColor);
  17279. };
  17280. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  17281. get: function () {
  17282. return this._skyColor;
  17283. },
  17284. set: function (value) {
  17285. this._skyColor = value;
  17286. this.updateShaderUniforms();
  17287. },
  17288. enumerable: true,
  17289. configurable: true
  17290. });
  17291. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  17292. get: function () {
  17293. return this._cloudColor;
  17294. },
  17295. set: function (value) {
  17296. this._cloudColor = value;
  17297. this.updateShaderUniforms();
  17298. },
  17299. enumerable: true,
  17300. configurable: true
  17301. });
  17302. return CloudProceduralTexture;
  17303. })(BABYLON.ProceduralTexture);
  17304. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  17305. var GrassProceduralTexture = (function (_super) {
  17306. __extends(GrassProceduralTexture, _super);
  17307. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17308. _super.call(this, name, size, "grass", scene, fallbackTexture, generateMipMaps);
  17309. this._herb1 = new BABYLON.Color3(0.29, 0.38, 0.02);
  17310. this._herb2 = new BABYLON.Color3(0.36, 0.49, 0.09);
  17311. this._herb3 = new BABYLON.Color3(0.51, 0.6, 0.28);
  17312. this._groundColor = new BABYLON.Color3(1, 1, 1);
  17313. this._grassColors = [
  17314. new BABYLON.Color3(0.29, 0.38, 0.02),
  17315. new BABYLON.Color3(0.36, 0.49, 0.09),
  17316. new BABYLON.Color3(0.51, 0.6, 0.28)
  17317. ];
  17318. this.updateShaderUniforms();
  17319. this.refreshRate = 0;
  17320. }
  17321. GrassProceduralTexture.prototype.updateShaderUniforms = function () {
  17322. this.setColor3("herb1Color", this._grassColors[0]);
  17323. this.setColor3("herb2Color", this._grassColors[1]);
  17324. this.setColor3("herb3Color", this._grassColors[2]);
  17325. this.setColor3("groundColor", this._groundColor);
  17326. };
  17327. Object.defineProperty(GrassProceduralTexture.prototype, "grassColors", {
  17328. get: function () {
  17329. return this._grassColors;
  17330. },
  17331. set: function (value) {
  17332. this._grassColors = value;
  17333. this.updateShaderUniforms();
  17334. },
  17335. enumerable: true,
  17336. configurable: true
  17337. });
  17338. Object.defineProperty(GrassProceduralTexture.prototype, "groundColor", {
  17339. get: function () {
  17340. return this._groundColor;
  17341. },
  17342. set: function (value) {
  17343. this.groundColor = value;
  17344. this.updateShaderUniforms();
  17345. },
  17346. enumerable: true,
  17347. configurable: true
  17348. });
  17349. return GrassProceduralTexture;
  17350. })(BABYLON.ProceduralTexture);
  17351. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  17352. var RoadProceduralTexture = (function (_super) {
  17353. __extends(RoadProceduralTexture, _super);
  17354. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17355. _super.call(this, name, size, "road", scene, fallbackTexture, generateMipMaps);
  17356. this._roadColor = new BABYLON.Color3(0.53, 0.53, 0.53);
  17357. this.updateShaderUniforms();
  17358. this.refreshRate = 0;
  17359. }
  17360. RoadProceduralTexture.prototype.updateShaderUniforms = function () {
  17361. this.setColor3("roadColor", this._roadColor);
  17362. };
  17363. Object.defineProperty(RoadProceduralTexture.prototype, "roadColor", {
  17364. get: function () {
  17365. return this._roadColor;
  17366. },
  17367. set: function (value) {
  17368. this._roadColor = value;
  17369. this.updateShaderUniforms();
  17370. },
  17371. enumerable: true,
  17372. configurable: true
  17373. });
  17374. return RoadProceduralTexture;
  17375. })(BABYLON.ProceduralTexture);
  17376. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  17377. var BrickProceduralTexture = (function (_super) {
  17378. __extends(BrickProceduralTexture, _super);
  17379. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17380. _super.call(this, name, size, "brick", scene, fallbackTexture, generateMipMaps);
  17381. this._numberOfBricksHeight = 15;
  17382. this._numberOfBricksWidth = 5;
  17383. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  17384. this._brickColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  17385. this.updateShaderUniforms();
  17386. this.refreshRate = 0;
  17387. }
  17388. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  17389. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  17390. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  17391. this.setColor3("brickColor", this._brickColor);
  17392. this.setColor3("jointColor", this._jointColor);
  17393. };
  17394. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  17395. get: function () {
  17396. return this._numberOfBricksHeight;
  17397. },
  17398. set: function (value) {
  17399. this._numberOfBricksHeight = value;
  17400. this.updateShaderUniforms();
  17401. },
  17402. enumerable: true,
  17403. configurable: true
  17404. });
  17405. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  17406. get: function () {
  17407. return this._numberOfBricksWidth;
  17408. },
  17409. set: function (value) {
  17410. this._numberOfBricksWidth = value;
  17411. this.updateShaderUniforms();
  17412. },
  17413. enumerable: true,
  17414. configurable: true
  17415. });
  17416. Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", {
  17417. get: function () {
  17418. return this._jointColor;
  17419. },
  17420. set: function (value) {
  17421. this._jointColor = value;
  17422. this.updateShaderUniforms();
  17423. },
  17424. enumerable: true,
  17425. configurable: true
  17426. });
  17427. Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", {
  17428. get: function () {
  17429. return this._brickColor;
  17430. },
  17431. set: function (value) {
  17432. this._brickColor = value;
  17433. this.updateShaderUniforms();
  17434. },
  17435. enumerable: true,
  17436. configurable: true
  17437. });
  17438. return BrickProceduralTexture;
  17439. })(BABYLON.ProceduralTexture);
  17440. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  17441. var MarbleProceduralTexture = (function (_super) {
  17442. __extends(MarbleProceduralTexture, _super);
  17443. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17444. _super.call(this, name, size, "marble", scene, fallbackTexture, generateMipMaps);
  17445. this._numberOfTilesHeight = 3;
  17446. this._numberOfTilesWidth = 3;
  17447. this._amplitude = 9.0;
  17448. this._marbleColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  17449. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  17450. this.updateShaderUniforms();
  17451. this.refreshRate = 0;
  17452. }
  17453. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  17454. this.setFloat("numberOfTilesHeight", this._numberOfTilesHeight);
  17455. this.setFloat("numberOfTilesWidth", this._numberOfTilesWidth);
  17456. this.setFloat("amplitude", this._amplitude);
  17457. this.setColor3("marbleColor", this._marbleColor);
  17458. this.setColor3("jointColor", this._jointColor);
  17459. };
  17460. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesHeight", {
  17461. get: function () {
  17462. return this._numberOfTilesHeight;
  17463. },
  17464. set: function (value) {
  17465. this._numberOfTilesHeight = value;
  17466. this.updateShaderUniforms();
  17467. },
  17468. enumerable: true,
  17469. configurable: true
  17470. });
  17471. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesWidth", {
  17472. get: function () {
  17473. return this._numberOfTilesWidth;
  17474. },
  17475. set: function (value) {
  17476. this._numberOfTilesWidth = value;
  17477. this.updateShaderUniforms();
  17478. },
  17479. enumerable: true,
  17480. configurable: true
  17481. });
  17482. Object.defineProperty(MarbleProceduralTexture.prototype, "jointColor", {
  17483. get: function () {
  17484. return this._jointColor;
  17485. },
  17486. set: function (value) {
  17487. this._jointColor = value;
  17488. this.updateShaderUniforms();
  17489. },
  17490. enumerable: true,
  17491. configurable: true
  17492. });
  17493. Object.defineProperty(MarbleProceduralTexture.prototype, "marbleColor", {
  17494. get: function () {
  17495. return this._marbleColor;
  17496. },
  17497. set: function (value) {
  17498. this._marbleColor = value;
  17499. this.updateShaderUniforms();
  17500. },
  17501. enumerable: true,
  17502. configurable: true
  17503. });
  17504. return MarbleProceduralTexture;
  17505. })(BABYLON.ProceduralTexture);
  17506. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  17507. })(BABYLON || (BABYLON = {}));
  17508. var BABYLON;
  17509. (function (BABYLON) {
  17510. var EffectFallbacks = (function () {
  17511. function EffectFallbacks() {
  17512. this._defines = {};
  17513. this._currentRank = 32;
  17514. this._maxRank = -1;
  17515. }
  17516. EffectFallbacks.prototype.addFallback = function (rank, define) {
  17517. if (!this._defines[rank]) {
  17518. if (rank < this._currentRank) {
  17519. this._currentRank = rank;
  17520. }
  17521. if (rank > this._maxRank) {
  17522. this._maxRank = rank;
  17523. }
  17524. this._defines[rank] = new Array();
  17525. }
  17526. this._defines[rank].push(define);
  17527. };
  17528. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  17529. get: function () {
  17530. return this._currentRank <= this._maxRank;
  17531. },
  17532. enumerable: true,
  17533. configurable: true
  17534. });
  17535. EffectFallbacks.prototype.reduce = function (currentDefines) {
  17536. var currentFallbacks = this._defines[this._currentRank];
  17537. for (var index = 0; index < currentFallbacks.length; index++) {
  17538. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  17539. }
  17540. this._currentRank++;
  17541. return currentDefines;
  17542. };
  17543. return EffectFallbacks;
  17544. })();
  17545. BABYLON.EffectFallbacks = EffectFallbacks;
  17546. var Effect = (function () {
  17547. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  17548. var _this = this;
  17549. this._isReady = false;
  17550. this._compilationError = "";
  17551. this._valueCache = [];
  17552. this._engine = engine;
  17553. this.name = baseName;
  17554. this.defines = defines;
  17555. this._uniformsNames = uniformsNames.concat(samplers);
  17556. this._samplers = samplers;
  17557. this._attributesNames = attributesNames;
  17558. this.onError = onError;
  17559. this.onCompiled = onCompiled;
  17560. var vertexSource;
  17561. var fragmentSource;
  17562. if (baseName.vertexElement) {
  17563. vertexSource = document.getElementById(baseName.vertexElement);
  17564. if (!vertexSource) {
  17565. vertexSource = baseName.vertexElement;
  17566. }
  17567. }
  17568. else {
  17569. vertexSource = baseName.vertex || baseName;
  17570. }
  17571. if (baseName.fragmentElement) {
  17572. fragmentSource = document.getElementById(baseName.fragmentElement);
  17573. if (!fragmentSource) {
  17574. fragmentSource = baseName.fragmentElement;
  17575. }
  17576. }
  17577. else {
  17578. fragmentSource = baseName.fragment || baseName;
  17579. }
  17580. this._loadVertexShader(vertexSource, function (vertexCode) {
  17581. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  17582. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  17583. });
  17584. });
  17585. }
  17586. // Properties
  17587. Effect.prototype.isReady = function () {
  17588. return this._isReady;
  17589. };
  17590. Effect.prototype.getProgram = function () {
  17591. return this._program;
  17592. };
  17593. Effect.prototype.getAttributesNames = function () {
  17594. return this._attributesNames;
  17595. };
  17596. Effect.prototype.getAttributeLocation = function (index) {
  17597. return this._attributes[index];
  17598. };
  17599. Effect.prototype.getAttributeLocationByName = function (name) {
  17600. var index = this._attributesNames.indexOf(name);
  17601. return this._attributes[index];
  17602. };
  17603. Effect.prototype.getAttributesCount = function () {
  17604. return this._attributes.length;
  17605. };
  17606. Effect.prototype.getUniformIndex = function (uniformName) {
  17607. return this._uniformsNames.indexOf(uniformName);
  17608. };
  17609. Effect.prototype.getUniform = function (uniformName) {
  17610. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  17611. };
  17612. Effect.prototype.getSamplers = function () {
  17613. return this._samplers;
  17614. };
  17615. Effect.prototype.getCompilationError = function () {
  17616. return this._compilationError;
  17617. };
  17618. // Methods
  17619. Effect.prototype._loadVertexShader = function (vertex, callback) {
  17620. // DOM element ?
  17621. if (vertex instanceof HTMLElement) {
  17622. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  17623. callback(vertexCode);
  17624. return;
  17625. }
  17626. // Is in local store ?
  17627. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  17628. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  17629. return;
  17630. }
  17631. var vertexShaderUrl;
  17632. if (vertex[0] === "." || vertex[0] === "/") {
  17633. vertexShaderUrl = vertex;
  17634. }
  17635. else {
  17636. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  17637. }
  17638. // Vertex shader
  17639. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  17640. };
  17641. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  17642. // DOM element ?
  17643. if (fragment instanceof HTMLElement) {
  17644. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  17645. callback(fragmentCode);
  17646. return;
  17647. }
  17648. // Is in local store ?
  17649. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  17650. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  17651. return;
  17652. }
  17653. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  17654. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  17655. return;
  17656. }
  17657. var fragmentShaderUrl;
  17658. if (fragment[0] === "." || fragment[0] === "/") {
  17659. fragmentShaderUrl = fragment;
  17660. }
  17661. else {
  17662. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  17663. }
  17664. // Fragment shader
  17665. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  17666. };
  17667. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  17668. try {
  17669. var engine = this._engine;
  17670. if (!engine.getCaps().highPrecisionShaderSupported) {
  17671. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  17672. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  17673. }
  17674. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  17675. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  17676. this._attributes = engine.getAttributes(this._program, attributesNames);
  17677. for (var index = 0; index < this._samplers.length; index++) {
  17678. var sampler = this.getUniform(this._samplers[index]);
  17679. if (sampler == null) {
  17680. this._samplers.splice(index, 1);
  17681. index--;
  17682. }
  17683. }
  17684. engine.bindSamplers(this);
  17685. this._isReady = true;
  17686. if (this.onCompiled) {
  17687. this.onCompiled(this);
  17688. }
  17689. }
  17690. catch (e) {
  17691. // Is it a problem with precision?
  17692. if (e.message.indexOf("highp") !== -1) {
  17693. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  17694. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  17695. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  17696. return;
  17697. }
  17698. // Let's go through fallbacks then
  17699. if (fallbacks && fallbacks.isMoreFallbacks) {
  17700. defines = fallbacks.reduce(defines);
  17701. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  17702. }
  17703. else {
  17704. BABYLON.Tools.Error("Unable to compile effect: ");
  17705. if (this.name.vertexElement) {
  17706. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  17707. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  17708. }
  17709. else if (this.name.vertex) {
  17710. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  17711. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  17712. }
  17713. else {
  17714. BABYLON.Tools.Error("Vertex shader:" + this.name);
  17715. BABYLON.Tools.Error("Fragment shader:" + this.name);
  17716. }
  17717. BABYLON.Tools.Error("Defines: " + defines);
  17718. BABYLON.Tools.Error("Error: " + e.message);
  17719. this._compilationError = e.message;
  17720. if (this.onError) {
  17721. this.onError(this, this._compilationError);
  17722. }
  17723. }
  17724. }
  17725. };
  17726. Effect.prototype._bindTexture = function (channel, texture) {
  17727. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  17728. };
  17729. Effect.prototype.setTexture = function (channel, texture) {
  17730. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  17731. };
  17732. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  17733. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  17734. };
  17735. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  17736. if (!this._valueCache[uniformName]) {
  17737. this._valueCache[uniformName] = new BABYLON.Matrix();
  17738. }
  17739. for (var index = 0; index < 16; index++) {
  17740. this._valueCache[uniformName].m[index] = matrix.m[index];
  17741. }
  17742. };
  17743. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  17744. if (!this._valueCache[uniformName]) {
  17745. this._valueCache[uniformName] = [x, y];
  17746. return;
  17747. }
  17748. this._valueCache[uniformName][0] = x;
  17749. this._valueCache[uniformName][1] = y;
  17750. };
  17751. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  17752. if (!this._valueCache[uniformName]) {
  17753. this._valueCache[uniformName] = [x, y, z];
  17754. return;
  17755. }
  17756. this._valueCache[uniformName][0] = x;
  17757. this._valueCache[uniformName][1] = y;
  17758. this._valueCache[uniformName][2] = z;
  17759. };
  17760. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  17761. if (!this._valueCache[uniformName]) {
  17762. this._valueCache[uniformName] = [x, y, z, w];
  17763. return;
  17764. }
  17765. this._valueCache[uniformName][0] = x;
  17766. this._valueCache[uniformName][1] = y;
  17767. this._valueCache[uniformName][2] = z;
  17768. this._valueCache[uniformName][3] = w;
  17769. };
  17770. Effect.prototype.setArray = function (uniformName, array) {
  17771. this._engine.setArray(this.getUniform(uniformName), array);
  17772. return this;
  17773. };
  17774. Effect.prototype.setArray2 = function (uniformName, array) {
  17775. this._engine.setArray2(this.getUniform(uniformName), array);
  17776. return this;
  17777. };
  17778. Effect.prototype.setArray3 = function (uniformName, array) {
  17779. this._engine.setArray3(this.getUniform(uniformName), array);
  17780. return this;
  17781. };
  17782. Effect.prototype.setArray4 = function (uniformName, array) {
  17783. this._engine.setArray4(this.getUniform(uniformName), array);
  17784. return this;
  17785. };
  17786. Effect.prototype.setMatrices = function (uniformName, matrices) {
  17787. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  17788. return this;
  17789. };
  17790. Effect.prototype.setMatrix = function (uniformName, matrix) {
  17791. if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  17792. return this;
  17793. this._cacheMatrix(uniformName, matrix);
  17794. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  17795. return this;
  17796. };
  17797. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  17798. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  17799. return this;
  17800. };
  17801. Effect.prototype.setMatrix2x2 = function (uniformname, matrix) {
  17802. this._engine.setMatrix2x2(this.getUniform(uniformname), matrix);
  17803. return this;
  17804. };
  17805. Effect.prototype.setFloat = function (uniformName, value) {
  17806. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  17807. return this;
  17808. this._valueCache[uniformName] = value;
  17809. this._engine.setFloat(this.getUniform(uniformName), value);
  17810. return this;
  17811. };
  17812. Effect.prototype.setBool = function (uniformName, bool) {
  17813. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  17814. return this;
  17815. this._valueCache[uniformName] = bool;
  17816. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  17817. return this;
  17818. };
  17819. Effect.prototype.setVector2 = function (uniformName, vector2) {
  17820. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  17821. return this;
  17822. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  17823. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  17824. return this;
  17825. };
  17826. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  17827. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  17828. return this;
  17829. this._cacheFloat2(uniformName, x, y);
  17830. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  17831. return this;
  17832. };
  17833. Effect.prototype.setVector3 = function (uniformName, vector3) {
  17834. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  17835. return this;
  17836. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  17837. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  17838. return this;
  17839. };
  17840. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  17841. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  17842. return this;
  17843. this._cacheFloat3(uniformName, x, y, z);
  17844. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  17845. return this;
  17846. };
  17847. Effect.prototype.setVector4 = function (uniformName, vector4) {
  17848. 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)
  17849. return this;
  17850. this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w);
  17851. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  17852. return this;
  17853. };
  17854. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  17855. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  17856. return this;
  17857. this._cacheFloat4(uniformName, x, y, z, w);
  17858. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  17859. return this;
  17860. };
  17861. Effect.prototype.setColor3 = function (uniformName, color3) {
  17862. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  17863. return this;
  17864. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  17865. this._engine.setColor3(this.getUniform(uniformName), color3);
  17866. return this;
  17867. };
  17868. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  17869. 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)
  17870. return this;
  17871. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  17872. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  17873. return this;
  17874. };
  17875. // Statics
  17876. Effect.ShadersStore = {};
  17877. return Effect;
  17878. })();
  17879. BABYLON.Effect = Effect;
  17880. })(BABYLON || (BABYLON = {}));
  17881. var BABYLON;
  17882. (function (BABYLON) {
  17883. var MaterialDefines = (function () {
  17884. function MaterialDefines() {
  17885. }
  17886. MaterialDefines.prototype.isEqual = function (other) {
  17887. for (var index = 0; index < this._keys.length; index++) {
  17888. var prop = this._keys[index];
  17889. if (this[prop] !== other[prop]) {
  17890. return false;
  17891. }
  17892. }
  17893. return true;
  17894. };
  17895. MaterialDefines.prototype.cloneTo = function (other) {
  17896. for (var index = 0; index < this._keys.length; index++) {
  17897. var prop = this._keys[index];
  17898. other[prop] = this[prop];
  17899. }
  17900. };
  17901. MaterialDefines.prototype.reset = function () {
  17902. for (var index = 0; index < this._keys.length; index++) {
  17903. var prop = this._keys[index];
  17904. if (prop === "BonesPerMesh") {
  17905. this[prop] = 0;
  17906. continue;
  17907. }
  17908. this[prop] = false;
  17909. }
  17910. };
  17911. MaterialDefines.prototype.toString = function () {
  17912. var result = "";
  17913. for (var index = 0; index < this._keys.length; index++) {
  17914. var prop = this._keys[index];
  17915. if (prop === "BonesPerMesh" && this[prop] > 0) {
  17916. result += "#define BonesPerMesh " + this[prop] + "\n";
  17917. continue;
  17918. }
  17919. if (this[prop]) {
  17920. result += "#define " + prop + "\n";
  17921. }
  17922. }
  17923. return result;
  17924. };
  17925. return MaterialDefines;
  17926. })();
  17927. BABYLON.MaterialDefines = MaterialDefines;
  17928. var Material = (function () {
  17929. function Material(name, scene, doNotAdd) {
  17930. this.name = name;
  17931. this.checkReadyOnEveryCall = false;
  17932. this.checkReadyOnlyOnce = false;
  17933. this.state = "";
  17934. this.alpha = 1.0;
  17935. this.backFaceCulling = true;
  17936. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  17937. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  17938. this.disableDepthWrite = false;
  17939. this.fogEnabled = true;
  17940. this._wasPreviouslyReady = false;
  17941. this._fillMode = Material.TriangleFillMode;
  17942. this.pointSize = 1.0;
  17943. this.zOffset = 0;
  17944. this.id = name;
  17945. this._scene = scene;
  17946. if (!doNotAdd) {
  17947. scene.materials.push(this);
  17948. }
  17949. }
  17950. Object.defineProperty(Material, "TriangleFillMode", {
  17951. get: function () {
  17952. return Material._TriangleFillMode;
  17953. },
  17954. enumerable: true,
  17955. configurable: true
  17956. });
  17957. Object.defineProperty(Material, "WireFrameFillMode", {
  17958. get: function () {
  17959. return Material._WireFrameFillMode;
  17960. },
  17961. enumerable: true,
  17962. configurable: true
  17963. });
  17964. Object.defineProperty(Material, "PointFillMode", {
  17965. get: function () {
  17966. return Material._PointFillMode;
  17967. },
  17968. enumerable: true,
  17969. configurable: true
  17970. });
  17971. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  17972. get: function () {
  17973. return Material._ClockWiseSideOrientation;
  17974. },
  17975. enumerable: true,
  17976. configurable: true
  17977. });
  17978. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  17979. get: function () {
  17980. return Material._CounterClockWiseSideOrientation;
  17981. },
  17982. enumerable: true,
  17983. configurable: true
  17984. });
  17985. Object.defineProperty(Material.prototype, "wireframe", {
  17986. get: function () {
  17987. return this._fillMode === Material.WireFrameFillMode;
  17988. },
  17989. set: function (value) {
  17990. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  17991. },
  17992. enumerable: true,
  17993. configurable: true
  17994. });
  17995. Object.defineProperty(Material.prototype, "pointsCloud", {
  17996. get: function () {
  17997. return this._fillMode === Material.PointFillMode;
  17998. },
  17999. set: function (value) {
  18000. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  18001. },
  18002. enumerable: true,
  18003. configurable: true
  18004. });
  18005. Object.defineProperty(Material.prototype, "fillMode", {
  18006. get: function () {
  18007. return this._fillMode;
  18008. },
  18009. set: function (value) {
  18010. this._fillMode = value;
  18011. },
  18012. enumerable: true,
  18013. configurable: true
  18014. });
  18015. Material.prototype.isReady = function (mesh, useInstances) {
  18016. return true;
  18017. };
  18018. Material.prototype.getEffect = function () {
  18019. return this._effect;
  18020. };
  18021. Material.prototype.getScene = function () {
  18022. return this._scene;
  18023. };
  18024. Material.prototype.needAlphaBlending = function () {
  18025. return (this.alpha < 1.0);
  18026. };
  18027. Material.prototype.needAlphaTesting = function () {
  18028. return false;
  18029. };
  18030. Material.prototype.getAlphaTestTexture = function () {
  18031. return null;
  18032. };
  18033. Material.prototype.trackCreation = function (onCompiled, onError) {
  18034. };
  18035. Material.prototype._preBind = function () {
  18036. var engine = this._scene.getEngine();
  18037. engine.enableEffect(this._effect);
  18038. engine.setState(this.backFaceCulling, this.zOffset, false, this.sideOrientation === Material.ClockWiseSideOrientation);
  18039. };
  18040. Material.prototype.bind = function (world, mesh) {
  18041. this._scene._cachedMaterial = this;
  18042. if (this.onBind) {
  18043. this.onBind(this, mesh);
  18044. }
  18045. if (this.disableDepthWrite) {
  18046. var engine = this._scene.getEngine();
  18047. this._cachedDepthWriteState = engine.getDepthWrite();
  18048. engine.setDepthWrite(false);
  18049. }
  18050. };
  18051. Material.prototype.bindOnlyWorldMatrix = function (world) {
  18052. };
  18053. Material.prototype.unbind = function () {
  18054. if (this.disableDepthWrite) {
  18055. var engine = this._scene.getEngine();
  18056. engine.setDepthWrite(this._cachedDepthWriteState);
  18057. }
  18058. };
  18059. Material.prototype.clone = function (name) {
  18060. return null;
  18061. };
  18062. Material.prototype.getBindedMeshes = function () {
  18063. var result = new Array();
  18064. for (var index = 0; index < this._scene.meshes.length; index++) {
  18065. var mesh = this._scene.meshes[index];
  18066. if (mesh.material === this) {
  18067. result.push(mesh);
  18068. }
  18069. }
  18070. return result;
  18071. };
  18072. Material.prototype.dispose = function (forceDisposeEffect) {
  18073. // Animations
  18074. this.getScene().stopAnimation(this);
  18075. // Remove from scene
  18076. var index = this._scene.materials.indexOf(this);
  18077. if (index >= 0) {
  18078. this._scene.materials.splice(index, 1);
  18079. }
  18080. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  18081. if (forceDisposeEffect && this._effect) {
  18082. this._scene.getEngine()._releaseEffect(this._effect);
  18083. this._effect = null;
  18084. }
  18085. // Remove from meshes
  18086. for (index = 0; index < this._scene.meshes.length; index++) {
  18087. var mesh = this._scene.meshes[index];
  18088. if (mesh.material === this) {
  18089. mesh.material = null;
  18090. }
  18091. }
  18092. // Callback
  18093. if (this.onDispose) {
  18094. this.onDispose();
  18095. }
  18096. };
  18097. Material.prototype.copyTo = function (other) {
  18098. other.checkReadyOnlyOnce = this.checkReadyOnlyOnce;
  18099. other.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  18100. other.alpha = this.alpha;
  18101. other.fillMode = this.fillMode;
  18102. other.backFaceCulling = this.backFaceCulling;
  18103. other.wireframe = this.wireframe;
  18104. other.fogEnabled = this.fogEnabled;
  18105. other.wireframe = this.wireframe;
  18106. other.zOffset = this.zOffset;
  18107. other.alphaMode = this.alphaMode;
  18108. other.sideOrientation = this.sideOrientation;
  18109. other.disableDepthWrite = this.disableDepthWrite;
  18110. other.pointSize = this.pointSize;
  18111. other.pointsCloud = this.pointsCloud;
  18112. };
  18113. Material._TriangleFillMode = 0;
  18114. Material._WireFrameFillMode = 1;
  18115. Material._PointFillMode = 2;
  18116. Material._ClockWiseSideOrientation = 0;
  18117. Material._CounterClockWiseSideOrientation = 1;
  18118. return Material;
  18119. })();
  18120. BABYLON.Material = Material;
  18121. })(BABYLON || (BABYLON = {}));
  18122. var BABYLON;
  18123. (function (BABYLON) {
  18124. var maxSimultaneousLights = 4;
  18125. var FresnelParameters = (function () {
  18126. function FresnelParameters() {
  18127. this.isEnabled = true;
  18128. this.leftColor = BABYLON.Color3.White();
  18129. this.rightColor = BABYLON.Color3.Black();
  18130. this.bias = 0;
  18131. this.power = 1;
  18132. }
  18133. FresnelParameters.prototype.clone = function () {
  18134. var newFresnelParameters = new FresnelParameters();
  18135. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  18136. return new FresnelParameters;
  18137. };
  18138. return FresnelParameters;
  18139. })();
  18140. BABYLON.FresnelParameters = FresnelParameters;
  18141. var StandardMaterialDefines = (function (_super) {
  18142. __extends(StandardMaterialDefines, _super);
  18143. function StandardMaterialDefines() {
  18144. _super.call(this);
  18145. this.DIFFUSE = false;
  18146. this.AMBIENT = false;
  18147. this.OPACITY = false;
  18148. this.OPACITYRGB = false;
  18149. this.REFLECTION = false;
  18150. this.EMISSIVE = false;
  18151. this.SPECULAR = false;
  18152. this.BUMP = false;
  18153. this.SPECULAROVERALPHA = false;
  18154. this.CLIPPLANE = false;
  18155. this.ALPHATEST = false;
  18156. this.ALPHAFROMDIFFUSE = false;
  18157. this.POINTSIZE = false;
  18158. this.FOG = false;
  18159. this.LIGHT0 = false;
  18160. this.LIGHT1 = false;
  18161. this.LIGHT2 = false;
  18162. this.LIGHT3 = false;
  18163. this.SPOTLIGHT0 = false;
  18164. this.SPOTLIGHT1 = false;
  18165. this.SPOTLIGHT2 = false;
  18166. this.SPOTLIGHT3 = false;
  18167. this.HEMILIGHT0 = false;
  18168. this.HEMILIGHT1 = false;
  18169. this.HEMILIGHT2 = false;
  18170. this.HEMILIGHT3 = false;
  18171. this.POINTDIRLIGHT0 = false;
  18172. this.POINTDIRLIGHT1 = false;
  18173. this.POINTDIRLIGHT2 = false;
  18174. this.POINTDIRLIGHT3 = false;
  18175. this.SPECULARTERM = false;
  18176. this.SHADOW0 = false;
  18177. this.SHADOW1 = false;
  18178. this.SHADOW2 = false;
  18179. this.SHADOW3 = false;
  18180. this.SHADOWS = false;
  18181. this.SHADOWVSM0 = false;
  18182. this.SHADOWVSM1 = false;
  18183. this.SHADOWVSM2 = false;
  18184. this.SHADOWVSM3 = false;
  18185. this.SHADOWPCF0 = false;
  18186. this.SHADOWPCF1 = false;
  18187. this.SHADOWPCF2 = false;
  18188. this.SHADOWPCF3 = false;
  18189. this.DIFFUSEFRESNEL = false;
  18190. this.OPACITYFRESNEL = false;
  18191. this.REFLECTIONFRESNEL = false;
  18192. this.EMISSIVEFRESNEL = false;
  18193. this.FRESNEL = false;
  18194. this.NORMAL = false;
  18195. this.UV1 = false;
  18196. this.UV2 = false;
  18197. this.VERTEXCOLOR = false;
  18198. this.VERTEXALPHA = false;
  18199. this.BONES = false;
  18200. this.BONES4 = false;
  18201. this.BonesPerMesh = 0;
  18202. this.INSTANCES = false;
  18203. this.GLOSSINESS = false;
  18204. this.ROUGHNESS = false;
  18205. this.EMISSIVEASILLUMINATION = false;
  18206. this.REFLECTIONFRESNELFROMSPECULAR = false;
  18207. this.LIGHTMAP = false;
  18208. this.USELIGHTMAPASSHADOWMAP = false;
  18209. this.REFLECTIONMAP_3D = false;
  18210. this.REFLECTIONMAP_SPHERICAL = false;
  18211. this.REFLECTIONMAP_PLANAR = false;
  18212. this.REFLECTIONMAP_CUBIC = false;
  18213. this.REFLECTIONMAP_PROJECTION = false;
  18214. this.REFLECTIONMAP_SKYBOX = false;
  18215. this.REFLECTIONMAP_EXPLICIT = false;
  18216. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  18217. this.INVERTCUBICMAP = false;
  18218. this._keys = Object.keys(this);
  18219. }
  18220. return StandardMaterialDefines;
  18221. })(BABYLON.MaterialDefines);
  18222. var StandardMaterial = (function (_super) {
  18223. __extends(StandardMaterial, _super);
  18224. function StandardMaterial(name, scene) {
  18225. var _this = this;
  18226. _super.call(this, name, scene);
  18227. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  18228. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  18229. this.specularColor = new BABYLON.Color3(1, 1, 1);
  18230. this.specularPower = 64;
  18231. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  18232. this.useAlphaFromDiffuseTexture = false;
  18233. this.useEmissiveAsIllumination = false;
  18234. this.useReflectionFresnelFromSpecular = false;
  18235. this.useSpecularOverAlpha = true;
  18236. this.disableLighting = false;
  18237. this.roughness = 0;
  18238. this.useLightmapAsShadowmap = false;
  18239. this.useGlossinessFromSpecularMapAlpha = false;
  18240. this._renderTargets = new BABYLON.SmartArray(16);
  18241. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  18242. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  18243. this._scaledDiffuse = new BABYLON.Color3();
  18244. this._scaledSpecular = new BABYLON.Color3();
  18245. this._defines = new StandardMaterialDefines();
  18246. this._cachedDefines = new StandardMaterialDefines();
  18247. this._cachedDefines.BonesPerMesh = -1;
  18248. this.getRenderTargetTextures = function () {
  18249. _this._renderTargets.reset();
  18250. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  18251. _this._renderTargets.push(_this.reflectionTexture);
  18252. }
  18253. return _this._renderTargets;
  18254. };
  18255. }
  18256. StandardMaterial.prototype.needAlphaBlending = function () {
  18257. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  18258. };
  18259. StandardMaterial.prototype.needAlphaTesting = function () {
  18260. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  18261. };
  18262. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  18263. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  18264. };
  18265. StandardMaterial.prototype.getAlphaTestTexture = function () {
  18266. return this.diffuseTexture;
  18267. };
  18268. // Methods
  18269. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  18270. if (!mesh) {
  18271. return true;
  18272. }
  18273. if (this._defines.INSTANCES !== useInstances) {
  18274. return false;
  18275. }
  18276. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  18277. return true;
  18278. }
  18279. return false;
  18280. };
  18281. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  18282. if (this.checkReadyOnlyOnce) {
  18283. if (this._wasPreviouslyReady) {
  18284. return true;
  18285. }
  18286. }
  18287. var scene = this.getScene();
  18288. if (!this.checkReadyOnEveryCall) {
  18289. if (this._renderId === scene.getRenderId()) {
  18290. if (this._checkCache(scene, mesh, useInstances)) {
  18291. return true;
  18292. }
  18293. }
  18294. }
  18295. var engine = scene.getEngine();
  18296. var needNormals = false;
  18297. var needUVs = false;
  18298. this._defines.reset();
  18299. // Textures
  18300. if (scene.texturesEnabled) {
  18301. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  18302. if (!this.diffuseTexture.isReady()) {
  18303. return false;
  18304. }
  18305. else {
  18306. needUVs = true;
  18307. this._defines.DIFFUSE = true;
  18308. }
  18309. }
  18310. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  18311. if (!this.ambientTexture.isReady()) {
  18312. return false;
  18313. }
  18314. else {
  18315. needUVs = true;
  18316. this._defines.AMBIENT = true;
  18317. }
  18318. }
  18319. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  18320. if (!this.opacityTexture.isReady()) {
  18321. return false;
  18322. }
  18323. else {
  18324. needUVs = true;
  18325. this._defines.OPACITY = true;
  18326. if (this.opacityTexture.getAlphaFromRGB) {
  18327. this._defines.OPACITYRGB = true;
  18328. }
  18329. }
  18330. }
  18331. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  18332. if (!this.reflectionTexture.isReady()) {
  18333. return false;
  18334. }
  18335. else {
  18336. needNormals = true;
  18337. this._defines.REFLECTION = true;
  18338. if (this.roughness > 0) {
  18339. this._defines.ROUGHNESS = true;
  18340. }
  18341. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  18342. this._defines.INVERTCUBICMAP = true;
  18343. }
  18344. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  18345. switch (this.reflectionTexture.coordinatesMode) {
  18346. case BABYLON.Texture.CUBIC_MODE:
  18347. case BABYLON.Texture.INVCUBIC_MODE:
  18348. this._defines.REFLECTIONMAP_CUBIC = true;
  18349. break;
  18350. case BABYLON.Texture.EXPLICIT_MODE:
  18351. this._defines.REFLECTIONMAP_EXPLICIT = true;
  18352. break;
  18353. case BABYLON.Texture.PLANAR_MODE:
  18354. this._defines.REFLECTIONMAP_PLANAR = true;
  18355. break;
  18356. case BABYLON.Texture.PROJECTION_MODE:
  18357. this._defines.REFLECTIONMAP_PROJECTION = true;
  18358. break;
  18359. case BABYLON.Texture.SKYBOX_MODE:
  18360. this._defines.REFLECTIONMAP_SKYBOX = true;
  18361. break;
  18362. case BABYLON.Texture.SPHERICAL_MODE:
  18363. this._defines.REFLECTIONMAP_SPHERICAL = true;
  18364. break;
  18365. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  18366. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  18367. break;
  18368. }
  18369. }
  18370. }
  18371. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  18372. if (!this.emissiveTexture.isReady()) {
  18373. return false;
  18374. }
  18375. else {
  18376. needUVs = true;
  18377. this._defines.EMISSIVE = true;
  18378. }
  18379. }
  18380. if (this.lightmapTexture && StandardMaterial.LightmapEnabled) {
  18381. if (!this.lightmapTexture.isReady()) {
  18382. return false;
  18383. }
  18384. else {
  18385. needUVs = true;
  18386. this._defines.LIGHTMAP = true;
  18387. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  18388. }
  18389. }
  18390. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  18391. if (!this.specularTexture.isReady()) {
  18392. return false;
  18393. }
  18394. else {
  18395. needUVs = true;
  18396. this._defines.SPECULAR = true;
  18397. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  18398. }
  18399. }
  18400. }
  18401. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  18402. if (!this.bumpTexture.isReady()) {
  18403. return false;
  18404. }
  18405. else {
  18406. needUVs = true;
  18407. this._defines.BUMP = true;
  18408. }
  18409. }
  18410. // Effect
  18411. if (scene.clipPlane) {
  18412. this._defines.CLIPPLANE = true;
  18413. }
  18414. if (engine.getAlphaTesting()) {
  18415. this._defines.ALPHATEST = true;
  18416. }
  18417. if (this._shouldUseAlphaFromDiffuseTexture()) {
  18418. this._defines.ALPHAFROMDIFFUSE = true;
  18419. }
  18420. if (this.useEmissiveAsIllumination) {
  18421. this._defines.EMISSIVEASILLUMINATION = true;
  18422. }
  18423. if (this.useReflectionFresnelFromSpecular) {
  18424. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  18425. }
  18426. // Point size
  18427. if (this.pointsCloud || scene.forcePointsCloud) {
  18428. this._defines.POINTSIZE = true;
  18429. }
  18430. // Fog
  18431. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  18432. this._defines.FOG = true;
  18433. }
  18434. var lightIndex = 0;
  18435. if (scene.lightsEnabled && !this.disableLighting) {
  18436. for (var index = 0; index < scene.lights.length; index++) {
  18437. var light = scene.lights[index];
  18438. if (!light.isEnabled()) {
  18439. continue;
  18440. }
  18441. // Excluded check
  18442. if (light._excludedMeshesIds.length > 0) {
  18443. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  18444. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  18445. if (excludedMesh) {
  18446. light.excludedMeshes.push(excludedMesh);
  18447. }
  18448. }
  18449. light._excludedMeshesIds = [];
  18450. }
  18451. // Included check
  18452. if (light._includedOnlyMeshesIds.length > 0) {
  18453. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  18454. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  18455. if (includedOnlyMesh) {
  18456. light.includedOnlyMeshes.push(includedOnlyMesh);
  18457. }
  18458. }
  18459. light._includedOnlyMeshesIds = [];
  18460. }
  18461. if (!light.canAffectMesh(mesh)) {
  18462. continue;
  18463. }
  18464. needNormals = true;
  18465. this._defines["LIGHT" + lightIndex] = true;
  18466. var type;
  18467. if (light instanceof BABYLON.SpotLight) {
  18468. type = "SPOTLIGHT" + lightIndex;
  18469. }
  18470. else if (light instanceof BABYLON.HemisphericLight) {
  18471. type = "HEMILIGHT" + lightIndex;
  18472. }
  18473. else {
  18474. type = "POINTDIRLIGHT" + lightIndex;
  18475. }
  18476. this._defines[type] = true;
  18477. // Specular
  18478. if (!light.specular.equalsFloats(0, 0, 0)) {
  18479. this._defines.SPECULARTERM = true;
  18480. }
  18481. // Shadows
  18482. if (scene.shadowsEnabled) {
  18483. var shadowGenerator = light.getShadowGenerator();
  18484. if (mesh && mesh.receiveShadows && shadowGenerator) {
  18485. this._defines["SHADOW" + lightIndex] = true;
  18486. this._defines.SHADOWS = true;
  18487. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  18488. this._defines["SHADOWVSM" + lightIndex] = true;
  18489. }
  18490. if (shadowGenerator.usePoissonSampling) {
  18491. this._defines["SHADOWPCF" + lightIndex] = true;
  18492. }
  18493. }
  18494. }
  18495. lightIndex++;
  18496. if (lightIndex === maxSimultaneousLights)
  18497. break;
  18498. }
  18499. }
  18500. if (StandardMaterial.FresnelEnabled) {
  18501. // Fresnel
  18502. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  18503. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  18504. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  18505. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  18506. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  18507. this._defines.DIFFUSEFRESNEL = true;
  18508. }
  18509. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  18510. this._defines.OPACITYFRESNEL = true;
  18511. }
  18512. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  18513. this._defines.REFLECTIONFRESNEL = true;
  18514. }
  18515. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  18516. this._defines.EMISSIVEFRESNEL = true;
  18517. }
  18518. needNormals = true;
  18519. this._defines.FRESNEL = true;
  18520. }
  18521. }
  18522. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  18523. this._defines.SPECULAROVERALPHA = true;
  18524. }
  18525. // Attribs
  18526. if (mesh) {
  18527. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18528. this._defines.NORMAL = true;
  18529. }
  18530. if (needUVs) {
  18531. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  18532. this._defines.UV1 = true;
  18533. }
  18534. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  18535. this._defines.UV2 = true;
  18536. }
  18537. }
  18538. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  18539. this._defines.VERTEXCOLOR = true;
  18540. if (mesh.hasVertexAlpha) {
  18541. this._defines.VERTEXALPHA = true;
  18542. }
  18543. }
  18544. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  18545. this._defines.BONES = true;
  18546. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  18547. this._defines.BONES4 = true;
  18548. }
  18549. // Instances
  18550. if (useInstances) {
  18551. this._defines.INSTANCES = true;
  18552. }
  18553. }
  18554. // Get correct effect
  18555. if (!this._defines.isEqual(this._cachedDefines)) {
  18556. this._defines.cloneTo(this._cachedDefines);
  18557. scene.resetCachedMaterial();
  18558. // Fallbacks
  18559. var fallbacks = new BABYLON.EffectFallbacks();
  18560. if (this._defines.REFLECTION) {
  18561. fallbacks.addFallback(0, "REFLECTION");
  18562. }
  18563. if (this._defines.SPECULAR) {
  18564. fallbacks.addFallback(0, "SPECULAR");
  18565. }
  18566. if (this._defines.BUMP) {
  18567. fallbacks.addFallback(0, "BUMP");
  18568. }
  18569. if (this._defines.SPECULAROVERALPHA) {
  18570. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  18571. }
  18572. if (this._defines.FOG) {
  18573. fallbacks.addFallback(1, "FOG");
  18574. }
  18575. for (lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  18576. if (!this._defines["LIGHT" + lightIndex]) {
  18577. continue;
  18578. }
  18579. if (lightIndex > 0) {
  18580. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  18581. }
  18582. if (this._defines["SHADOW" + lightIndex]) {
  18583. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  18584. }
  18585. if (this._defines["SHADOWPCF" + lightIndex]) {
  18586. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  18587. }
  18588. if (this._defines["SHADOWVSM" + lightIndex]) {
  18589. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  18590. }
  18591. }
  18592. if (this._defines.SPECULARTERM) {
  18593. fallbacks.addFallback(0, "SPECULARTERM");
  18594. }
  18595. if (this._defines.DIFFUSEFRESNEL) {
  18596. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  18597. }
  18598. if (this._defines.OPACITYFRESNEL) {
  18599. fallbacks.addFallback(2, "OPACITYFRESNEL");
  18600. }
  18601. if (this._defines.REFLECTIONFRESNEL) {
  18602. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  18603. }
  18604. if (this._defines.EMISSIVEFRESNEL) {
  18605. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  18606. }
  18607. if (this._defines.FRESNEL) {
  18608. fallbacks.addFallback(4, "FRESNEL");
  18609. }
  18610. if (this._defines.BONES4) {
  18611. fallbacks.addFallback(0, "BONES4");
  18612. }
  18613. //Attributes
  18614. var attribs = [BABYLON.VertexBuffer.PositionKind];
  18615. if (this._defines.NORMAL) {
  18616. attribs.push(BABYLON.VertexBuffer.NormalKind);
  18617. }
  18618. if (this._defines.UV1) {
  18619. attribs.push(BABYLON.VertexBuffer.UVKind);
  18620. }
  18621. if (this._defines.UV2) {
  18622. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  18623. }
  18624. if (this._defines.VERTEXCOLOR) {
  18625. attribs.push(BABYLON.VertexBuffer.ColorKind);
  18626. }
  18627. if (this._defines.BONES) {
  18628. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  18629. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  18630. }
  18631. if (this._defines.INSTANCES) {
  18632. attribs.push("world0");
  18633. attribs.push("world1");
  18634. attribs.push("world2");
  18635. attribs.push("world3");
  18636. }
  18637. // Legacy browser patch
  18638. var shaderName = "default";
  18639. if (!scene.getEngine().getCaps().standardDerivatives) {
  18640. shaderName = "legacydefault";
  18641. }
  18642. var join = this._defines.toString();
  18643. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  18644. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  18645. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  18646. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  18647. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  18648. "vFogInfos", "vFogColor", "pointSize",
  18649. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos",
  18650. "mBones",
  18651. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix",
  18652. "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3",
  18653. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor"
  18654. ], ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler",
  18655. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  18656. ], join, fallbacks, this.onCompiled, this.onError);
  18657. }
  18658. if (!this._effect.isReady()) {
  18659. return false;
  18660. }
  18661. this._renderId = scene.getRenderId();
  18662. this._wasPreviouslyReady = true;
  18663. if (mesh) {
  18664. if (!mesh._materialDefines) {
  18665. mesh._materialDefines = new StandardMaterialDefines();
  18666. }
  18667. this._defines.cloneTo(mesh._materialDefines);
  18668. }
  18669. return true;
  18670. };
  18671. StandardMaterial.prototype.unbind = function () {
  18672. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  18673. this._effect.setTexture("reflection2DSampler", null);
  18674. }
  18675. _super.prototype.unbind.call(this);
  18676. };
  18677. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  18678. this._effect.setMatrix("world", world);
  18679. };
  18680. StandardMaterial.prototype.bind = function (world, mesh) {
  18681. var scene = this.getScene();
  18682. // Matrices
  18683. this.bindOnlyWorldMatrix(world);
  18684. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  18685. // Bones
  18686. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  18687. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  18688. }
  18689. if (scene.getCachedMaterial() !== this) {
  18690. if (StandardMaterial.FresnelEnabled) {
  18691. // Fresnel
  18692. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  18693. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  18694. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  18695. }
  18696. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  18697. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  18698. }
  18699. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  18700. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  18701. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  18702. }
  18703. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  18704. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  18705. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  18706. }
  18707. }
  18708. // Textures
  18709. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  18710. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  18711. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  18712. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  18713. }
  18714. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  18715. this._effect.setTexture("ambientSampler", this.ambientTexture);
  18716. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  18717. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  18718. }
  18719. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  18720. this._effect.setTexture("opacitySampler", this.opacityTexture);
  18721. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  18722. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  18723. }
  18724. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  18725. if (this.reflectionTexture.isCube) {
  18726. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  18727. }
  18728. else {
  18729. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  18730. }
  18731. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  18732. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  18733. }
  18734. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  18735. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  18736. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  18737. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  18738. }
  18739. if (this.lightmapTexture && StandardMaterial.LightmapEnabled) {
  18740. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  18741. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  18742. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  18743. }
  18744. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  18745. this._effect.setTexture("specularSampler", this.specularTexture);
  18746. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  18747. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  18748. }
  18749. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  18750. this._effect.setTexture("bumpSampler", this.bumpTexture);
  18751. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  18752. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  18753. }
  18754. // Clip plane
  18755. if (scene.clipPlane) {
  18756. var clipPlane = scene.clipPlane;
  18757. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  18758. }
  18759. // Point size
  18760. if (this.pointsCloud) {
  18761. this._effect.setFloat("pointSize", this.pointSize);
  18762. }
  18763. // Colors
  18764. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  18765. // Scaling down color according to emissive
  18766. this._scaledSpecular.r = this.specularColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  18767. this._scaledSpecular.g = this.specularColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  18768. this._scaledSpecular.b = this.specularColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  18769. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  18770. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  18771. if (this._defines.SPECULARTERM) {
  18772. this._effect.setColor4("vSpecularColor", this._scaledSpecular, this.specularPower);
  18773. }
  18774. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  18775. }
  18776. // Scaling down color according to emissive
  18777. this._scaledDiffuse.r = this.diffuseColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  18778. this._scaledDiffuse.g = this.diffuseColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  18779. this._scaledDiffuse.b = this.diffuseColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  18780. this._effect.setColor4("vDiffuseColor", this._scaledDiffuse, this.alpha * mesh.visibility);
  18781. if (scene.lightsEnabled && !this.disableLighting) {
  18782. var lightIndex = 0;
  18783. for (var index = 0; index < scene.lights.length; index++) {
  18784. var light = scene.lights[index];
  18785. if (!light.isEnabled()) {
  18786. continue;
  18787. }
  18788. if (!light.canAffectMesh(mesh)) {
  18789. continue;
  18790. }
  18791. if (light instanceof BABYLON.PointLight) {
  18792. // Point Light
  18793. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  18794. }
  18795. else if (light instanceof BABYLON.DirectionalLight) {
  18796. // Directional Light
  18797. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  18798. }
  18799. else if (light instanceof BABYLON.SpotLight) {
  18800. // Spot Light
  18801. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  18802. }
  18803. else if (light instanceof BABYLON.HemisphericLight) {
  18804. // Hemispheric Light
  18805. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  18806. }
  18807. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  18808. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  18809. if (this._defines.SPECULARTERM) {
  18810. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  18811. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  18812. }
  18813. // Shadows
  18814. if (scene.shadowsEnabled) {
  18815. var shadowGenerator = light.getShadowGenerator();
  18816. if (mesh.receiveShadows && shadowGenerator) {
  18817. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  18818. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  18819. this._effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  18820. }
  18821. }
  18822. lightIndex++;
  18823. if (lightIndex === maxSimultaneousLights)
  18824. break;
  18825. }
  18826. }
  18827. // View
  18828. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  18829. this._effect.setMatrix("view", scene.getViewMatrix());
  18830. }
  18831. // Fog
  18832. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  18833. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  18834. this._effect.setColor3("vFogColor", scene.fogColor);
  18835. }
  18836. _super.prototype.bind.call(this, world, mesh);
  18837. };
  18838. StandardMaterial.prototype.getAnimatables = function () {
  18839. var results = [];
  18840. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  18841. results.push(this.diffuseTexture);
  18842. }
  18843. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  18844. results.push(this.ambientTexture);
  18845. }
  18846. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  18847. results.push(this.opacityTexture);
  18848. }
  18849. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  18850. results.push(this.reflectionTexture);
  18851. }
  18852. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  18853. results.push(this.emissiveTexture);
  18854. }
  18855. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  18856. results.push(this.specularTexture);
  18857. }
  18858. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  18859. results.push(this.bumpTexture);
  18860. }
  18861. return results;
  18862. };
  18863. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  18864. if (this.diffuseTexture) {
  18865. this.diffuseTexture.dispose();
  18866. }
  18867. if (this.ambientTexture) {
  18868. this.ambientTexture.dispose();
  18869. }
  18870. if (this.opacityTexture) {
  18871. this.opacityTexture.dispose();
  18872. }
  18873. if (this.reflectionTexture) {
  18874. this.reflectionTexture.dispose();
  18875. }
  18876. if (this.emissiveTexture) {
  18877. this.emissiveTexture.dispose();
  18878. }
  18879. if (this.specularTexture) {
  18880. this.specularTexture.dispose();
  18881. }
  18882. if (this.bumpTexture) {
  18883. this.bumpTexture.dispose();
  18884. }
  18885. _super.prototype.dispose.call(this, forceDisposeEffect);
  18886. };
  18887. StandardMaterial.prototype.clone = function (name) {
  18888. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  18889. // Base material
  18890. this.copyTo(newStandardMaterial);
  18891. // Standard material
  18892. if (this.diffuseTexture && this.diffuseTexture.clone) {
  18893. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  18894. }
  18895. if (this.ambientTexture && this.ambientTexture.clone) {
  18896. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  18897. }
  18898. if (this.opacityTexture && this.opacityTexture.clone) {
  18899. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  18900. }
  18901. if (this.reflectionTexture && this.reflectionTexture.clone) {
  18902. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  18903. }
  18904. if (this.emissiveTexture && this.emissiveTexture.clone) {
  18905. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  18906. }
  18907. if (this.specularTexture && this.specularTexture.clone) {
  18908. newStandardMaterial.specularTexture = this.specularTexture.clone();
  18909. }
  18910. if (this.bumpTexture && this.bumpTexture.clone) {
  18911. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  18912. }
  18913. if (this.lightmapTexture && this.lightmapTexture.clone) {
  18914. newStandardMaterial.lightmapTexture = this.lightmapTexture.clone();
  18915. newStandardMaterial.useLightmapAsShadowmap = this.useLightmapAsShadowmap;
  18916. }
  18917. newStandardMaterial.ambientColor = this.ambientColor.clone();
  18918. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  18919. newStandardMaterial.specularColor = this.specularColor.clone();
  18920. newStandardMaterial.specularPower = this.specularPower;
  18921. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  18922. newStandardMaterial.useAlphaFromDiffuseTexture = this.useAlphaFromDiffuseTexture;
  18923. newStandardMaterial.useEmissiveAsIllumination = this.useEmissiveAsIllumination;
  18924. newStandardMaterial.useGlossinessFromSpecularMapAlpha = this.useGlossinessFromSpecularMapAlpha;
  18925. newStandardMaterial.useReflectionFresnelFromSpecular = this.useReflectionFresnelFromSpecular;
  18926. newStandardMaterial.useSpecularOverAlpha = this.useSpecularOverAlpha;
  18927. newStandardMaterial.roughness = this.roughness;
  18928. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.clone) {
  18929. newStandardMaterial.diffuseFresnelParameters = this.diffuseFresnelParameters.clone();
  18930. }
  18931. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.clone) {
  18932. newStandardMaterial.emissiveFresnelParameters = this.emissiveFresnelParameters.clone();
  18933. }
  18934. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.clone) {
  18935. newStandardMaterial.reflectionFresnelParameters = this.reflectionFresnelParameters.clone();
  18936. }
  18937. if (this.opacityFresnelParameters && this.opacityFresnelParameters.clone) {
  18938. newStandardMaterial.opacityFresnelParameters = this.opacityFresnelParameters.clone();
  18939. }
  18940. return newStandardMaterial;
  18941. };
  18942. // Statics
  18943. // Flags used to enable or disable a type of texture for all Standard Materials
  18944. StandardMaterial.DiffuseTextureEnabled = true;
  18945. StandardMaterial.AmbientTextureEnabled = true;
  18946. StandardMaterial.OpacityTextureEnabled = true;
  18947. StandardMaterial.ReflectionTextureEnabled = true;
  18948. StandardMaterial.EmissiveTextureEnabled = true;
  18949. StandardMaterial.SpecularTextureEnabled = true;
  18950. StandardMaterial.BumpTextureEnabled = true;
  18951. StandardMaterial.FresnelEnabled = true;
  18952. StandardMaterial.LightmapEnabled = true;
  18953. return StandardMaterial;
  18954. })(BABYLON.Material);
  18955. BABYLON.StandardMaterial = StandardMaterial;
  18956. })(BABYLON || (BABYLON = {}));
  18957. var BABYLON;
  18958. (function (BABYLON) {
  18959. var MultiMaterial = (function (_super) {
  18960. __extends(MultiMaterial, _super);
  18961. function MultiMaterial(name, scene) {
  18962. _super.call(this, name, scene, true);
  18963. this.subMaterials = new Array();
  18964. scene.multiMaterials.push(this);
  18965. }
  18966. // Properties
  18967. MultiMaterial.prototype.getSubMaterial = function (index) {
  18968. if (index < 0 || index >= this.subMaterials.length) {
  18969. return this.getScene().defaultMaterial;
  18970. }
  18971. return this.subMaterials[index];
  18972. };
  18973. // Methods
  18974. MultiMaterial.prototype.isReady = function (mesh) {
  18975. for (var index = 0; index < this.subMaterials.length; index++) {
  18976. var subMaterial = this.subMaterials[index];
  18977. if (subMaterial) {
  18978. if (!this.subMaterials[index].isReady(mesh)) {
  18979. return false;
  18980. }
  18981. }
  18982. }
  18983. return true;
  18984. };
  18985. MultiMaterial.prototype.clone = function (name) {
  18986. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  18987. for (var index = 0; index < this.subMaterials.length; index++) {
  18988. var subMaterial = this.subMaterials[index];
  18989. newMultiMaterial.subMaterials.push(subMaterial);
  18990. }
  18991. return newMultiMaterial;
  18992. };
  18993. return MultiMaterial;
  18994. })(BABYLON.Material);
  18995. BABYLON.MultiMaterial = MultiMaterial;
  18996. })(BABYLON || (BABYLON = {}));
  18997. var BABYLON;
  18998. (function (BABYLON) {
  18999. var SceneLoader = (function () {
  19000. function SceneLoader() {
  19001. }
  19002. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  19003. get: function () {
  19004. return SceneLoader._ForceFullSceneLoadingForIncremental;
  19005. },
  19006. set: function (value) {
  19007. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  19008. },
  19009. enumerable: true,
  19010. configurable: true
  19011. });
  19012. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  19013. get: function () {
  19014. return SceneLoader._ShowLoadingScreen;
  19015. },
  19016. set: function (value) {
  19017. SceneLoader._ShowLoadingScreen = value;
  19018. },
  19019. enumerable: true,
  19020. configurable: true
  19021. });
  19022. SceneLoader._getPluginForFilename = function (sceneFilename) {
  19023. var dotPosition = sceneFilename.lastIndexOf(".");
  19024. var queryStringPosition = sceneFilename.indexOf("?");
  19025. if (queryStringPosition === -1) {
  19026. queryStringPosition = sceneFilename.length;
  19027. }
  19028. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  19029. for (var index = 0; index < this._registeredPlugins.length; index++) {
  19030. var plugin = this._registeredPlugins[index];
  19031. if (plugin.extensions.indexOf(extension) !== -1) {
  19032. return plugin;
  19033. }
  19034. }
  19035. return this._registeredPlugins[this._registeredPlugins.length - 1];
  19036. };
  19037. // Public functions
  19038. SceneLoader.RegisterPlugin = function (plugin) {
  19039. plugin.extensions = plugin.extensions.toLowerCase();
  19040. SceneLoader._registeredPlugins.push(plugin);
  19041. };
  19042. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  19043. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  19044. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  19045. return;
  19046. }
  19047. var loadingToken = {};
  19048. scene._addPendingData(loadingToken);
  19049. var manifestChecked = function (success) {
  19050. scene.database = database;
  19051. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  19052. var importMeshFromData = function (data) {
  19053. var meshes = [];
  19054. var particleSystems = [];
  19055. var skeletons = [];
  19056. try {
  19057. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  19058. if (onerror) {
  19059. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  19060. }
  19061. scene._removePendingData(loadingToken);
  19062. return;
  19063. }
  19064. }
  19065. catch (e) {
  19066. if (onerror) {
  19067. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename + ' (Exception: ' + e + ')');
  19068. }
  19069. scene._removePendingData(loadingToken);
  19070. return;
  19071. }
  19072. if (onsuccess) {
  19073. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  19074. onsuccess(meshes, particleSystems, skeletons);
  19075. scene._removePendingData(loadingToken);
  19076. }
  19077. };
  19078. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  19079. // Direct load
  19080. importMeshFromData(sceneFilename.substr(5));
  19081. return;
  19082. }
  19083. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  19084. importMeshFromData(data);
  19085. }, progressCallBack, database);
  19086. };
  19087. if (scene.getEngine().enableOfflineSupport) {
  19088. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  19089. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  19090. }
  19091. else {
  19092. manifestChecked(true);
  19093. }
  19094. };
  19095. /**
  19096. * Load a scene
  19097. * @param rootUrl a string that defines the root url for scene and resources
  19098. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  19099. * @param engine is the instance of BABYLON.Engine to use to create the scene
  19100. */
  19101. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  19102. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  19103. };
  19104. /**
  19105. * Append a scene
  19106. * @param rootUrl a string that defines the root url for scene and resources
  19107. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  19108. * @param scene is the instance of BABYLON.Scene to append to
  19109. */
  19110. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  19111. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  19112. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  19113. return;
  19114. }
  19115. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  19116. var database;
  19117. var loadingToken = {};
  19118. scene._addPendingData(loadingToken);
  19119. if (SceneLoader.ShowLoadingScreen) {
  19120. scene.getEngine().displayLoadingUI();
  19121. }
  19122. var loadSceneFromData = function (data) {
  19123. scene.database = database;
  19124. if (!plugin.load(scene, data, rootUrl)) {
  19125. if (onerror) {
  19126. onerror(scene);
  19127. }
  19128. scene._removePendingData(loadingToken);
  19129. scene.getEngine().hideLoadingUI();
  19130. return;
  19131. }
  19132. if (onsuccess) {
  19133. onsuccess(scene);
  19134. }
  19135. scene._removePendingData(loadingToken);
  19136. if (SceneLoader.ShowLoadingScreen) {
  19137. scene.executeWhenReady(function () {
  19138. scene.getEngine().hideLoadingUI();
  19139. });
  19140. }
  19141. };
  19142. var manifestChecked = function (success) {
  19143. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  19144. };
  19145. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  19146. // Direct load
  19147. loadSceneFromData(sceneFilename.substr(5));
  19148. return;
  19149. }
  19150. if (rootUrl.indexOf("file:") === -1) {
  19151. if (scene.getEngine().enableOfflineSupport) {
  19152. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  19153. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  19154. }
  19155. else {
  19156. manifestChecked(true);
  19157. }
  19158. }
  19159. else {
  19160. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  19161. }
  19162. };
  19163. // Flags
  19164. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  19165. SceneLoader._ShowLoadingScreen = true;
  19166. // Members
  19167. SceneLoader._registeredPlugins = new Array();
  19168. return SceneLoader;
  19169. })();
  19170. BABYLON.SceneLoader = SceneLoader;
  19171. ;
  19172. })(BABYLON || (BABYLON = {}));
  19173. var BABYLON;
  19174. (function (BABYLON) {
  19175. var Internals;
  19176. (function (Internals) {
  19177. var checkColors4 = function (colors, count) {
  19178. // Check if color3 was used
  19179. if (colors.length === count * 3) {
  19180. var colors4 = [];
  19181. for (var index = 0; index < colors.length; index += 3) {
  19182. var newIndex = (index / 3) * 4;
  19183. colors4[newIndex] = colors[index];
  19184. colors4[newIndex + 1] = colors[index + 1];
  19185. colors4[newIndex + 2] = colors[index + 2];
  19186. colors4[newIndex + 3] = 1.0;
  19187. }
  19188. return colors4;
  19189. }
  19190. return colors;
  19191. };
  19192. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  19193. var texture = null;
  19194. if ((parsedTexture.name || parsedTexture.extensions) && !parsedTexture.isRenderTarget) {
  19195. texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  19196. texture.name = parsedTexture.name;
  19197. texture.hasAlpha = parsedTexture.hasAlpha;
  19198. texture.level = parsedTexture.level;
  19199. texture.coordinatesMode = parsedTexture.coordinatesMode;
  19200. }
  19201. return texture;
  19202. };
  19203. var loadTexture = function (rootUrl, parsedTexture, scene) {
  19204. if (parsedTexture.isCube) {
  19205. return loadCubeTexture(rootUrl, parsedTexture, scene);
  19206. }
  19207. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  19208. return null;
  19209. }
  19210. var texture;
  19211. if (parsedTexture.mirrorPlane) {
  19212. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19213. texture._waitingRenderList = parsedTexture.renderList;
  19214. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  19215. }
  19216. else if (parsedTexture.isRenderTarget) {
  19217. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19218. texture._waitingRenderList = parsedTexture.renderList;
  19219. }
  19220. else {
  19221. if (parsedTexture.base64String) {
  19222. texture = BABYLON.Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  19223. }
  19224. else {
  19225. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  19226. }
  19227. }
  19228. texture.name = parsedTexture.name;
  19229. texture.hasAlpha = parsedTexture.hasAlpha;
  19230. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  19231. texture.level = parsedTexture.level;
  19232. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  19233. texture.coordinatesMode = parsedTexture.coordinatesMode;
  19234. texture.uOffset = parsedTexture.uOffset;
  19235. texture.vOffset = parsedTexture.vOffset;
  19236. texture.uScale = parsedTexture.uScale;
  19237. texture.vScale = parsedTexture.vScale;
  19238. texture.uAng = parsedTexture.uAng;
  19239. texture.vAng = parsedTexture.vAng;
  19240. texture.wAng = parsedTexture.wAng;
  19241. texture.wrapU = parsedTexture.wrapU;
  19242. texture.wrapV = parsedTexture.wrapV;
  19243. // Animations
  19244. if (parsedTexture.animations) {
  19245. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  19246. var parsedAnimation = parsedTexture.animations[animationIndex];
  19247. texture.animations.push(parseAnimation(parsedAnimation));
  19248. }
  19249. }
  19250. return texture;
  19251. };
  19252. var parseSkeleton = function (parsedSkeleton, scene) {
  19253. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  19254. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  19255. var parsedBone = parsedSkeleton.bones[index];
  19256. var parentBone = null;
  19257. if (parsedBone.parentBoneIndex > -1) {
  19258. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  19259. }
  19260. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  19261. if (parsedBone.animation) {
  19262. bone.animations.push(parseAnimation(parsedBone.animation));
  19263. }
  19264. }
  19265. return skeleton;
  19266. };
  19267. var parseFresnelParameters = function (parsedFresnelParameters) {
  19268. var fresnelParameters = new BABYLON.FresnelParameters();
  19269. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  19270. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  19271. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  19272. fresnelParameters.bias = parsedFresnelParameters.bias;
  19273. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  19274. return fresnelParameters;
  19275. };
  19276. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  19277. var material;
  19278. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  19279. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  19280. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  19281. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  19282. material.specularPower = parsedMaterial.specularPower;
  19283. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  19284. material.useReflectionFresnelFromSpecular = parsedMaterial.useReflectionFresnelFromSpecular;
  19285. material.useEmissiveAsIllumination = parsedMaterial.useEmissiveAsIllumination;
  19286. material.alpha = parsedMaterial.alpha;
  19287. material.id = parsedMaterial.id;
  19288. if (parsedMaterial.disableDepthWrite) {
  19289. material.disableDepthWrite = parsedMaterial.disableDepthWrite;
  19290. }
  19291. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  19292. material.backFaceCulling = parsedMaterial.backFaceCulling;
  19293. material.wireframe = parsedMaterial.wireframe;
  19294. if (parsedMaterial.diffuseTexture) {
  19295. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  19296. }
  19297. if (parsedMaterial.diffuseFresnelParameters) {
  19298. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  19299. }
  19300. if (parsedMaterial.ambientTexture) {
  19301. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  19302. }
  19303. if (parsedMaterial.opacityTexture) {
  19304. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  19305. }
  19306. if (parsedMaterial.opacityFresnelParameters) {
  19307. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  19308. }
  19309. if (parsedMaterial.reflectionTexture) {
  19310. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  19311. }
  19312. if (parsedMaterial.reflectionFresnelParameters) {
  19313. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  19314. }
  19315. if (parsedMaterial.emissiveTexture) {
  19316. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  19317. }
  19318. if (parsedMaterial.lightmapTexture) {
  19319. material.lightmapTexture = loadTexture(rootUrl, parsedMaterial.lightmapTexture, scene);
  19320. material.lightmapThreshold = parsedMaterial.lightmapThreshold;
  19321. }
  19322. if (parsedMaterial.emissiveFresnelParameters) {
  19323. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  19324. }
  19325. if (parsedMaterial.specularTexture) {
  19326. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  19327. }
  19328. if (parsedMaterial.bumpTexture) {
  19329. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  19330. }
  19331. if (parsedMaterial.checkReadyOnlyOnce) {
  19332. material.checkReadyOnlyOnce = parsedMaterial.checkReadyOnlyOnce;
  19333. }
  19334. return material;
  19335. };
  19336. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  19337. for (var index = 0; index < parsedData.materials.length; index++) {
  19338. var parsedMaterial = parsedData.materials[index];
  19339. if (parsedMaterial.id === id) {
  19340. return parseMaterial(parsedMaterial, scene, rootUrl);
  19341. }
  19342. }
  19343. return null;
  19344. };
  19345. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  19346. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  19347. multiMaterial.id = parsedMultiMaterial.id;
  19348. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  19349. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  19350. var subMatId = parsedMultiMaterial.materials[matIndex];
  19351. if (subMatId) {
  19352. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  19353. }
  19354. else {
  19355. multiMaterial.subMaterials.push(null);
  19356. }
  19357. }
  19358. return multiMaterial;
  19359. };
  19360. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  19361. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  19362. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  19363. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  19364. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  19365. var parsedFlare = parsedLensFlareSystem.flares[index];
  19366. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  19367. }
  19368. return lensFlareSystem;
  19369. };
  19370. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  19371. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  19372. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  19373. if (parsedParticleSystem.textureName) {
  19374. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  19375. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  19376. }
  19377. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  19378. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  19379. particleSystem.minSize = parsedParticleSystem.minSize;
  19380. particleSystem.maxSize = parsedParticleSystem.maxSize;
  19381. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  19382. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  19383. particleSystem.emitter = emitter;
  19384. particleSystem.emitRate = parsedParticleSystem.emitRate;
  19385. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  19386. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  19387. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  19388. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  19389. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  19390. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  19391. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  19392. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  19393. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  19394. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  19395. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  19396. particleSystem.blendMode = parsedParticleSystem.blendMode;
  19397. particleSystem.start();
  19398. return particleSystem;
  19399. };
  19400. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  19401. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  19402. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  19403. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  19404. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  19405. shadowGenerator.getShadowMap().renderList.push(mesh);
  19406. }
  19407. if (parsedShadowGenerator.usePoissonSampling) {
  19408. shadowGenerator.usePoissonSampling = true;
  19409. }
  19410. else if (parsedShadowGenerator.useVarianceShadowMap) {
  19411. shadowGenerator.useVarianceShadowMap = true;
  19412. }
  19413. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  19414. shadowGenerator.useBlurVarianceShadowMap = true;
  19415. if (parsedShadowGenerator.blurScale) {
  19416. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  19417. }
  19418. if (parsedShadowGenerator.blurBoxOffset) {
  19419. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  19420. }
  19421. }
  19422. if (parsedShadowGenerator.bias !== undefined) {
  19423. shadowGenerator.bias = parsedShadowGenerator.bias;
  19424. }
  19425. return shadowGenerator;
  19426. };
  19427. var parseAnimation = function (parsedAnimation) {
  19428. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  19429. var dataType = parsedAnimation.dataType;
  19430. var keys = [];
  19431. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  19432. var key = parsedAnimation.keys[index];
  19433. var data;
  19434. switch (dataType) {
  19435. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  19436. data = key.values[0];
  19437. break;
  19438. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  19439. data = BABYLON.Quaternion.FromArray(key.values);
  19440. break;
  19441. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  19442. data = BABYLON.Matrix.FromArray(key.values);
  19443. break;
  19444. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  19445. default:
  19446. data = BABYLON.Vector3.FromArray(key.values);
  19447. break;
  19448. }
  19449. keys.push({
  19450. frame: key.frame,
  19451. value: data
  19452. });
  19453. }
  19454. animation.setKeys(keys);
  19455. return animation;
  19456. };
  19457. var parseLight = function (parsedLight, scene) {
  19458. var light;
  19459. switch (parsedLight.type) {
  19460. case 0:
  19461. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  19462. break;
  19463. case 1:
  19464. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  19465. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  19466. break;
  19467. case 2:
  19468. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  19469. break;
  19470. case 3:
  19471. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  19472. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  19473. break;
  19474. }
  19475. light.id = parsedLight.id;
  19476. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  19477. if (parsedLight.intensity !== undefined) {
  19478. light.intensity = parsedLight.intensity;
  19479. }
  19480. if (parsedLight.range) {
  19481. light.range = parsedLight.range;
  19482. }
  19483. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  19484. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  19485. if (parsedLight.excludedMeshesIds) {
  19486. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19487. }
  19488. // Parent
  19489. if (parsedLight.parentId) {
  19490. light._waitingParentId = parsedLight.parentId;
  19491. }
  19492. if (parsedLight.includedOnlyMeshesIds) {
  19493. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19494. }
  19495. // Animations
  19496. if (parsedLight.animations) {
  19497. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19498. var parsedAnimation = parsedLight.animations[animationIndex];
  19499. light.animations.push(parseAnimation(parsedAnimation));
  19500. }
  19501. }
  19502. if (parsedLight.autoAnimate) {
  19503. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  19504. }
  19505. };
  19506. var parseCamera = function (parsedCamera, scene) {
  19507. var camera;
  19508. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  19509. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  19510. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  19511. var alpha = parsedCamera.alpha;
  19512. var beta = parsedCamera.beta;
  19513. var radius = parsedCamera.radius;
  19514. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  19515. var interaxial_distance = parsedCamera.interaxial_distance;
  19516. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, interaxial_distance, scene);
  19517. }
  19518. else {
  19519. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  19520. }
  19521. }
  19522. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  19523. interaxial_distance = parsedCamera.interaxial_distance;
  19524. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, interaxial_distance, scene);
  19525. }
  19526. else if (parsedCamera.type === "DeviceOrientationCamera") {
  19527. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  19528. }
  19529. else if (parsedCamera.type === "FollowCamera") {
  19530. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  19531. camera.heightOffset = parsedCamera.heightOffset;
  19532. camera.radius = parsedCamera.radius;
  19533. camera.rotationOffset = parsedCamera.rotationOffset;
  19534. if (lockedTargetMesh)
  19535. camera.target = lockedTargetMesh;
  19536. }
  19537. else if (parsedCamera.type === "GamepadCamera") {
  19538. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  19539. }
  19540. else if (parsedCamera.type === "TouchCamera") {
  19541. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  19542. }
  19543. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  19544. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  19545. }
  19546. else if (parsedCamera.type === "WebVRFreeCamera") {
  19547. camera = new BABYLON.WebVRFreeCamera(parsedCamera.name, position, scene);
  19548. }
  19549. else if (parsedCamera.type === "VRDeviceOrientationFreeCamera") {
  19550. camera = new BABYLON.VRDeviceOrientationFreeCamera(parsedCamera.name, position, scene);
  19551. }
  19552. else {
  19553. // Free Camera is the default value
  19554. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  19555. }
  19556. // apply 3d rig, when found
  19557. if (parsedCamera.cameraRigMode) {
  19558. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  19559. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  19560. }
  19561. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  19562. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  19563. camera.lockedTarget = lockedTargetMesh;
  19564. }
  19565. camera.id = parsedCamera.id;
  19566. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  19567. // Parent
  19568. if (parsedCamera.parentId) {
  19569. camera._waitingParentId = parsedCamera.parentId;
  19570. }
  19571. // Target
  19572. if (parsedCamera.target) {
  19573. if (camera.setTarget) {
  19574. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  19575. }
  19576. else {
  19577. //For ArcRotate
  19578. camera.target = BABYLON.Vector3.FromArray(parsedCamera.target);
  19579. }
  19580. }
  19581. else {
  19582. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  19583. }
  19584. camera.fov = parsedCamera.fov;
  19585. camera.minZ = parsedCamera.minZ;
  19586. camera.maxZ = parsedCamera.maxZ;
  19587. camera.speed = parsedCamera.speed;
  19588. camera.inertia = parsedCamera.inertia;
  19589. camera.checkCollisions = parsedCamera.checkCollisions;
  19590. camera.applyGravity = parsedCamera.applyGravity;
  19591. if (parsedCamera.ellipsoid) {
  19592. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  19593. }
  19594. // Animations
  19595. if (parsedCamera.animations) {
  19596. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  19597. var parsedAnimation = parsedCamera.animations[animationIndex];
  19598. camera.animations.push(parseAnimation(parsedAnimation));
  19599. }
  19600. }
  19601. if (parsedCamera.autoAnimate) {
  19602. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  19603. }
  19604. // Layer Mask
  19605. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  19606. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  19607. }
  19608. else {
  19609. camera.layerMask = 0x0FFFFFFF;
  19610. }
  19611. return camera;
  19612. };
  19613. var parseGeometry = function (parsedGeometry, scene) {
  19614. var id = parsedGeometry.id;
  19615. return scene.getGeometryByID(id);
  19616. };
  19617. var parseBox = function (parsedBox, scene) {
  19618. if (parseGeometry(parsedBox, scene)) {
  19619. return null; // null since geometry could be something else than a box...
  19620. }
  19621. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  19622. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  19623. scene.pushGeometry(box, true);
  19624. return box;
  19625. };
  19626. var parseSphere = function (parsedSphere, scene) {
  19627. if (parseGeometry(parsedSphere, scene)) {
  19628. return null; // null since geometry could be something else than a sphere...
  19629. }
  19630. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  19631. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  19632. scene.pushGeometry(sphere, true);
  19633. return sphere;
  19634. };
  19635. var parseCylinder = function (parsedCylinder, scene) {
  19636. if (parseGeometry(parsedCylinder, scene)) {
  19637. return null; // null since geometry could be something else than a cylinder...
  19638. }
  19639. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  19640. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  19641. scene.pushGeometry(cylinder, true);
  19642. return cylinder;
  19643. };
  19644. var parseTorus = function (parsedTorus, scene) {
  19645. if (parseGeometry(parsedTorus, scene)) {
  19646. return null; // null since geometry could be something else than a torus...
  19647. }
  19648. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  19649. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  19650. scene.pushGeometry(torus, true);
  19651. return torus;
  19652. };
  19653. var parseGround = function (parsedGround, scene) {
  19654. if (parseGeometry(parsedGround, scene)) {
  19655. return null; // null since geometry could be something else than a ground...
  19656. }
  19657. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  19658. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  19659. scene.pushGeometry(ground, true);
  19660. return ground;
  19661. };
  19662. var parsePlane = function (parsedPlane, scene) {
  19663. if (parseGeometry(parsedPlane, scene)) {
  19664. return null; // null since geometry could be something else than a plane...
  19665. }
  19666. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  19667. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  19668. scene.pushGeometry(plane, true);
  19669. return plane;
  19670. };
  19671. var parseTorusKnot = function (parsedTorusKnot, scene) {
  19672. if (parseGeometry(parsedTorusKnot, scene)) {
  19673. return null; // null since geometry could be something else than a torusKnot...
  19674. }
  19675. 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);
  19676. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  19677. scene.pushGeometry(torusKnot, true);
  19678. return torusKnot;
  19679. };
  19680. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  19681. if (parseGeometry(parsedVertexData, scene)) {
  19682. return null; // null since geometry could be a primitive
  19683. }
  19684. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  19685. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  19686. if (parsedVertexData.delayLoadingFile) {
  19687. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19688. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  19689. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  19690. geometry._delayInfo = [];
  19691. if (parsedVertexData.hasUVs) {
  19692. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  19693. }
  19694. if (parsedVertexData.hasUVs2) {
  19695. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  19696. }
  19697. if (parsedVertexData.hasUVs3) {
  19698. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  19699. }
  19700. if (parsedVertexData.hasUVs4) {
  19701. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  19702. }
  19703. if (parsedVertexData.hasUVs5) {
  19704. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  19705. }
  19706. if (parsedVertexData.hasUVs6) {
  19707. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  19708. }
  19709. if (parsedVertexData.hasColors) {
  19710. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  19711. }
  19712. if (parsedVertexData.hasMatricesIndices) {
  19713. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19714. }
  19715. if (parsedVertexData.hasMatricesWeights) {
  19716. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19717. }
  19718. geometry._delayLoadingFunction = importVertexData;
  19719. }
  19720. else {
  19721. importVertexData(parsedVertexData, geometry);
  19722. }
  19723. scene.pushGeometry(geometry, true);
  19724. return geometry;
  19725. };
  19726. var parseMesh = function (parsedMesh, scene, rootUrl) {
  19727. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  19728. mesh.id = parsedMesh.id;
  19729. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  19730. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  19731. if (parsedMesh.rotationQuaternion) {
  19732. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  19733. }
  19734. else if (parsedMesh.rotation) {
  19735. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  19736. }
  19737. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  19738. if (parsedMesh.localMatrix) {
  19739. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  19740. }
  19741. else if (parsedMesh.pivotMatrix) {
  19742. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  19743. }
  19744. mesh.setEnabled(parsedMesh.isEnabled);
  19745. mesh.isVisible = parsedMesh.isVisible;
  19746. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  19747. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  19748. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  19749. if (parsedMesh.applyFog !== undefined) {
  19750. mesh.applyFog = parsedMesh.applyFog;
  19751. }
  19752. if (parsedMesh.pickable !== undefined) {
  19753. mesh.isPickable = parsedMesh.pickable;
  19754. }
  19755. if (parsedMesh.alphaIndex !== undefined) {
  19756. mesh.alphaIndex = parsedMesh.alphaIndex;
  19757. }
  19758. mesh.receiveShadows = parsedMesh.receiveShadows;
  19759. mesh.billboardMode = parsedMesh.billboardMode;
  19760. if (parsedMesh.visibility !== undefined) {
  19761. mesh.visibility = parsedMesh.visibility;
  19762. }
  19763. mesh.checkCollisions = parsedMesh.checkCollisions;
  19764. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  19765. // freezeWorldMatrix
  19766. if (parsedMesh.freezeWorldMatrix) {
  19767. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  19768. }
  19769. // Parent
  19770. if (parsedMesh.parentId) {
  19771. mesh._waitingParentId = parsedMesh.parentId;
  19772. }
  19773. // Actions
  19774. if (parsedMesh.actions !== undefined) {
  19775. mesh._waitingActions = parsedMesh.actions;
  19776. }
  19777. // Geometry
  19778. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  19779. if (parsedMesh.delayLoadingFile) {
  19780. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19781. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  19782. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  19783. if (parsedMesh._binaryInfo) {
  19784. mesh._binaryInfo = parsedMesh._binaryInfo;
  19785. }
  19786. mesh._delayInfo = [];
  19787. if (parsedMesh.hasUVs) {
  19788. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  19789. }
  19790. if (parsedMesh.hasUVs2) {
  19791. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  19792. }
  19793. if (parsedMesh.hasUVs3) {
  19794. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  19795. }
  19796. if (parsedMesh.hasUVs4) {
  19797. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  19798. }
  19799. if (parsedMesh.hasUVs5) {
  19800. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  19801. }
  19802. if (parsedMesh.hasUVs6) {
  19803. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  19804. }
  19805. if (parsedMesh.hasColors) {
  19806. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  19807. }
  19808. if (parsedMesh.hasMatricesIndices) {
  19809. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19810. }
  19811. if (parsedMesh.hasMatricesWeights) {
  19812. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19813. }
  19814. mesh._delayLoadingFunction = importGeometry;
  19815. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  19816. mesh._checkDelayState();
  19817. }
  19818. }
  19819. else {
  19820. importGeometry(parsedMesh, mesh);
  19821. }
  19822. // Material
  19823. if (parsedMesh.materialId) {
  19824. mesh.setMaterialByID(parsedMesh.materialId);
  19825. }
  19826. else {
  19827. mesh.material = null;
  19828. }
  19829. // Skeleton
  19830. if (parsedMesh.skeletonId > -1) {
  19831. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  19832. }
  19833. // Physics
  19834. if (parsedMesh.physicsImpostor) {
  19835. if (!scene.isPhysicsEnabled()) {
  19836. scene.enablePhysics();
  19837. }
  19838. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  19839. }
  19840. // Animations
  19841. if (parsedMesh.animations) {
  19842. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  19843. var parsedAnimation = parsedMesh.animations[animationIndex];
  19844. mesh.animations.push(parseAnimation(parsedAnimation));
  19845. }
  19846. }
  19847. if (parsedMesh.autoAnimate) {
  19848. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  19849. }
  19850. // Layer Mask
  19851. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  19852. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  19853. }
  19854. else {
  19855. mesh.layerMask = 0x0FFFFFFF;
  19856. }
  19857. // Instances
  19858. if (parsedMesh.instances) {
  19859. for (var index = 0; index < parsedMesh.instances.length; index++) {
  19860. var parsedInstance = parsedMesh.instances[index];
  19861. var instance = mesh.createInstance(parsedInstance.name);
  19862. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  19863. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  19864. if (parsedInstance.rotationQuaternion) {
  19865. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  19866. }
  19867. else if (parsedInstance.rotation) {
  19868. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  19869. }
  19870. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  19871. instance.checkCollisions = mesh.checkCollisions;
  19872. if (parsedMesh.animations) {
  19873. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  19874. parsedAnimation = parsedMesh.animations[animationIndex];
  19875. instance.animations.push(parseAnimation(parsedAnimation));
  19876. }
  19877. }
  19878. }
  19879. }
  19880. return mesh;
  19881. };
  19882. var parseActions = function (parsedActions, object, scene) {
  19883. var actionManager = new BABYLON.ActionManager(scene);
  19884. if (object === null)
  19885. scene.actionManager = actionManager;
  19886. else
  19887. object.actionManager = actionManager;
  19888. // instanciate a new object
  19889. var instanciate = function (name, params) {
  19890. var newInstance = Object.create(BABYLON[name].prototype);
  19891. newInstance.constructor.apply(newInstance, params);
  19892. return newInstance;
  19893. };
  19894. var parseParameter = function (name, value, target, propertyPath) {
  19895. if (propertyPath === null) {
  19896. // String, boolean or float
  19897. var floatValue = parseFloat(value);
  19898. if (value === "true" || value === "false")
  19899. return value === "true";
  19900. else
  19901. return isNaN(floatValue) ? value : floatValue;
  19902. }
  19903. var effectiveTarget = propertyPath.split(".");
  19904. var values = value.split(",");
  19905. // Get effective Target
  19906. for (var i = 0; i < effectiveTarget.length; i++) {
  19907. target = target[effectiveTarget[i]];
  19908. }
  19909. // Return appropriate value with its type
  19910. if (typeof (target) === "boolean")
  19911. return values[0] === "true";
  19912. if (typeof (target) === "string")
  19913. return values[0];
  19914. // Parameters with multiple values such as Vector3 etc.
  19915. var split = new Array();
  19916. for (var i = 0; i < values.length; i++)
  19917. split.push(parseFloat(values[i]));
  19918. if (target instanceof BABYLON.Vector3)
  19919. return BABYLON.Vector3.FromArray(split);
  19920. if (target instanceof BABYLON.Vector4)
  19921. return BABYLON.Vector4.FromArray(split);
  19922. if (target instanceof BABYLON.Color3)
  19923. return BABYLON.Color3.FromArray(split);
  19924. if (target instanceof BABYLON.Color4)
  19925. return BABYLON.Color4.FromArray(split);
  19926. return parseFloat(values[0]);
  19927. };
  19928. // traverse graph per trigger
  19929. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  19930. if (combineArray === void 0) { combineArray = null; }
  19931. if (parsedAction.detached)
  19932. return;
  19933. var parameters = new Array();
  19934. var target = null;
  19935. var propertyPath = null;
  19936. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  19937. // Parameters
  19938. if (parsedAction.type === 2)
  19939. parameters.push(actionManager);
  19940. else
  19941. parameters.push(trigger);
  19942. if (combine) {
  19943. var actions = new Array();
  19944. for (var j = 0; j < parsedAction.combine.length; j++) {
  19945. traverse(parsedAction.combine[j], BABYLON.ActionManager.NothingTrigger, condition, action, actions);
  19946. }
  19947. parameters.push(actions);
  19948. }
  19949. else {
  19950. for (var i = 0; i < parsedAction.properties.length; i++) {
  19951. var value = parsedAction.properties[i].value;
  19952. var name = parsedAction.properties[i].name;
  19953. var targetType = parsedAction.properties[i].targetType;
  19954. if (name === "target")
  19955. if (targetType !== null && targetType === "SceneProperties")
  19956. value = target = scene;
  19957. else
  19958. value = target = scene.getNodeByName(value);
  19959. else if (name === "parent")
  19960. value = scene.getNodeByName(value);
  19961. else if (name === "sound")
  19962. value = scene.getSoundByName(value);
  19963. else if (name !== "propertyPath") {
  19964. if (parsedAction.type === 2 && name === "operator")
  19965. value = BABYLON.ValueCondition[value];
  19966. else
  19967. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  19968. }
  19969. else {
  19970. propertyPath = value;
  19971. }
  19972. parameters.push(value);
  19973. }
  19974. }
  19975. if (combineArray === null) {
  19976. parameters.push(condition);
  19977. }
  19978. else {
  19979. parameters.push(null);
  19980. }
  19981. // If interpolate value action
  19982. if (parsedAction.name === "InterpolateValueAction") {
  19983. var param = parameters[parameters.length - 2];
  19984. parameters[parameters.length - 1] = param;
  19985. parameters[parameters.length - 2] = condition;
  19986. }
  19987. // Action or condition(s) and not CombineAction
  19988. var newAction = instanciate(parsedAction.name, parameters);
  19989. if (newAction instanceof BABYLON.Condition && condition !== null) {
  19990. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  19991. if (action)
  19992. action.then(nothing);
  19993. else
  19994. actionManager.registerAction(nothing);
  19995. action = nothing;
  19996. }
  19997. if (combineArray === null) {
  19998. if (newAction instanceof BABYLON.Condition) {
  19999. condition = newAction;
  20000. newAction = action;
  20001. }
  20002. else {
  20003. condition = null;
  20004. if (action)
  20005. action.then(newAction);
  20006. else
  20007. actionManager.registerAction(newAction);
  20008. }
  20009. }
  20010. else {
  20011. combineArray.push(newAction);
  20012. }
  20013. for (var i = 0; i < parsedAction.children.length; i++)
  20014. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  20015. };
  20016. // triggers
  20017. for (var i = 0; i < parsedActions.children.length; i++) {
  20018. var triggerParams;
  20019. var trigger = parsedActions.children[i];
  20020. if (trigger.properties.length > 0) {
  20021. var param = trigger.properties[0].value;
  20022. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  20023. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  20024. }
  20025. else
  20026. triggerParams = BABYLON.ActionManager[trigger.name];
  20027. for (var j = 0; j < trigger.children.length; j++) {
  20028. if (!trigger.detached)
  20029. traverse(trigger.children[j], triggerParams, null, null);
  20030. }
  20031. }
  20032. };
  20033. var parseSound = function (parsedSound, scene, rootUrl) {
  20034. var soundName = parsedSound.name;
  20035. var soundUrl = rootUrl + soundName;
  20036. var options = {
  20037. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  20038. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  20039. rolloffFactor: parsedSound.rolloffFactor,
  20040. refDistance: parsedSound.refDistance,
  20041. distanceModel: parsedSound.distanceModel,
  20042. playbackRate: parsedSound.playbackRate
  20043. };
  20044. var newSound = new BABYLON.Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  20045. scene._addPendingData(newSound);
  20046. if (parsedSound.position) {
  20047. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  20048. newSound.setPosition(soundPosition);
  20049. }
  20050. if (parsedSound.isDirectional) {
  20051. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  20052. if (parsedSound.localDirectionToMesh) {
  20053. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  20054. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  20055. }
  20056. }
  20057. if (parsedSound.connectedMeshId) {
  20058. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  20059. if (connectedMesh) {
  20060. newSound.attachToMesh(connectedMesh);
  20061. }
  20062. }
  20063. };
  20064. var isDescendantOf = function (mesh, names, hierarchyIds) {
  20065. names = (names instanceof Array) ? names : [names];
  20066. for (var i in names) {
  20067. if (mesh.name === names[i]) {
  20068. hierarchyIds.push(mesh.id);
  20069. return true;
  20070. }
  20071. }
  20072. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  20073. hierarchyIds.push(mesh.id);
  20074. return true;
  20075. }
  20076. return false;
  20077. };
  20078. var importVertexData = function (parsedVertexData, geometry) {
  20079. var vertexData = new BABYLON.VertexData();
  20080. // positions
  20081. var positions = parsedVertexData.positions;
  20082. if (positions) {
  20083. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  20084. }
  20085. // normals
  20086. var normals = parsedVertexData.normals;
  20087. if (normals) {
  20088. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  20089. }
  20090. // uvs
  20091. var uvs = parsedVertexData.uvs;
  20092. if (uvs) {
  20093. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  20094. }
  20095. // uv2s
  20096. var uv2s = parsedVertexData.uv2s;
  20097. if (uv2s) {
  20098. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  20099. }
  20100. // uv3s
  20101. var uv3s = parsedVertexData.uv3s;
  20102. if (uv3s) {
  20103. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  20104. }
  20105. // uv4s
  20106. var uv4s = parsedVertexData.uv4s;
  20107. if (uv4s) {
  20108. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  20109. }
  20110. // uv5s
  20111. var uv5s = parsedVertexData.uv5s;
  20112. if (uv5s) {
  20113. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  20114. }
  20115. // uv6s
  20116. var uv6s = parsedVertexData.uv6s;
  20117. if (uv6s) {
  20118. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  20119. }
  20120. // colors
  20121. var colors = parsedVertexData.colors;
  20122. if (colors) {
  20123. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  20124. }
  20125. // matricesIndices
  20126. var matricesIndices = parsedVertexData.matricesIndices;
  20127. if (matricesIndices) {
  20128. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  20129. }
  20130. // matricesWeights
  20131. var matricesWeights = parsedVertexData.matricesWeights;
  20132. if (matricesWeights) {
  20133. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  20134. }
  20135. // indices
  20136. var indices = parsedVertexData.indices;
  20137. if (indices) {
  20138. vertexData.indices = indices;
  20139. }
  20140. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  20141. };
  20142. var importGeometry = function (parsedGeometry, mesh) {
  20143. var scene = mesh.getScene();
  20144. // Geometry
  20145. var geometryId = parsedGeometry.geometryId;
  20146. if (geometryId) {
  20147. var geometry = scene.getGeometryByID(geometryId);
  20148. if (geometry) {
  20149. geometry.applyToMesh(mesh);
  20150. }
  20151. }
  20152. else if (parsedGeometry instanceof ArrayBuffer) {
  20153. var binaryInfo = mesh._binaryInfo;
  20154. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  20155. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  20156. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  20157. }
  20158. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  20159. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  20160. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  20161. }
  20162. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  20163. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  20164. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  20165. }
  20166. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  20167. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  20168. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  20169. }
  20170. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  20171. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  20172. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  20173. }
  20174. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  20175. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  20176. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  20177. }
  20178. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  20179. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  20180. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  20181. }
  20182. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  20183. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  20184. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  20185. }
  20186. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  20187. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  20188. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  20189. }
  20190. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  20191. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  20192. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  20193. }
  20194. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  20195. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  20196. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  20197. }
  20198. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  20199. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  20200. mesh.setIndices(indicesData);
  20201. }
  20202. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  20203. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  20204. mesh.subMeshes = [];
  20205. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  20206. var materialIndex = subMeshesData[(i * 5) + 0];
  20207. var verticesStart = subMeshesData[(i * 5) + 1];
  20208. var verticesCount = subMeshesData[(i * 5) + 2];
  20209. var indexStart = subMeshesData[(i * 5) + 3];
  20210. var indexCount = subMeshesData[(i * 5) + 4];
  20211. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  20212. }
  20213. }
  20214. }
  20215. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  20216. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  20217. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  20218. if (parsedGeometry.uvs) {
  20219. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  20220. }
  20221. if (parsedGeometry.uvs2) {
  20222. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  20223. }
  20224. if (parsedGeometry.uvs3) {
  20225. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  20226. }
  20227. if (parsedGeometry.uvs4) {
  20228. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  20229. }
  20230. if (parsedGeometry.uvs5) {
  20231. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  20232. }
  20233. if (parsedGeometry.uvs6) {
  20234. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  20235. }
  20236. if (parsedGeometry.colors) {
  20237. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  20238. }
  20239. if (parsedGeometry.matricesIndices) {
  20240. if (!parsedGeometry.matricesIndices._isExpanded) {
  20241. var floatIndices = [];
  20242. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  20243. var matricesIndex = parsedGeometry.matricesIndices[i];
  20244. floatIndices.push(matricesIndex & 0x000000FF);
  20245. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  20246. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  20247. floatIndices.push(matricesIndex >> 24);
  20248. }
  20249. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  20250. }
  20251. else {
  20252. delete parsedGeometry.matricesIndices._isExpanded;
  20253. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  20254. }
  20255. }
  20256. if (parsedGeometry.matricesWeights) {
  20257. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  20258. }
  20259. mesh.setIndices(parsedGeometry.indices);
  20260. }
  20261. // SubMeshes
  20262. if (parsedGeometry.subMeshes) {
  20263. mesh.subMeshes = [];
  20264. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  20265. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  20266. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  20267. }
  20268. }
  20269. // Flat shading
  20270. if (mesh._shouldGenerateFlatShading) {
  20271. mesh.convertToFlatShadedMesh();
  20272. delete mesh._shouldGenerateFlatShading;
  20273. }
  20274. // Update
  20275. mesh.computeWorldMatrix(true);
  20276. // Octree
  20277. if (scene._selectionOctree) {
  20278. scene._selectionOctree.addMesh(mesh);
  20279. }
  20280. };
  20281. BABYLON.SceneLoader.RegisterPlugin({
  20282. extensions: ".babylon",
  20283. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  20284. var parsedData = JSON.parse(data);
  20285. var loadedSkeletonsIds = [];
  20286. var loadedMaterialsIds = [];
  20287. var hierarchyIds = [];
  20288. for (var index = 0; index < parsedData.meshes.length; index++) {
  20289. var parsedMesh = parsedData.meshes[index];
  20290. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  20291. if (meshesNames instanceof Array) {
  20292. // Remove found mesh name from list.
  20293. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  20294. }
  20295. //Geometry?
  20296. if (parsedMesh.geometryId) {
  20297. //does the file contain geometries?
  20298. if (parsedData.geometries) {
  20299. //find the correct geometry and add it to the scene
  20300. var found = false;
  20301. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  20302. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  20303. return;
  20304. }
  20305. else {
  20306. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  20307. if (parsedGeometryData.id == parsedMesh.geometryId) {
  20308. switch (geometryType) {
  20309. case "boxes":
  20310. parseBox(parsedGeometryData, scene);
  20311. break;
  20312. case "spheres":
  20313. parseSphere(parsedGeometryData, scene);
  20314. break;
  20315. case "cylinders":
  20316. parseCylinder(parsedGeometryData, scene);
  20317. break;
  20318. case "toruses":
  20319. parseTorus(parsedGeometryData, scene);
  20320. break;
  20321. case "grounds":
  20322. parseGround(parsedGeometryData, scene);
  20323. break;
  20324. case "planes":
  20325. parsePlane(parsedGeometryData, scene);
  20326. break;
  20327. case "torusKnots":
  20328. parseTorusKnot(parsedGeometryData, scene);
  20329. break;
  20330. case "vertexData":
  20331. parseVertexData(parsedGeometryData, scene, rootUrl);
  20332. break;
  20333. }
  20334. found = true;
  20335. }
  20336. });
  20337. }
  20338. });
  20339. if (!found) {
  20340. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  20341. }
  20342. }
  20343. }
  20344. // Material ?
  20345. if (parsedMesh.materialId) {
  20346. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  20347. if (!materialFound && parsedData.multiMaterials) {
  20348. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  20349. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  20350. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  20351. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  20352. var subMatId = parsedMultiMaterial.materials[matIndex];
  20353. loadedMaterialsIds.push(subMatId);
  20354. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  20355. }
  20356. loadedMaterialsIds.push(parsedMultiMaterial.id);
  20357. parseMultiMaterial(parsedMultiMaterial, scene);
  20358. materialFound = true;
  20359. break;
  20360. }
  20361. }
  20362. }
  20363. if (!materialFound) {
  20364. loadedMaterialsIds.push(parsedMesh.materialId);
  20365. if (!parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl)) {
  20366. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  20367. }
  20368. }
  20369. }
  20370. // Skeleton ?
  20371. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  20372. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  20373. if (!skeletonAlreadyLoaded) {
  20374. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  20375. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  20376. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  20377. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  20378. loadedSkeletonsIds.push(parsedSkeleton.id);
  20379. }
  20380. }
  20381. }
  20382. }
  20383. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  20384. meshes.push(mesh);
  20385. }
  20386. }
  20387. // Connecting parents
  20388. for (index = 0; index < scene.meshes.length; index++) {
  20389. var currentMesh = scene.meshes[index];
  20390. if (currentMesh._waitingParentId) {
  20391. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  20392. currentMesh._waitingParentId = undefined;
  20393. }
  20394. }
  20395. // freeze world matrix application
  20396. for (index = 0; index < scene.meshes.length; index++) {
  20397. var currentMesh = scene.meshes[index];
  20398. if (currentMesh._waitingFreezeWorldMatrix) {
  20399. currentMesh.freezeWorldMatrix();
  20400. currentMesh._waitingFreezeWorldMatrix = undefined;
  20401. }
  20402. }
  20403. // Particles
  20404. if (parsedData.particleSystems) {
  20405. for (index = 0; index < parsedData.particleSystems.length; index++) {
  20406. var parsedParticleSystem = parsedData.particleSystems[index];
  20407. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  20408. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  20409. }
  20410. }
  20411. }
  20412. return true;
  20413. },
  20414. load: function (scene, data, rootUrl) {
  20415. var parsedData = JSON.parse(data);
  20416. // Scene
  20417. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  20418. scene.autoClear = parsedData.autoClear;
  20419. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  20420. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  20421. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  20422. // Fog
  20423. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  20424. scene.fogMode = parsedData.fogMode;
  20425. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  20426. scene.fogStart = parsedData.fogStart;
  20427. scene.fogEnd = parsedData.fogEnd;
  20428. scene.fogDensity = parsedData.fogDensity;
  20429. }
  20430. // Lights
  20431. for (var index = 0; index < parsedData.lights.length; index++) {
  20432. var parsedLight = parsedData.lights[index];
  20433. parseLight(parsedLight, scene);
  20434. }
  20435. // Materials
  20436. if (parsedData.materials) {
  20437. for (index = 0; index < parsedData.materials.length; index++) {
  20438. var parsedMaterial = parsedData.materials[index];
  20439. parseMaterial(parsedMaterial, scene, rootUrl);
  20440. }
  20441. }
  20442. if (parsedData.multiMaterials) {
  20443. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  20444. var parsedMultiMaterial = parsedData.multiMaterials[index];
  20445. parseMultiMaterial(parsedMultiMaterial, scene);
  20446. }
  20447. }
  20448. // Skeletons
  20449. if (parsedData.skeletons) {
  20450. for (index = 0; index < parsedData.skeletons.length; index++) {
  20451. var parsedSkeleton = parsedData.skeletons[index];
  20452. parseSkeleton(parsedSkeleton, scene);
  20453. }
  20454. }
  20455. // Geometries
  20456. var geometries = parsedData.geometries;
  20457. if (geometries) {
  20458. // Boxes
  20459. var boxes = geometries.boxes;
  20460. if (boxes) {
  20461. for (index = 0; index < boxes.length; index++) {
  20462. var parsedBox = boxes[index];
  20463. parseBox(parsedBox, scene);
  20464. }
  20465. }
  20466. // Spheres
  20467. var spheres = geometries.spheres;
  20468. if (spheres) {
  20469. for (index = 0; index < spheres.length; index++) {
  20470. var parsedSphere = spheres[index];
  20471. parseSphere(parsedSphere, scene);
  20472. }
  20473. }
  20474. // Cylinders
  20475. var cylinders = geometries.cylinders;
  20476. if (cylinders) {
  20477. for (index = 0; index < cylinders.length; index++) {
  20478. var parsedCylinder = cylinders[index];
  20479. parseCylinder(parsedCylinder, scene);
  20480. }
  20481. }
  20482. // Toruses
  20483. var toruses = geometries.toruses;
  20484. if (toruses) {
  20485. for (index = 0; index < toruses.length; index++) {
  20486. var parsedTorus = toruses[index];
  20487. parseTorus(parsedTorus, scene);
  20488. }
  20489. }
  20490. // Grounds
  20491. var grounds = geometries.grounds;
  20492. if (grounds) {
  20493. for (index = 0; index < grounds.length; index++) {
  20494. var parsedGround = grounds[index];
  20495. parseGround(parsedGround, scene);
  20496. }
  20497. }
  20498. // Planes
  20499. var planes = geometries.planes;
  20500. if (planes) {
  20501. for (index = 0; index < planes.length; index++) {
  20502. var parsedPlane = planes[index];
  20503. parsePlane(parsedPlane, scene);
  20504. }
  20505. }
  20506. // TorusKnots
  20507. var torusKnots = geometries.torusKnots;
  20508. if (torusKnots) {
  20509. for (index = 0; index < torusKnots.length; index++) {
  20510. var parsedTorusKnot = torusKnots[index];
  20511. parseTorusKnot(parsedTorusKnot, scene);
  20512. }
  20513. }
  20514. // VertexData
  20515. var vertexData = geometries.vertexData;
  20516. if (vertexData) {
  20517. for (index = 0; index < vertexData.length; index++) {
  20518. var parsedVertexData = vertexData[index];
  20519. parseVertexData(parsedVertexData, scene, rootUrl);
  20520. }
  20521. }
  20522. }
  20523. // Meshes
  20524. for (index = 0; index < parsedData.meshes.length; index++) {
  20525. var parsedMesh = parsedData.meshes[index];
  20526. parseMesh(parsedMesh, scene, rootUrl);
  20527. }
  20528. // Cameras
  20529. for (index = 0; index < parsedData.cameras.length; index++) {
  20530. var parsedCamera = parsedData.cameras[index];
  20531. parseCamera(parsedCamera, scene);
  20532. }
  20533. if (parsedData.activeCameraID) {
  20534. scene.setActiveCameraByID(parsedData.activeCameraID);
  20535. }
  20536. // Browsing all the graph to connect the dots
  20537. for (index = 0; index < scene.cameras.length; index++) {
  20538. var camera = scene.cameras[index];
  20539. if (camera._waitingParentId) {
  20540. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  20541. camera._waitingParentId = undefined;
  20542. }
  20543. }
  20544. for (index = 0; index < scene.lights.length; index++) {
  20545. var light = scene.lights[index];
  20546. if (light._waitingParentId) {
  20547. light.parent = scene.getLastEntryByID(light._waitingParentId);
  20548. light._waitingParentId = undefined;
  20549. }
  20550. }
  20551. // Sounds
  20552. if (BABYLON.AudioEngine && parsedData.sounds) {
  20553. for (index = 0; index < parsedData.sounds.length; index++) {
  20554. var parsedSound = parsedData.sounds[index];
  20555. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  20556. parseSound(parsedSound, scene, rootUrl);
  20557. }
  20558. else {
  20559. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  20560. }
  20561. }
  20562. }
  20563. // Connect parents & children and parse actions
  20564. for (index = 0; index < scene.meshes.length; index++) {
  20565. var mesh = scene.meshes[index];
  20566. if (mesh._waitingParentId) {
  20567. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  20568. mesh._waitingParentId = undefined;
  20569. }
  20570. if (mesh._waitingActions) {
  20571. parseActions(mesh._waitingActions, mesh, scene);
  20572. mesh._waitingActions = undefined;
  20573. }
  20574. }
  20575. // freeze world matrix application
  20576. for (index = 0; index < scene.meshes.length; index++) {
  20577. var currentMesh = scene.meshes[index];
  20578. if (currentMesh._waitingFreezeWorldMatrix) {
  20579. currentMesh.freezeWorldMatrix();
  20580. currentMesh._waitingFreezeWorldMatrix = undefined;
  20581. }
  20582. }
  20583. // Particles Systems
  20584. if (parsedData.particleSystems) {
  20585. for (index = 0; index < parsedData.particleSystems.length; index++) {
  20586. var parsedParticleSystem = parsedData.particleSystems[index];
  20587. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  20588. }
  20589. }
  20590. // Lens flares
  20591. if (parsedData.lensFlareSystems) {
  20592. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  20593. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  20594. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  20595. }
  20596. }
  20597. // Shadows
  20598. if (parsedData.shadowGenerators) {
  20599. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  20600. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  20601. parseShadowGenerator(parsedShadowGenerator, scene);
  20602. }
  20603. }
  20604. // Actions (scene)
  20605. if (parsedData.actions) {
  20606. parseActions(parsedData.actions, null, scene);
  20607. }
  20608. // Finish
  20609. return true;
  20610. }
  20611. });
  20612. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  20613. })(BABYLON || (BABYLON = {}));
  20614. var BABYLON;
  20615. (function (BABYLON) {
  20616. var SpriteManager = (function () {
  20617. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  20618. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  20619. this.name = name;
  20620. this.cellSize = cellSize;
  20621. this.sprites = new Array();
  20622. this.renderingGroupId = 0;
  20623. this.layerMask = 0x0FFFFFFF;
  20624. this.fogEnabled = true;
  20625. this.isPickable = false;
  20626. this._vertexDeclaration = [4, 4, 4, 4];
  20627. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  20628. this._capacity = capacity;
  20629. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  20630. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  20631. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  20632. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  20633. this._scene = scene;
  20634. this._scene.spriteManagers.push(this);
  20635. // VBO
  20636. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  20637. var indices = [];
  20638. var index = 0;
  20639. for (var count = 0; count < capacity; count++) {
  20640. indices.push(index);
  20641. indices.push(index + 1);
  20642. indices.push(index + 2);
  20643. indices.push(index);
  20644. indices.push(index + 2);
  20645. indices.push(index + 3);
  20646. index += 4;
  20647. }
  20648. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  20649. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  20650. // Effects
  20651. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  20652. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  20653. }
  20654. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  20655. var arrayOffset = index * 16;
  20656. if (offsetX === 0)
  20657. offsetX = this._epsilon;
  20658. else if (offsetX === 1)
  20659. offsetX = 1 - this._epsilon;
  20660. if (offsetY === 0)
  20661. offsetY = this._epsilon;
  20662. else if (offsetY === 1)
  20663. offsetY = 1 - this._epsilon;
  20664. this._vertices[arrayOffset] = sprite.position.x;
  20665. this._vertices[arrayOffset + 1] = sprite.position.y;
  20666. this._vertices[arrayOffset + 2] = sprite.position.z;
  20667. this._vertices[arrayOffset + 3] = sprite.angle;
  20668. this._vertices[arrayOffset + 4] = sprite.width;
  20669. this._vertices[arrayOffset + 5] = sprite.height;
  20670. this._vertices[arrayOffset + 6] = offsetX;
  20671. this._vertices[arrayOffset + 7] = offsetY;
  20672. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  20673. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  20674. var offset = (sprite.cellIndex / rowSize) >> 0;
  20675. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  20676. this._vertices[arrayOffset + 11] = offset;
  20677. // Color
  20678. this._vertices[arrayOffset + 12] = sprite.color.r;
  20679. this._vertices[arrayOffset + 13] = sprite.color.g;
  20680. this._vertices[arrayOffset + 14] = sprite.color.b;
  20681. this._vertices[arrayOffset + 15] = sprite.color.a;
  20682. };
  20683. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  20684. var count = Math.min(this._capacity, this.sprites.length);
  20685. var min = BABYLON.Vector3.Zero();
  20686. var max = BABYLON.Vector3.Zero();
  20687. var distance = Number.MAX_VALUE;
  20688. var currentSprite;
  20689. var cameraSpacePosition = BABYLON.Vector3.Zero();
  20690. var cameraView = camera.getViewMatrix();
  20691. for (var index = 0; index < count; index++) {
  20692. var sprite = this.sprites[index];
  20693. if (!sprite) {
  20694. continue;
  20695. }
  20696. if (predicate) {
  20697. if (!predicate(sprite)) {
  20698. continue;
  20699. }
  20700. }
  20701. else if (!sprite.isPickable) {
  20702. continue;
  20703. }
  20704. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  20705. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  20706. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  20707. if (ray.intersectsBoxMinMax(min, max)) {
  20708. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  20709. if (distance > currentDistance) {
  20710. distance = currentDistance;
  20711. currentSprite = sprite;
  20712. if (fastCheck) {
  20713. break;
  20714. }
  20715. }
  20716. }
  20717. }
  20718. if (currentSprite) {
  20719. var result = new BABYLON.PickingInfo();
  20720. result.hit = true;
  20721. result.pickedSprite = currentSprite;
  20722. result.distance = distance;
  20723. return result;
  20724. }
  20725. return null;
  20726. };
  20727. SpriteManager.prototype.render = function () {
  20728. // Check
  20729. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  20730. return;
  20731. var engine = this._scene.getEngine();
  20732. var baseSize = this._spriteTexture.getBaseSize();
  20733. // Sprites
  20734. var deltaTime = engine.getDeltaTime();
  20735. var max = Math.min(this._capacity, this.sprites.length);
  20736. var rowSize = baseSize.width / this.cellSize;
  20737. var offset = 0;
  20738. for (var index = 0; index < max; index++) {
  20739. var sprite = this.sprites[index];
  20740. if (!sprite) {
  20741. continue;
  20742. }
  20743. sprite._animate(deltaTime);
  20744. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  20745. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  20746. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  20747. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  20748. }
  20749. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  20750. // Render
  20751. var effect = this._effectBase;
  20752. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  20753. effect = this._effectFog;
  20754. }
  20755. engine.enableEffect(effect);
  20756. var viewMatrix = this._scene.getViewMatrix();
  20757. effect.setTexture("diffuseSampler", this._spriteTexture);
  20758. effect.setMatrix("view", viewMatrix);
  20759. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  20760. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  20761. // Fog
  20762. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  20763. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  20764. effect.setColor3("vFogColor", this._scene.fogColor);
  20765. }
  20766. // VBOs
  20767. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  20768. // Draw order
  20769. engine.setDepthFunctionToLessOrEqual();
  20770. effect.setBool("alphaTest", true);
  20771. engine.setColorWrite(false);
  20772. engine.draw(true, 0, max * 6);
  20773. engine.setColorWrite(true);
  20774. effect.setBool("alphaTest", false);
  20775. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  20776. engine.draw(true, 0, max * 6);
  20777. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20778. };
  20779. SpriteManager.prototype.dispose = function () {
  20780. if (this._vertexBuffer) {
  20781. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  20782. this._vertexBuffer = null;
  20783. }
  20784. if (this._indexBuffer) {
  20785. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  20786. this._indexBuffer = null;
  20787. }
  20788. if (this._spriteTexture) {
  20789. this._spriteTexture.dispose();
  20790. this._spriteTexture = null;
  20791. }
  20792. // Remove from scene
  20793. var index = this._scene.spriteManagers.indexOf(this);
  20794. this._scene.spriteManagers.splice(index, 1);
  20795. // Callback
  20796. if (this.onDispose) {
  20797. this.onDispose();
  20798. }
  20799. };
  20800. return SpriteManager;
  20801. })();
  20802. BABYLON.SpriteManager = SpriteManager;
  20803. })(BABYLON || (BABYLON = {}));
  20804. var BABYLON;
  20805. (function (BABYLON) {
  20806. var Sprite = (function () {
  20807. function Sprite(name, manager) {
  20808. this.name = name;
  20809. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  20810. this.width = 1.0;
  20811. this.height = 1.0;
  20812. this.angle = 0;
  20813. this.cellIndex = 0;
  20814. this.invertU = 0;
  20815. this.invertV = 0;
  20816. this.animations = new Array();
  20817. this.isPickable = false;
  20818. this._animationStarted = false;
  20819. this._loopAnimation = false;
  20820. this._fromIndex = 0;
  20821. this._toIndex = 0;
  20822. this._delay = 0;
  20823. this._direction = 1;
  20824. this._frameCount = 0;
  20825. this._time = 0;
  20826. this._manager = manager;
  20827. this._manager.sprites.push(this);
  20828. this.position = BABYLON.Vector3.Zero();
  20829. }
  20830. Object.defineProperty(Sprite.prototype, "size", {
  20831. get: function () {
  20832. return this.width;
  20833. },
  20834. set: function (value) {
  20835. this.width = value;
  20836. this.height = value;
  20837. },
  20838. enumerable: true,
  20839. configurable: true
  20840. });
  20841. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  20842. this._fromIndex = from;
  20843. this._toIndex = to;
  20844. this._loopAnimation = loop;
  20845. this._delay = delay;
  20846. this._animationStarted = true;
  20847. this._direction = from < to ? 1 : -1;
  20848. this.cellIndex = from;
  20849. this._time = 0;
  20850. };
  20851. Sprite.prototype.stopAnimation = function () {
  20852. this._animationStarted = false;
  20853. };
  20854. Sprite.prototype._animate = function (deltaTime) {
  20855. if (!this._animationStarted)
  20856. return;
  20857. this._time += deltaTime;
  20858. if (this._time > this._delay) {
  20859. this._time = this._time % this._delay;
  20860. this.cellIndex += this._direction;
  20861. if (this.cellIndex == this._toIndex) {
  20862. if (this._loopAnimation) {
  20863. this.cellIndex = this._fromIndex;
  20864. }
  20865. else {
  20866. this._animationStarted = false;
  20867. if (this.disposeWhenFinishedAnimating) {
  20868. this.dispose();
  20869. }
  20870. }
  20871. }
  20872. }
  20873. };
  20874. Sprite.prototype.dispose = function () {
  20875. for (var i = 0; i < this._manager.sprites.length; i++) {
  20876. if (this._manager.sprites[i] == this) {
  20877. this._manager.sprites.splice(i, 1);
  20878. }
  20879. }
  20880. };
  20881. return Sprite;
  20882. })();
  20883. BABYLON.Sprite = Sprite;
  20884. })(BABYLON || (BABYLON = {}));
  20885. var BABYLON;
  20886. (function (BABYLON) {
  20887. var Layer = (function () {
  20888. function Layer(name, imgUrl, scene, isBackground, color) {
  20889. this.name = name;
  20890. this._vertexDeclaration = [2];
  20891. this._vertexStrideSize = 2 * 4;
  20892. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  20893. this.isBackground = isBackground === undefined ? true : isBackground;
  20894. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  20895. this._scene = scene;
  20896. this._scene.layers.push(this);
  20897. // VBO
  20898. var vertices = [];
  20899. vertices.push(1, 1);
  20900. vertices.push(-1, 1);
  20901. vertices.push(-1, -1);
  20902. vertices.push(1, -1);
  20903. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  20904. // Indices
  20905. var indices = [];
  20906. indices.push(0);
  20907. indices.push(1);
  20908. indices.push(2);
  20909. indices.push(0);
  20910. indices.push(2);
  20911. indices.push(3);
  20912. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  20913. // Effects
  20914. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  20915. }
  20916. Layer.prototype.render = function () {
  20917. // Check
  20918. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  20919. return;
  20920. var engine = this._scene.getEngine();
  20921. // Render
  20922. engine.enableEffect(this._effect);
  20923. engine.setState(false);
  20924. // Texture
  20925. this._effect.setTexture("textureSampler", this.texture);
  20926. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  20927. // Color
  20928. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  20929. // VBOs
  20930. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  20931. // Draw order
  20932. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  20933. engine.draw(true, 0, 6);
  20934. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20935. };
  20936. Layer.prototype.dispose = function () {
  20937. if (this._vertexBuffer) {
  20938. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  20939. this._vertexBuffer = null;
  20940. }
  20941. if (this._indexBuffer) {
  20942. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  20943. this._indexBuffer = null;
  20944. }
  20945. if (this.texture) {
  20946. this.texture.dispose();
  20947. this.texture = null;
  20948. }
  20949. // Remove from scene
  20950. var index = this._scene.layers.indexOf(this);
  20951. this._scene.layers.splice(index, 1);
  20952. // Callback
  20953. if (this.onDispose) {
  20954. this.onDispose();
  20955. }
  20956. };
  20957. return Layer;
  20958. })();
  20959. BABYLON.Layer = Layer;
  20960. })(BABYLON || (BABYLON = {}));
  20961. var BABYLON;
  20962. (function (BABYLON) {
  20963. var Particle = (function () {
  20964. function Particle() {
  20965. this.position = BABYLON.Vector3.Zero();
  20966. this.direction = BABYLON.Vector3.Zero();
  20967. this.color = new BABYLON.Color4(0, 0, 0, 0);
  20968. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  20969. this.lifeTime = 1.0;
  20970. this.age = 0;
  20971. this.size = 0;
  20972. this.angle = 0;
  20973. this.angularSpeed = 0;
  20974. }
  20975. Particle.prototype.copyTo = function (other) {
  20976. other.position.copyFrom(this.position);
  20977. other.direction.copyFrom(this.direction);
  20978. other.color.copyFrom(this.color);
  20979. other.colorStep.copyFrom(this.colorStep);
  20980. other.lifeTime = this.lifeTime;
  20981. other.age = this.age;
  20982. other.size = this.size;
  20983. other.angle = this.angle;
  20984. other.angularSpeed = this.angularSpeed;
  20985. };
  20986. return Particle;
  20987. })();
  20988. BABYLON.Particle = Particle;
  20989. })(BABYLON || (BABYLON = {}));
  20990. var BABYLON;
  20991. (function (BABYLON) {
  20992. var randomNumber = function (min, max) {
  20993. if (min === max) {
  20994. return (min);
  20995. }
  20996. var random = Math.random();
  20997. return ((random * (max - min)) + min);
  20998. };
  20999. var ParticleSystem = (function () {
  21000. function ParticleSystem(name, capacity, scene, customEffect) {
  21001. var _this = this;
  21002. this.name = name;
  21003. this.renderingGroupId = 0;
  21004. this.emitter = null;
  21005. this.emitRate = 10;
  21006. this.manualEmitCount = -1;
  21007. this.updateSpeed = 0.01;
  21008. this.targetStopDuration = 0;
  21009. this.disposeOnStop = false;
  21010. this.minEmitPower = 1;
  21011. this.maxEmitPower = 1;
  21012. this.minLifeTime = 1;
  21013. this.maxLifeTime = 1;
  21014. this.minSize = 1;
  21015. this.maxSize = 1;
  21016. this.minAngularSpeed = 0;
  21017. this.maxAngularSpeed = 0;
  21018. this.layerMask = 0x0FFFFFFF;
  21019. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  21020. this.forceDepthWrite = false;
  21021. this.gravity = BABYLON.Vector3.Zero();
  21022. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  21023. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  21024. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  21025. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  21026. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21027. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21028. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  21029. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21030. this.particles = new Array();
  21031. this._vertexDeclaration = [3, 4, 4];
  21032. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  21033. this._stockParticles = new Array();
  21034. this._newPartsExcess = 0;
  21035. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  21036. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  21037. this._scaledDirection = BABYLON.Vector3.Zero();
  21038. this._scaledGravity = BABYLON.Vector3.Zero();
  21039. this._currentRenderId = -1;
  21040. this._started = false;
  21041. this._stopped = false;
  21042. this._actualFrame = 0;
  21043. this.id = name;
  21044. this._capacity = capacity;
  21045. this._scene = scene;
  21046. this._customEffect = customEffect;
  21047. scene.particleSystems.push(this);
  21048. // VBO
  21049. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  21050. var indices = [];
  21051. var index = 0;
  21052. for (var count = 0; count < capacity; count++) {
  21053. indices.push(index);
  21054. indices.push(index + 1);
  21055. indices.push(index + 2);
  21056. indices.push(index);
  21057. indices.push(index + 2);
  21058. indices.push(index + 3);
  21059. index += 4;
  21060. }
  21061. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21062. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  21063. // Default behaviors
  21064. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  21065. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  21066. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  21067. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  21068. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  21069. };
  21070. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  21071. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  21072. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  21073. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  21074. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  21075. };
  21076. this.updateFunction = function (particles) {
  21077. for (var index = 0; index < particles.length; index++) {
  21078. var particle = particles[index];
  21079. particle.age += _this._scaledUpdateSpeed;
  21080. if (particle.age >= particle.lifeTime) {
  21081. _this.recycleParticle(particle);
  21082. index--;
  21083. continue;
  21084. }
  21085. else {
  21086. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  21087. particle.color.addInPlace(_this._scaledColorStep);
  21088. if (particle.color.a < 0)
  21089. particle.color.a = 0;
  21090. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  21091. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  21092. particle.position.addInPlace(_this._scaledDirection);
  21093. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  21094. particle.direction.addInPlace(_this._scaledGravity);
  21095. }
  21096. }
  21097. };
  21098. }
  21099. ParticleSystem.prototype.recycleParticle = function (particle) {
  21100. var lastParticle = this.particles.pop();
  21101. if (lastParticle !== particle) {
  21102. lastParticle.copyTo(particle);
  21103. this._stockParticles.push(lastParticle);
  21104. }
  21105. };
  21106. ParticleSystem.prototype.getCapacity = function () {
  21107. return this._capacity;
  21108. };
  21109. ParticleSystem.prototype.isAlive = function () {
  21110. return this._alive;
  21111. };
  21112. ParticleSystem.prototype.isStarted = function () {
  21113. return this._started;
  21114. };
  21115. ParticleSystem.prototype.start = function () {
  21116. this._started = true;
  21117. this._stopped = false;
  21118. this._actualFrame = 0;
  21119. };
  21120. ParticleSystem.prototype.stop = function () {
  21121. this._stopped = true;
  21122. };
  21123. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  21124. var offset = index * 11;
  21125. this._vertices[offset] = particle.position.x;
  21126. this._vertices[offset + 1] = particle.position.y;
  21127. this._vertices[offset + 2] = particle.position.z;
  21128. this._vertices[offset + 3] = particle.color.r;
  21129. this._vertices[offset + 4] = particle.color.g;
  21130. this._vertices[offset + 5] = particle.color.b;
  21131. this._vertices[offset + 6] = particle.color.a;
  21132. this._vertices[offset + 7] = particle.angle;
  21133. this._vertices[offset + 8] = particle.size;
  21134. this._vertices[offset + 9] = offsetX;
  21135. this._vertices[offset + 10] = offsetY;
  21136. };
  21137. ParticleSystem.prototype._update = function (newParticles) {
  21138. // Update current
  21139. this._alive = this.particles.length > 0;
  21140. this.updateFunction(this.particles);
  21141. // Add new ones
  21142. var worldMatrix;
  21143. if (this.emitter.position) {
  21144. worldMatrix = this.emitter.getWorldMatrix();
  21145. }
  21146. else {
  21147. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  21148. }
  21149. for (var index = 0; index < newParticles; index++) {
  21150. if (this.particles.length === this._capacity) {
  21151. break;
  21152. }
  21153. if (this._stockParticles.length !== 0) {
  21154. var particle = this._stockParticles.pop();
  21155. particle.age = 0;
  21156. }
  21157. else {
  21158. particle = new BABYLON.Particle();
  21159. }
  21160. this.particles.push(particle);
  21161. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  21162. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  21163. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  21164. particle.size = randomNumber(this.minSize, this.maxSize);
  21165. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  21166. this.startPositionFunction(worldMatrix, particle.position);
  21167. var step = randomNumber(0, 1.0);
  21168. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  21169. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  21170. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  21171. }
  21172. };
  21173. ParticleSystem.prototype._getEffect = function () {
  21174. if (this._customEffect) {
  21175. return this._customEffect;
  21176. }
  21177. ;
  21178. var defines = [];
  21179. if (this._scene.clipPlane) {
  21180. defines.push("#define CLIPPLANE");
  21181. }
  21182. // Effect
  21183. var join = defines.join("\n");
  21184. if (this._cachedDefines !== join) {
  21185. this._cachedDefines = join;
  21186. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  21187. }
  21188. return this._effect;
  21189. };
  21190. ParticleSystem.prototype.animate = function () {
  21191. if (!this._started)
  21192. return;
  21193. var effect = this._getEffect();
  21194. // Check
  21195. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  21196. return;
  21197. if (this._currentRenderId === this._scene.getRenderId()) {
  21198. return;
  21199. }
  21200. this._currentRenderId = this._scene.getRenderId();
  21201. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  21202. // determine the number of particles we need to create
  21203. var emitCout;
  21204. if (this.manualEmitCount > -1) {
  21205. emitCout = this.manualEmitCount;
  21206. this.manualEmitCount = 0;
  21207. }
  21208. else {
  21209. emitCout = this.emitRate;
  21210. }
  21211. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  21212. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  21213. if (this._newPartsExcess > 1.0) {
  21214. newParticles += this._newPartsExcess >> 0;
  21215. this._newPartsExcess -= this._newPartsExcess >> 0;
  21216. }
  21217. this._alive = false;
  21218. if (!this._stopped) {
  21219. this._actualFrame += this._scaledUpdateSpeed;
  21220. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  21221. this.stop();
  21222. }
  21223. else {
  21224. newParticles = 0;
  21225. }
  21226. this._update(newParticles);
  21227. // Stopped?
  21228. if (this._stopped) {
  21229. if (!this._alive) {
  21230. this._started = false;
  21231. if (this.disposeOnStop) {
  21232. this._scene._toBeDisposed.push(this);
  21233. }
  21234. }
  21235. }
  21236. // Update VBO
  21237. var offset = 0;
  21238. for (var index = 0; index < this.particles.length; index++) {
  21239. var particle = this.particles[index];
  21240. this._appendParticleVertex(offset++, particle, 0, 0);
  21241. this._appendParticleVertex(offset++, particle, 1, 0);
  21242. this._appendParticleVertex(offset++, particle, 1, 1);
  21243. this._appendParticleVertex(offset++, particle, 0, 1);
  21244. }
  21245. var engine = this._scene.getEngine();
  21246. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  21247. };
  21248. ParticleSystem.prototype.render = function () {
  21249. var effect = this._getEffect();
  21250. // Check
  21251. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  21252. return 0;
  21253. var engine = this._scene.getEngine();
  21254. // Render
  21255. engine.enableEffect(effect);
  21256. engine.setState(false);
  21257. var viewMatrix = this._scene.getViewMatrix();
  21258. effect.setTexture("diffuseSampler", this.particleTexture);
  21259. effect.setMatrix("view", viewMatrix);
  21260. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  21261. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  21262. if (this._scene.clipPlane) {
  21263. var clipPlane = this._scene.clipPlane;
  21264. var invView = viewMatrix.clone();
  21265. invView.invert();
  21266. effect.setMatrix("invView", invView);
  21267. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  21268. }
  21269. // VBOs
  21270. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  21271. // Draw order
  21272. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  21273. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  21274. }
  21275. else {
  21276. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21277. }
  21278. if (this.forceDepthWrite) {
  21279. engine.setDepthWrite(true);
  21280. }
  21281. engine.draw(true, 0, this.particles.length * 6);
  21282. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21283. return this.particles.length;
  21284. };
  21285. ParticleSystem.prototype.dispose = function () {
  21286. if (this._vertexBuffer) {
  21287. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21288. this._vertexBuffer = null;
  21289. }
  21290. if (this._indexBuffer) {
  21291. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21292. this._indexBuffer = null;
  21293. }
  21294. if (this.particleTexture) {
  21295. this.particleTexture.dispose();
  21296. this.particleTexture = null;
  21297. }
  21298. // Remove from scene
  21299. var index = this._scene.particleSystems.indexOf(this);
  21300. this._scene.particleSystems.splice(index, 1);
  21301. // Callback
  21302. if (this.onDispose) {
  21303. this.onDispose();
  21304. }
  21305. };
  21306. // Clone
  21307. ParticleSystem.prototype.clone = function (name, newEmitter) {
  21308. var result = new ParticleSystem(name, this._capacity, this._scene);
  21309. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  21310. if (newEmitter === undefined) {
  21311. newEmitter = this.emitter;
  21312. }
  21313. result.emitter = newEmitter;
  21314. if (this.particleTexture) {
  21315. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  21316. }
  21317. result.start();
  21318. return result;
  21319. };
  21320. // Statics
  21321. ParticleSystem.BLENDMODE_ONEONE = 0;
  21322. ParticleSystem.BLENDMODE_STANDARD = 1;
  21323. return ParticleSystem;
  21324. })();
  21325. BABYLON.ParticleSystem = ParticleSystem;
  21326. })(BABYLON || (BABYLON = {}));
  21327. var BABYLON;
  21328. (function (BABYLON) {
  21329. var AnimationRange = (function () {
  21330. function AnimationRange(name, from, to) {
  21331. this.name = name;
  21332. this.from = from;
  21333. this.to = to;
  21334. }
  21335. return AnimationRange;
  21336. })();
  21337. BABYLON.AnimationRange = AnimationRange;
  21338. var Animation = (function () {
  21339. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  21340. this.name = name;
  21341. this.targetProperty = targetProperty;
  21342. this.framePerSecond = framePerSecond;
  21343. this.dataType = dataType;
  21344. this.loopMode = loopMode;
  21345. this._offsetsCache = {};
  21346. this._highLimitsCache = {};
  21347. this._stopped = false;
  21348. this.allowMatricesInterpolation = false;
  21349. this._ranges = new Array();
  21350. this.targetPropertyPath = targetProperty.split(".");
  21351. this.dataType = dataType;
  21352. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  21353. }
  21354. Animation.CreateAndStartAnimation = function (name, mesh, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  21355. var dataType = undefined;
  21356. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  21357. dataType = Animation.ANIMATIONTYPE_FLOAT;
  21358. }
  21359. else if (from instanceof BABYLON.Quaternion) {
  21360. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  21361. }
  21362. else if (from instanceof BABYLON.Vector3) {
  21363. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  21364. }
  21365. else if (from instanceof BABYLON.Vector2) {
  21366. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  21367. }
  21368. else if (from instanceof BABYLON.Color3) {
  21369. dataType = Animation.ANIMATIONTYPE_COLOR3;
  21370. }
  21371. if (dataType == undefined) {
  21372. return null;
  21373. }
  21374. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  21375. var keys = [];
  21376. keys.push({ frame: 0, value: from });
  21377. keys.push({ frame: totalFrame, value: to });
  21378. animation.setKeys(keys);
  21379. if (easingFunction !== undefined) {
  21380. animation.setEasingFunction(easingFunction);
  21381. }
  21382. mesh.animations.push(animation);
  21383. return mesh.getScene().beginAnimation(mesh, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  21384. };
  21385. // Methods
  21386. Animation.prototype.createRange = function (name, from, to) {
  21387. this._ranges.push(new AnimationRange(name, from, to));
  21388. };
  21389. Animation.prototype.deleteRange = function (name) {
  21390. for (var index = 0; index < this._ranges.length; index++) {
  21391. if (this._ranges[index].name === name) {
  21392. this._ranges.splice(index, 1);
  21393. return;
  21394. }
  21395. }
  21396. };
  21397. Animation.prototype.getRange = function (name) {
  21398. for (var index = 0; index < this._ranges.length; index++) {
  21399. if (this._ranges[index].name === name) {
  21400. return this._ranges[index];
  21401. }
  21402. }
  21403. return null;
  21404. };
  21405. Animation.prototype.reset = function () {
  21406. this._offsetsCache = {};
  21407. this._highLimitsCache = {};
  21408. this.currentFrame = 0;
  21409. };
  21410. Animation.prototype.isStopped = function () {
  21411. return this._stopped;
  21412. };
  21413. Animation.prototype.getKeys = function () {
  21414. return this._keys;
  21415. };
  21416. Animation.prototype.getEasingFunction = function () {
  21417. return this._easingFunction;
  21418. };
  21419. Animation.prototype.setEasingFunction = function (easingFunction) {
  21420. this._easingFunction = easingFunction;
  21421. };
  21422. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  21423. return startValue + (endValue - startValue) * gradient;
  21424. };
  21425. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  21426. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  21427. };
  21428. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  21429. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  21430. };
  21431. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  21432. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  21433. };
  21434. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  21435. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  21436. };
  21437. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  21438. var startScale = new BABYLON.Vector3(0, 0, 0);
  21439. var startRotation = new BABYLON.Quaternion();
  21440. var startTranslation = new BABYLON.Vector3(0, 0, 0);
  21441. startValue.decompose(startScale, startRotation, startTranslation);
  21442. var endScale = new BABYLON.Vector3(0, 0, 0);
  21443. var endRotation = new BABYLON.Quaternion();
  21444. var endTranslation = new BABYLON.Vector3(0, 0, 0);
  21445. endValue.decompose(endScale, endRotation, endTranslation);
  21446. var resultScale = this.vector3InterpolateFunction(startScale, endScale, gradient);
  21447. var resultRotation = this.quaternionInterpolateFunction(startRotation, endRotation, gradient);
  21448. var resultTranslation = this.vector3InterpolateFunction(startTranslation, endTranslation, gradient);
  21449. var result = BABYLON.Matrix.Compose(resultScale, resultRotation, resultTranslation);
  21450. return result;
  21451. };
  21452. Animation.prototype.clone = function () {
  21453. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  21454. if (this._keys) {
  21455. clone.setKeys(this._keys);
  21456. }
  21457. return clone;
  21458. };
  21459. Animation.prototype.setKeys = function (values) {
  21460. this._keys = values.slice(0);
  21461. this._offsetsCache = {};
  21462. this._highLimitsCache = {};
  21463. };
  21464. Animation.prototype._getKeyValue = function (value) {
  21465. if (typeof value === "function") {
  21466. return value();
  21467. }
  21468. return value;
  21469. };
  21470. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  21471. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  21472. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  21473. }
  21474. this.currentFrame = currentFrame;
  21475. // Try to get a hash to find the right key
  21476. 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));
  21477. if (this._keys[startKey].frame >= currentFrame) {
  21478. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  21479. startKey--;
  21480. }
  21481. }
  21482. for (var key = startKey; key < this._keys.length; key++) {
  21483. if (this._keys[key + 1].frame >= currentFrame) {
  21484. var startValue = this._getKeyValue(this._keys[key].value);
  21485. var endValue = this._getKeyValue(this._keys[key + 1].value);
  21486. // gradient : percent of currentFrame between the frame inf and the frame sup
  21487. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  21488. // check for easingFunction and correction of gradient
  21489. if (this._easingFunction != null) {
  21490. gradient = this._easingFunction.ease(gradient);
  21491. }
  21492. switch (this.dataType) {
  21493. // Float
  21494. case Animation.ANIMATIONTYPE_FLOAT:
  21495. switch (loopMode) {
  21496. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21497. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21498. return this.floatInterpolateFunction(startValue, endValue, gradient);
  21499. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21500. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  21501. }
  21502. break;
  21503. // Quaternion
  21504. case Animation.ANIMATIONTYPE_QUATERNION:
  21505. var quaternion = null;
  21506. switch (loopMode) {
  21507. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21508. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21509. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  21510. break;
  21511. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21512. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21513. break;
  21514. }
  21515. return quaternion;
  21516. // Vector3
  21517. case Animation.ANIMATIONTYPE_VECTOR3:
  21518. switch (loopMode) {
  21519. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21520. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21521. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  21522. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21523. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21524. }
  21525. // Vector2
  21526. case Animation.ANIMATIONTYPE_VECTOR2:
  21527. switch (loopMode) {
  21528. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21529. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21530. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  21531. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21532. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21533. }
  21534. // Color3
  21535. case Animation.ANIMATIONTYPE_COLOR3:
  21536. switch (loopMode) {
  21537. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21538. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21539. return this.color3InterpolateFunction(startValue, endValue, gradient);
  21540. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21541. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21542. }
  21543. // Matrix
  21544. case Animation.ANIMATIONTYPE_MATRIX:
  21545. switch (loopMode) {
  21546. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21547. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21548. if (this.allowMatricesInterpolation) {
  21549. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  21550. }
  21551. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21552. return startValue;
  21553. }
  21554. default:
  21555. break;
  21556. }
  21557. break;
  21558. }
  21559. }
  21560. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  21561. };
  21562. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  21563. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  21564. this._stopped = true;
  21565. return false;
  21566. }
  21567. var returnValue = true;
  21568. // Adding a start key at frame 0 if missing
  21569. if (this._keys[0].frame !== 0) {
  21570. var newKey = { frame: 0, value: this._keys[0].value };
  21571. this._keys.splice(0, 0, newKey);
  21572. }
  21573. // Check limits
  21574. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  21575. from = this._keys[0].frame;
  21576. }
  21577. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  21578. to = this._keys[this._keys.length - 1].frame;
  21579. }
  21580. // Compute ratio
  21581. var range = to - from;
  21582. var offsetValue;
  21583. // ratio represents the frame delta between from and to
  21584. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  21585. var highLimitValue = 0;
  21586. if (ratio > range && !loop) {
  21587. returnValue = false;
  21588. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  21589. }
  21590. else {
  21591. // Get max value if required
  21592. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  21593. var keyOffset = to.toString() + from.toString();
  21594. if (!this._offsetsCache[keyOffset]) {
  21595. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  21596. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  21597. switch (this.dataType) {
  21598. // Float
  21599. case Animation.ANIMATIONTYPE_FLOAT:
  21600. this._offsetsCache[keyOffset] = toValue - fromValue;
  21601. break;
  21602. // Quaternion
  21603. case Animation.ANIMATIONTYPE_QUATERNION:
  21604. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21605. break;
  21606. // Vector3
  21607. case Animation.ANIMATIONTYPE_VECTOR3:
  21608. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21609. // Vector2
  21610. case Animation.ANIMATIONTYPE_VECTOR2:
  21611. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21612. // Color3
  21613. case Animation.ANIMATIONTYPE_COLOR3:
  21614. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21615. default:
  21616. break;
  21617. }
  21618. this._highLimitsCache[keyOffset] = toValue;
  21619. }
  21620. highLimitValue = this._highLimitsCache[keyOffset];
  21621. offsetValue = this._offsetsCache[keyOffset];
  21622. }
  21623. }
  21624. if (offsetValue === undefined) {
  21625. switch (this.dataType) {
  21626. // Float
  21627. case Animation.ANIMATIONTYPE_FLOAT:
  21628. offsetValue = 0;
  21629. break;
  21630. // Quaternion
  21631. case Animation.ANIMATIONTYPE_QUATERNION:
  21632. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  21633. break;
  21634. // Vector3
  21635. case Animation.ANIMATIONTYPE_VECTOR3:
  21636. offsetValue = BABYLON.Vector3.Zero();
  21637. break;
  21638. // Vector2
  21639. case Animation.ANIMATIONTYPE_VECTOR2:
  21640. offsetValue = BABYLON.Vector2.Zero();
  21641. break;
  21642. // Color3
  21643. case Animation.ANIMATIONTYPE_COLOR3:
  21644. offsetValue = BABYLON.Color3.Black();
  21645. }
  21646. }
  21647. // Compute value
  21648. var repeatCount = (ratio / range) >> 0;
  21649. var currentFrame = returnValue ? from + ratio % range : to;
  21650. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  21651. // Set value
  21652. if (this.targetPropertyPath.length > 1) {
  21653. var property = this._target[this.targetPropertyPath[0]];
  21654. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  21655. property = property[this.targetPropertyPath[index]];
  21656. }
  21657. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  21658. }
  21659. else {
  21660. this._target[this.targetPropertyPath[0]] = currentValue;
  21661. }
  21662. if (this._target.markAsDirty) {
  21663. this._target.markAsDirty(this.targetProperty);
  21664. }
  21665. if (!returnValue) {
  21666. this._stopped = true;
  21667. }
  21668. return returnValue;
  21669. };
  21670. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  21671. get: function () {
  21672. return Animation._ANIMATIONTYPE_FLOAT;
  21673. },
  21674. enumerable: true,
  21675. configurable: true
  21676. });
  21677. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  21678. get: function () {
  21679. return Animation._ANIMATIONTYPE_VECTOR3;
  21680. },
  21681. enumerable: true,
  21682. configurable: true
  21683. });
  21684. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  21685. get: function () {
  21686. return Animation._ANIMATIONTYPE_VECTOR2;
  21687. },
  21688. enumerable: true,
  21689. configurable: true
  21690. });
  21691. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  21692. get: function () {
  21693. return Animation._ANIMATIONTYPE_QUATERNION;
  21694. },
  21695. enumerable: true,
  21696. configurable: true
  21697. });
  21698. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  21699. get: function () {
  21700. return Animation._ANIMATIONTYPE_MATRIX;
  21701. },
  21702. enumerable: true,
  21703. configurable: true
  21704. });
  21705. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  21706. get: function () {
  21707. return Animation._ANIMATIONTYPE_COLOR3;
  21708. },
  21709. enumerable: true,
  21710. configurable: true
  21711. });
  21712. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  21713. get: function () {
  21714. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  21715. },
  21716. enumerable: true,
  21717. configurable: true
  21718. });
  21719. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  21720. get: function () {
  21721. return Animation._ANIMATIONLOOPMODE_CYCLE;
  21722. },
  21723. enumerable: true,
  21724. configurable: true
  21725. });
  21726. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  21727. get: function () {
  21728. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  21729. },
  21730. enumerable: true,
  21731. configurable: true
  21732. });
  21733. // Statics
  21734. Animation._ANIMATIONTYPE_FLOAT = 0;
  21735. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  21736. Animation._ANIMATIONTYPE_QUATERNION = 2;
  21737. Animation._ANIMATIONTYPE_MATRIX = 3;
  21738. Animation._ANIMATIONTYPE_COLOR3 = 4;
  21739. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  21740. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  21741. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  21742. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  21743. return Animation;
  21744. })();
  21745. BABYLON.Animation = Animation;
  21746. })(BABYLON || (BABYLON = {}));
  21747. var BABYLON;
  21748. (function (BABYLON) {
  21749. var Animatable = (function () {
  21750. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  21751. if (fromFrame === void 0) { fromFrame = 0; }
  21752. if (toFrame === void 0) { toFrame = 100; }
  21753. if (loopAnimation === void 0) { loopAnimation = false; }
  21754. if (speedRatio === void 0) { speedRatio = 1.0; }
  21755. this.target = target;
  21756. this.fromFrame = fromFrame;
  21757. this.toFrame = toFrame;
  21758. this.loopAnimation = loopAnimation;
  21759. this.speedRatio = speedRatio;
  21760. this.onAnimationEnd = onAnimationEnd;
  21761. this._animations = new Array();
  21762. this._paused = false;
  21763. this.animationStarted = false;
  21764. if (animations) {
  21765. this.appendAnimations(target, animations);
  21766. }
  21767. this._scene = scene;
  21768. scene._activeAnimatables.push(this);
  21769. }
  21770. // Methods
  21771. Animatable.prototype.getAnimations = function () {
  21772. return this._animations;
  21773. };
  21774. Animatable.prototype.appendAnimations = function (target, animations) {
  21775. for (var index = 0; index < animations.length; index++) {
  21776. var animation = animations[index];
  21777. animation._target = target;
  21778. this._animations.push(animation);
  21779. }
  21780. };
  21781. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  21782. var animations = this._animations;
  21783. for (var index = 0; index < animations.length; index++) {
  21784. if (animations[index].targetProperty === property) {
  21785. return animations[index];
  21786. }
  21787. }
  21788. return null;
  21789. };
  21790. Animatable.prototype.reset = function () {
  21791. var animations = this._animations;
  21792. for (var index = 0; index < animations.length; index++) {
  21793. animations[index].reset();
  21794. }
  21795. this._localDelayOffset = null;
  21796. this._pausedDelay = null;
  21797. };
  21798. Animatable.prototype.pause = function () {
  21799. if (this._paused) {
  21800. return;
  21801. }
  21802. this._paused = true;
  21803. };
  21804. Animatable.prototype.restart = function () {
  21805. this._paused = false;
  21806. };
  21807. Animatable.prototype.stop = function () {
  21808. var index = this._scene._activeAnimatables.indexOf(this);
  21809. if (index > -1) {
  21810. this._scene._activeAnimatables.splice(index, 1);
  21811. }
  21812. if (this.onAnimationEnd) {
  21813. this.onAnimationEnd();
  21814. }
  21815. };
  21816. Animatable.prototype._animate = function (delay) {
  21817. if (this._paused) {
  21818. if (!this._pausedDelay) {
  21819. this._pausedDelay = delay;
  21820. }
  21821. return true;
  21822. }
  21823. if (!this._localDelayOffset) {
  21824. this._localDelayOffset = delay;
  21825. }
  21826. else if (this._pausedDelay) {
  21827. this._localDelayOffset += delay - this._pausedDelay;
  21828. this._pausedDelay = null;
  21829. }
  21830. // Animating
  21831. var running = false;
  21832. var animations = this._animations;
  21833. for (var index = 0; index < animations.length; index++) {
  21834. var animation = animations[index];
  21835. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  21836. running = running || isRunning;
  21837. }
  21838. if (!running) {
  21839. // Remove from active animatables
  21840. index = this._scene._activeAnimatables.indexOf(this);
  21841. this._scene._activeAnimatables.splice(index, 1);
  21842. }
  21843. if (!running && this.onAnimationEnd) {
  21844. this.onAnimationEnd();
  21845. }
  21846. return running;
  21847. };
  21848. return Animatable;
  21849. })();
  21850. BABYLON.Animatable = Animatable;
  21851. })(BABYLON || (BABYLON = {}));
  21852. var BABYLON;
  21853. (function (BABYLON) {
  21854. var EasingFunction = (function () {
  21855. function EasingFunction() {
  21856. // Properties
  21857. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  21858. }
  21859. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  21860. get: function () {
  21861. return EasingFunction._EASINGMODE_EASEIN;
  21862. },
  21863. enumerable: true,
  21864. configurable: true
  21865. });
  21866. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  21867. get: function () {
  21868. return EasingFunction._EASINGMODE_EASEOUT;
  21869. },
  21870. enumerable: true,
  21871. configurable: true
  21872. });
  21873. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  21874. get: function () {
  21875. return EasingFunction._EASINGMODE_EASEINOUT;
  21876. },
  21877. enumerable: true,
  21878. configurable: true
  21879. });
  21880. EasingFunction.prototype.setEasingMode = function (easingMode) {
  21881. var n = Math.min(Math.max(easingMode, 0), 2);
  21882. this._easingMode = n;
  21883. };
  21884. EasingFunction.prototype.getEasingMode = function () {
  21885. return this._easingMode;
  21886. };
  21887. EasingFunction.prototype.easeInCore = function (gradient) {
  21888. throw new Error('You must implement this method');
  21889. };
  21890. EasingFunction.prototype.ease = function (gradient) {
  21891. switch (this._easingMode) {
  21892. case EasingFunction.EASINGMODE_EASEIN:
  21893. return this.easeInCore(gradient);
  21894. case EasingFunction.EASINGMODE_EASEOUT:
  21895. return (1 - this.easeInCore(1 - gradient));
  21896. }
  21897. if (gradient >= 0.5) {
  21898. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  21899. }
  21900. return (this.easeInCore(gradient * 2) * 0.5);
  21901. };
  21902. //Statics
  21903. EasingFunction._EASINGMODE_EASEIN = 0;
  21904. EasingFunction._EASINGMODE_EASEOUT = 1;
  21905. EasingFunction._EASINGMODE_EASEINOUT = 2;
  21906. return EasingFunction;
  21907. })();
  21908. BABYLON.EasingFunction = EasingFunction;
  21909. var CircleEase = (function (_super) {
  21910. __extends(CircleEase, _super);
  21911. function CircleEase() {
  21912. _super.apply(this, arguments);
  21913. }
  21914. CircleEase.prototype.easeInCore = function (gradient) {
  21915. gradient = Math.max(0, Math.min(1, gradient));
  21916. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  21917. };
  21918. return CircleEase;
  21919. })(EasingFunction);
  21920. BABYLON.CircleEase = CircleEase;
  21921. var BackEase = (function (_super) {
  21922. __extends(BackEase, _super);
  21923. function BackEase(amplitude) {
  21924. if (amplitude === void 0) { amplitude = 1; }
  21925. _super.call(this);
  21926. this.amplitude = amplitude;
  21927. }
  21928. BackEase.prototype.easeInCore = function (gradient) {
  21929. var num = Math.max(0, this.amplitude);
  21930. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  21931. };
  21932. return BackEase;
  21933. })(EasingFunction);
  21934. BABYLON.BackEase = BackEase;
  21935. var BounceEase = (function (_super) {
  21936. __extends(BounceEase, _super);
  21937. function BounceEase(bounces, bounciness) {
  21938. if (bounces === void 0) { bounces = 3; }
  21939. if (bounciness === void 0) { bounciness = 2; }
  21940. _super.call(this);
  21941. this.bounces = bounces;
  21942. this.bounciness = bounciness;
  21943. }
  21944. BounceEase.prototype.easeInCore = function (gradient) {
  21945. var y = Math.max(0.0, this.bounces);
  21946. var bounciness = this.bounciness;
  21947. if (bounciness <= 1.0) {
  21948. bounciness = 1.001;
  21949. }
  21950. var num9 = Math.pow(bounciness, y);
  21951. var num5 = 1.0 - bounciness;
  21952. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  21953. var num15 = gradient * num4;
  21954. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  21955. var num3 = Math.floor(num65);
  21956. var num13 = num3 + 1.0;
  21957. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  21958. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  21959. var num7 = (num8 + num12) * 0.5;
  21960. var num6 = gradient - num7;
  21961. var num2 = num7 - num8;
  21962. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  21963. };
  21964. return BounceEase;
  21965. })(EasingFunction);
  21966. BABYLON.BounceEase = BounceEase;
  21967. var CubicEase = (function (_super) {
  21968. __extends(CubicEase, _super);
  21969. function CubicEase() {
  21970. _super.apply(this, arguments);
  21971. }
  21972. CubicEase.prototype.easeInCore = function (gradient) {
  21973. return (gradient * gradient * gradient);
  21974. };
  21975. return CubicEase;
  21976. })(EasingFunction);
  21977. BABYLON.CubicEase = CubicEase;
  21978. var ElasticEase = (function (_super) {
  21979. __extends(ElasticEase, _super);
  21980. function ElasticEase(oscillations, springiness) {
  21981. if (oscillations === void 0) { oscillations = 3; }
  21982. if (springiness === void 0) { springiness = 3; }
  21983. _super.call(this);
  21984. this.oscillations = oscillations;
  21985. this.springiness = springiness;
  21986. }
  21987. ElasticEase.prototype.easeInCore = function (gradient) {
  21988. var num2;
  21989. var num3 = Math.max(0.0, this.oscillations);
  21990. var num = Math.max(0.0, this.springiness);
  21991. if (num == 0) {
  21992. num2 = gradient;
  21993. }
  21994. else {
  21995. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  21996. }
  21997. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  21998. };
  21999. return ElasticEase;
  22000. })(EasingFunction);
  22001. BABYLON.ElasticEase = ElasticEase;
  22002. var ExponentialEase = (function (_super) {
  22003. __extends(ExponentialEase, _super);
  22004. function ExponentialEase(exponent) {
  22005. if (exponent === void 0) { exponent = 2; }
  22006. _super.call(this);
  22007. this.exponent = exponent;
  22008. }
  22009. ExponentialEase.prototype.easeInCore = function (gradient) {
  22010. if (this.exponent <= 0) {
  22011. return gradient;
  22012. }
  22013. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  22014. };
  22015. return ExponentialEase;
  22016. })(EasingFunction);
  22017. BABYLON.ExponentialEase = ExponentialEase;
  22018. var PowerEase = (function (_super) {
  22019. __extends(PowerEase, _super);
  22020. function PowerEase(power) {
  22021. if (power === void 0) { power = 2; }
  22022. _super.call(this);
  22023. this.power = power;
  22024. }
  22025. PowerEase.prototype.easeInCore = function (gradient) {
  22026. var y = Math.max(0.0, this.power);
  22027. return Math.pow(gradient, y);
  22028. };
  22029. return PowerEase;
  22030. })(EasingFunction);
  22031. BABYLON.PowerEase = PowerEase;
  22032. var QuadraticEase = (function (_super) {
  22033. __extends(QuadraticEase, _super);
  22034. function QuadraticEase() {
  22035. _super.apply(this, arguments);
  22036. }
  22037. QuadraticEase.prototype.easeInCore = function (gradient) {
  22038. return (gradient * gradient);
  22039. };
  22040. return QuadraticEase;
  22041. })(EasingFunction);
  22042. BABYLON.QuadraticEase = QuadraticEase;
  22043. var QuarticEase = (function (_super) {
  22044. __extends(QuarticEase, _super);
  22045. function QuarticEase() {
  22046. _super.apply(this, arguments);
  22047. }
  22048. QuarticEase.prototype.easeInCore = function (gradient) {
  22049. return (gradient * gradient * gradient * gradient);
  22050. };
  22051. return QuarticEase;
  22052. })(EasingFunction);
  22053. BABYLON.QuarticEase = QuarticEase;
  22054. var QuinticEase = (function (_super) {
  22055. __extends(QuinticEase, _super);
  22056. function QuinticEase() {
  22057. _super.apply(this, arguments);
  22058. }
  22059. QuinticEase.prototype.easeInCore = function (gradient) {
  22060. return (gradient * gradient * gradient * gradient * gradient);
  22061. };
  22062. return QuinticEase;
  22063. })(EasingFunction);
  22064. BABYLON.QuinticEase = QuinticEase;
  22065. var SineEase = (function (_super) {
  22066. __extends(SineEase, _super);
  22067. function SineEase() {
  22068. _super.apply(this, arguments);
  22069. }
  22070. SineEase.prototype.easeInCore = function (gradient) {
  22071. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  22072. };
  22073. return SineEase;
  22074. })(EasingFunction);
  22075. BABYLON.SineEase = SineEase;
  22076. var BezierCurveEase = (function (_super) {
  22077. __extends(BezierCurveEase, _super);
  22078. function BezierCurveEase(x1, y1, x2, y2) {
  22079. if (x1 === void 0) { x1 = 0; }
  22080. if (y1 === void 0) { y1 = 0; }
  22081. if (x2 === void 0) { x2 = 1; }
  22082. if (y2 === void 0) { y2 = 1; }
  22083. _super.call(this);
  22084. this.x1 = x1;
  22085. this.y1 = y1;
  22086. this.x2 = x2;
  22087. this.y2 = y2;
  22088. }
  22089. BezierCurveEase.prototype.easeInCore = function (gradient) {
  22090. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  22091. };
  22092. return BezierCurveEase;
  22093. })(EasingFunction);
  22094. BABYLON.BezierCurveEase = BezierCurveEase;
  22095. })(BABYLON || (BABYLON = {}));
  22096. var BABYLON;
  22097. (function (BABYLON) {
  22098. var Bone = (function (_super) {
  22099. __extends(Bone, _super);
  22100. function Bone(name, skeleton, parentBone, matrix) {
  22101. _super.call(this, name, skeleton.getScene());
  22102. this.name = name;
  22103. this.children = new Array();
  22104. this.animations = new Array();
  22105. this._worldTransform = new BABYLON.Matrix();
  22106. this._absoluteTransform = new BABYLON.Matrix();
  22107. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  22108. this._skeleton = skeleton;
  22109. this._matrix = matrix;
  22110. this._baseMatrix = matrix;
  22111. skeleton.bones.push(this);
  22112. if (parentBone) {
  22113. this._parent = parentBone;
  22114. parentBone.children.push(this);
  22115. }
  22116. else {
  22117. this._parent = null;
  22118. }
  22119. this._updateDifferenceMatrix();
  22120. }
  22121. // Members
  22122. Bone.prototype.getParent = function () {
  22123. return this._parent;
  22124. };
  22125. Bone.prototype.getLocalMatrix = function () {
  22126. return this._matrix;
  22127. };
  22128. Bone.prototype.getBaseMatrix = function () {
  22129. return this._baseMatrix;
  22130. };
  22131. Bone.prototype.getWorldMatrix = function () {
  22132. return this._worldTransform;
  22133. };
  22134. Bone.prototype.getInvertedAbsoluteTransform = function () {
  22135. return this._invertedAbsoluteTransform;
  22136. };
  22137. Bone.prototype.getAbsoluteMatrix = function () {
  22138. var matrix = this._matrix.clone();
  22139. var parent = this._parent;
  22140. while (parent) {
  22141. matrix = matrix.multiply(parent.getLocalMatrix());
  22142. parent = parent.getParent();
  22143. }
  22144. return matrix;
  22145. };
  22146. // Methods
  22147. Bone.prototype.updateMatrix = function (matrix) {
  22148. this._matrix = matrix;
  22149. this._skeleton._markAsDirty();
  22150. this._updateDifferenceMatrix();
  22151. };
  22152. Bone.prototype._updateDifferenceMatrix = function () {
  22153. if (this._parent) {
  22154. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  22155. }
  22156. else {
  22157. this._absoluteTransform.copyFrom(this._matrix);
  22158. }
  22159. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  22160. for (var index = 0; index < this.children.length; index++) {
  22161. this.children[index]._updateDifferenceMatrix();
  22162. }
  22163. };
  22164. Bone.prototype.markAsDirty = function () {
  22165. this._currentRenderId++;
  22166. this._skeleton._markAsDirty();
  22167. };
  22168. return Bone;
  22169. })(BABYLON.Node);
  22170. BABYLON.Bone = Bone;
  22171. })(BABYLON || (BABYLON = {}));
  22172. var BABYLON;
  22173. (function (BABYLON) {
  22174. var Skeleton = (function () {
  22175. function Skeleton(name, id, scene) {
  22176. this.name = name;
  22177. this.id = id;
  22178. this.bones = new Array();
  22179. this._isDirty = true;
  22180. this._identity = BABYLON.Matrix.Identity();
  22181. this._ranges = new Array();
  22182. this.bones = [];
  22183. this._scene = scene;
  22184. scene.skeletons.push(this);
  22185. this.prepare();
  22186. //make sure it will recalculate the matrix next time prepare is called.
  22187. this._isDirty = true;
  22188. }
  22189. // Members
  22190. Skeleton.prototype.getTransformMatrices = function () {
  22191. return this._transformMatrices;
  22192. };
  22193. Skeleton.prototype.getScene = function () {
  22194. return this._scene;
  22195. };
  22196. // Methods
  22197. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  22198. this._ranges.push(new BABYLON.AnimationRange(name, from, to));
  22199. };
  22200. Skeleton.prototype.deleteAnimationRange = function (name) {
  22201. for (var index = 0; index < this._ranges.length; index++) {
  22202. if (this._ranges[index].name === name) {
  22203. this._ranges.splice(index, 1);
  22204. return;
  22205. }
  22206. }
  22207. };
  22208. Skeleton.prototype.getAnimationRange = function (name) {
  22209. for (var index = 0; index < this._ranges.length; index++) {
  22210. if (this._ranges[index].name === name) {
  22211. return this._ranges[index];
  22212. }
  22213. }
  22214. return null;
  22215. };
  22216. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  22217. var range = this.getAnimationRange(name);
  22218. if (!range) {
  22219. return null;
  22220. }
  22221. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  22222. };
  22223. Skeleton.prototype._markAsDirty = function () {
  22224. this._isDirty = true;
  22225. };
  22226. Skeleton.prototype.prepare = function () {
  22227. if (!this._isDirty) {
  22228. return;
  22229. }
  22230. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  22231. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  22232. }
  22233. for (var index = 0; index < this.bones.length; index++) {
  22234. var bone = this.bones[index];
  22235. var parentBone = bone.getParent();
  22236. if (parentBone) {
  22237. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  22238. }
  22239. else {
  22240. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  22241. }
  22242. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  22243. }
  22244. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  22245. this._isDirty = false;
  22246. this._scene._activeBones += this.bones.length;
  22247. };
  22248. Skeleton.prototype.getAnimatables = function () {
  22249. if (!this._animatables || this._animatables.length !== this.bones.length) {
  22250. this._animatables = [];
  22251. for (var index = 0; index < this.bones.length; index++) {
  22252. this._animatables.push(this.bones[index]);
  22253. }
  22254. }
  22255. return this._animatables;
  22256. };
  22257. Skeleton.prototype.clone = function (name, id) {
  22258. var result = new Skeleton(name, id || name, this._scene);
  22259. for (var index = 0; index < this.bones.length; index++) {
  22260. var source = this.bones[index];
  22261. var parentBone = null;
  22262. if (source.getParent()) {
  22263. var parentIndex = this.bones.indexOf(source.getParent());
  22264. parentBone = result.bones[parentIndex];
  22265. }
  22266. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  22267. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  22268. }
  22269. return result;
  22270. };
  22271. Skeleton.prototype.dispose = function () {
  22272. // Animations
  22273. this.getScene().stopAnimation(this);
  22274. // Remove from scene
  22275. this.getScene().removeSkeleton(this);
  22276. };
  22277. return Skeleton;
  22278. })();
  22279. BABYLON.Skeleton = Skeleton;
  22280. })(BABYLON || (BABYLON = {}));
  22281. var BABYLON;
  22282. (function (BABYLON) {
  22283. var PostProcess = (function () {
  22284. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines, textureType) {
  22285. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  22286. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  22287. this.name = name;
  22288. this.width = -1;
  22289. this.height = -1;
  22290. this._reusable = false;
  22291. this._textures = new BABYLON.SmartArray(2);
  22292. this._currentRenderTextureInd = 0;
  22293. if (camera != null) {
  22294. this._camera = camera;
  22295. this._scene = camera.getScene();
  22296. camera.attachPostProcess(this);
  22297. this._engine = this._scene.getEngine();
  22298. }
  22299. else {
  22300. this._engine = engine;
  22301. }
  22302. this._renderRatio = ratio;
  22303. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  22304. this._reusable = reusable || false;
  22305. this._textureType = textureType;
  22306. samplers = samplers || [];
  22307. samplers.push("textureSampler");
  22308. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, defines !== undefined ? defines : "");
  22309. }
  22310. PostProcess.prototype.isReusable = function () {
  22311. return this._reusable;
  22312. };
  22313. PostProcess.prototype.activate = function (camera, sourceTexture) {
  22314. camera = camera || this._camera;
  22315. var scene = camera.getScene();
  22316. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  22317. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  22318. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  22319. desiredWidth = this._renderRatio.width || BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  22320. desiredHeight = this._renderRatio.height || BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  22321. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  22322. if (this._textures.length > 0) {
  22323. for (var i = 0; i < this._textures.length; i++) {
  22324. this._engine._releaseTexture(this._textures.data[i]);
  22325. }
  22326. this._textures.reset();
  22327. }
  22328. this.width = desiredWidth;
  22329. this.height = desiredHeight;
  22330. 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 }));
  22331. if (this._reusable) {
  22332. 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 }));
  22333. }
  22334. if (this.onSizeChanged) {
  22335. this.onSizeChanged();
  22336. }
  22337. }
  22338. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  22339. if (this.onActivate) {
  22340. this.onActivate(camera);
  22341. }
  22342. // Clear
  22343. if (this.clearColor) {
  22344. this._engine.clear(this.clearColor, true, true);
  22345. }
  22346. else {
  22347. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  22348. }
  22349. if (this._reusable) {
  22350. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  22351. }
  22352. };
  22353. PostProcess.prototype.apply = function () {
  22354. // Check
  22355. if (!this._effect.isReady())
  22356. return null;
  22357. // States
  22358. this._engine.enableEffect(this._effect);
  22359. this._engine.setState(false);
  22360. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  22361. this._engine.setDepthBuffer(false);
  22362. this._engine.setDepthWrite(false);
  22363. // Texture
  22364. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  22365. // Parameters
  22366. if (this.onApply) {
  22367. this.onApply(this._effect);
  22368. }
  22369. return this._effect;
  22370. };
  22371. PostProcess.prototype.dispose = function (camera) {
  22372. camera = camera || this._camera;
  22373. if (this._textures.length > 0) {
  22374. for (var i = 0; i < this._textures.length; i++) {
  22375. this._engine._releaseTexture(this._textures.data[i]);
  22376. }
  22377. this._textures.reset();
  22378. }
  22379. if (!camera) {
  22380. return;
  22381. }
  22382. camera.detachPostProcess(this);
  22383. var index = camera._postProcesses.indexOf(this);
  22384. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  22385. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  22386. }
  22387. };
  22388. return PostProcess;
  22389. })();
  22390. BABYLON.PostProcess = PostProcess;
  22391. })(BABYLON || (BABYLON = {}));
  22392. var BABYLON;
  22393. (function (BABYLON) {
  22394. var PostProcessManager = (function () {
  22395. function PostProcessManager(scene) {
  22396. this._vertexDeclaration = [2];
  22397. this._vertexStrideSize = 2 * 4;
  22398. this._scene = scene;
  22399. }
  22400. PostProcessManager.prototype._prepareBuffers = function () {
  22401. if (this._vertexBuffer) {
  22402. return;
  22403. }
  22404. // VBO
  22405. var vertices = [];
  22406. vertices.push(1, 1);
  22407. vertices.push(-1, 1);
  22408. vertices.push(-1, -1);
  22409. vertices.push(1, -1);
  22410. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  22411. // Indices
  22412. var indices = [];
  22413. indices.push(0);
  22414. indices.push(1);
  22415. indices.push(2);
  22416. indices.push(0);
  22417. indices.push(2);
  22418. indices.push(3);
  22419. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  22420. };
  22421. // Methods
  22422. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  22423. var postProcesses = this._scene.activeCamera._postProcesses;
  22424. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  22425. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  22426. return false;
  22427. }
  22428. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  22429. return true;
  22430. };
  22431. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  22432. var engine = this._scene.getEngine();
  22433. for (var index = 0; index < postProcesses.length; index++) {
  22434. if (index < postProcesses.length - 1) {
  22435. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  22436. }
  22437. else {
  22438. if (targetTexture) {
  22439. engine.bindFramebuffer(targetTexture);
  22440. }
  22441. else {
  22442. engine.restoreDefaultFramebuffer();
  22443. }
  22444. }
  22445. var pp = postProcesses[index];
  22446. var effect = pp.apply();
  22447. if (effect) {
  22448. if (pp.onBeforeRender) {
  22449. pp.onBeforeRender(effect);
  22450. }
  22451. // VBOs
  22452. this._prepareBuffers();
  22453. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  22454. // Draw order
  22455. engine.draw(true, 0, 6);
  22456. if (pp.onAfterRender) {
  22457. pp.onAfterRender(effect);
  22458. }
  22459. }
  22460. }
  22461. // Restore depth buffer
  22462. engine.setDepthBuffer(true);
  22463. engine.setDepthWrite(true);
  22464. };
  22465. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  22466. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  22467. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  22468. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  22469. return;
  22470. }
  22471. var engine = this._scene.getEngine();
  22472. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  22473. if (index < postProcessesTakenIndices.length - 1) {
  22474. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  22475. }
  22476. else {
  22477. if (targetTexture) {
  22478. engine.bindFramebuffer(targetTexture, faceIndex);
  22479. }
  22480. else {
  22481. engine.restoreDefaultFramebuffer();
  22482. }
  22483. }
  22484. if (doNotPresent) {
  22485. break;
  22486. }
  22487. var pp = postProcesses[postProcessesTakenIndices[index]];
  22488. var effect = pp.apply();
  22489. if (effect) {
  22490. if (pp.onBeforeRender) {
  22491. pp.onBeforeRender(effect);
  22492. }
  22493. // VBOs
  22494. this._prepareBuffers();
  22495. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  22496. // Draw order
  22497. engine.draw(true, 0, 6);
  22498. if (pp.onAfterRender) {
  22499. pp.onAfterRender(effect);
  22500. }
  22501. }
  22502. }
  22503. // Restore depth buffer
  22504. engine.setDepthBuffer(true);
  22505. engine.setDepthWrite(true);
  22506. };
  22507. PostProcessManager.prototype.dispose = function () {
  22508. if (this._vertexBuffer) {
  22509. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  22510. this._vertexBuffer = null;
  22511. }
  22512. if (this._indexBuffer) {
  22513. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  22514. this._indexBuffer = null;
  22515. }
  22516. };
  22517. return PostProcessManager;
  22518. })();
  22519. BABYLON.PostProcessManager = PostProcessManager;
  22520. })(BABYLON || (BABYLON = {}));
  22521. var BABYLON;
  22522. (function (BABYLON) {
  22523. var PassPostProcess = (function (_super) {
  22524. __extends(PassPostProcess, _super);
  22525. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  22526. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  22527. }
  22528. return PassPostProcess;
  22529. })(BABYLON.PostProcess);
  22530. BABYLON.PassPostProcess = PassPostProcess;
  22531. })(BABYLON || (BABYLON = {}));
  22532. var BABYLON;
  22533. (function (BABYLON) {
  22534. var PhysicsEngine = (function () {
  22535. function PhysicsEngine(plugin) {
  22536. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  22537. }
  22538. PhysicsEngine.prototype._initialize = function (gravity) {
  22539. this._currentPlugin.initialize();
  22540. this._setGravity(gravity);
  22541. };
  22542. PhysicsEngine.prototype._runOneStep = function (delta) {
  22543. if (delta > 0.1) {
  22544. delta = 0.1;
  22545. }
  22546. else if (delta <= 0) {
  22547. delta = 1.0 / 60.0;
  22548. }
  22549. this._currentPlugin.runOneStep(delta);
  22550. };
  22551. PhysicsEngine.prototype._setGravity = function (gravity) {
  22552. this.gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  22553. this._currentPlugin.setGravity(this.gravity);
  22554. };
  22555. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  22556. return this._currentPlugin.registerMesh(mesh, impostor, options);
  22557. };
  22558. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  22559. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  22560. };
  22561. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  22562. this._currentPlugin.unregisterMesh(mesh);
  22563. };
  22564. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  22565. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  22566. };
  22567. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  22568. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  22569. };
  22570. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  22571. this._currentPlugin.updateBodyPosition(mesh);
  22572. };
  22573. PhysicsEngine.prototype.dispose = function () {
  22574. this._currentPlugin.dispose();
  22575. };
  22576. PhysicsEngine.prototype.isSupported = function () {
  22577. return this._currentPlugin.isSupported();
  22578. };
  22579. PhysicsEngine.prototype.getPhysicsBodyOfMesh = function (mesh) {
  22580. return this._currentPlugin.getPhysicsBodyOfMesh(mesh);
  22581. };
  22582. // Statics
  22583. PhysicsEngine.NoImpostor = 0;
  22584. PhysicsEngine.SphereImpostor = 1;
  22585. PhysicsEngine.BoxImpostor = 2;
  22586. PhysicsEngine.PlaneImpostor = 3;
  22587. PhysicsEngine.MeshImpostor = 4;
  22588. PhysicsEngine.CapsuleImpostor = 5;
  22589. PhysicsEngine.ConeImpostor = 6;
  22590. PhysicsEngine.CylinderImpostor = 7;
  22591. PhysicsEngine.ConvexHullImpostor = 8;
  22592. PhysicsEngine.HeightmapImpostor = 9;
  22593. PhysicsEngine.Epsilon = 0.001;
  22594. return PhysicsEngine;
  22595. })();
  22596. BABYLON.PhysicsEngine = PhysicsEngine;
  22597. })(BABYLON || (BABYLON = {}));
  22598. var BABYLON;
  22599. (function (BABYLON) {
  22600. var VertexData = (function () {
  22601. function VertexData() {
  22602. }
  22603. VertexData.prototype.set = function (data, kind) {
  22604. switch (kind) {
  22605. case BABYLON.VertexBuffer.PositionKind:
  22606. this.positions = data;
  22607. break;
  22608. case BABYLON.VertexBuffer.NormalKind:
  22609. this.normals = data;
  22610. break;
  22611. case BABYLON.VertexBuffer.UVKind:
  22612. this.uvs = data;
  22613. break;
  22614. case BABYLON.VertexBuffer.UV2Kind:
  22615. this.uvs2 = data;
  22616. break;
  22617. case BABYLON.VertexBuffer.UV3Kind:
  22618. this.uvs3 = data;
  22619. break;
  22620. case BABYLON.VertexBuffer.UV4Kind:
  22621. this.uvs4 = data;
  22622. break;
  22623. case BABYLON.VertexBuffer.UV5Kind:
  22624. this.uvs5 = data;
  22625. break;
  22626. case BABYLON.VertexBuffer.UV6Kind:
  22627. this.uvs6 = data;
  22628. break;
  22629. case BABYLON.VertexBuffer.ColorKind:
  22630. this.colors = data;
  22631. break;
  22632. case BABYLON.VertexBuffer.MatricesIndicesKind:
  22633. this.matricesIndices = data;
  22634. break;
  22635. case BABYLON.VertexBuffer.MatricesWeightsKind:
  22636. this.matricesWeights = data;
  22637. break;
  22638. }
  22639. };
  22640. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  22641. this._applyTo(mesh, updatable);
  22642. };
  22643. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  22644. this._applyTo(geometry, updatable);
  22645. };
  22646. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  22647. this._update(mesh);
  22648. };
  22649. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  22650. this._update(geometry);
  22651. };
  22652. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  22653. if (this.positions) {
  22654. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  22655. }
  22656. if (this.normals) {
  22657. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  22658. }
  22659. if (this.uvs) {
  22660. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  22661. }
  22662. if (this.uvs2) {
  22663. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  22664. }
  22665. if (this.uvs3) {
  22666. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  22667. }
  22668. if (this.uvs4) {
  22669. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  22670. }
  22671. if (this.uvs5) {
  22672. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  22673. }
  22674. if (this.uvs6) {
  22675. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  22676. }
  22677. if (this.colors) {
  22678. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  22679. }
  22680. if (this.matricesIndices) {
  22681. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  22682. }
  22683. if (this.matricesWeights) {
  22684. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  22685. }
  22686. if (this.indices) {
  22687. meshOrGeometry.setIndices(this.indices);
  22688. }
  22689. };
  22690. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  22691. if (this.positions) {
  22692. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  22693. }
  22694. if (this.normals) {
  22695. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  22696. }
  22697. if (this.uvs) {
  22698. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  22699. }
  22700. if (this.uvs2) {
  22701. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  22702. }
  22703. if (this.uvs3) {
  22704. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  22705. }
  22706. if (this.uvs4) {
  22707. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  22708. }
  22709. if (this.uvs5) {
  22710. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  22711. }
  22712. if (this.uvs6) {
  22713. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  22714. }
  22715. if (this.colors) {
  22716. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  22717. }
  22718. if (this.matricesIndices) {
  22719. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  22720. }
  22721. if (this.matricesWeights) {
  22722. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  22723. }
  22724. if (this.indices) {
  22725. meshOrGeometry.setIndices(this.indices);
  22726. }
  22727. };
  22728. VertexData.prototype.transform = function (matrix) {
  22729. var transformed = BABYLON.Vector3.Zero();
  22730. var index;
  22731. if (this.positions) {
  22732. var position = BABYLON.Vector3.Zero();
  22733. for (index = 0; index < this.positions.length; index += 3) {
  22734. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  22735. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  22736. this.positions[index] = transformed.x;
  22737. this.positions[index + 1] = transformed.y;
  22738. this.positions[index + 2] = transformed.z;
  22739. }
  22740. }
  22741. if (this.normals) {
  22742. var normal = BABYLON.Vector3.Zero();
  22743. for (index = 0; index < this.normals.length; index += 3) {
  22744. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  22745. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  22746. this.normals[index] = transformed.x;
  22747. this.normals[index + 1] = transformed.y;
  22748. this.normals[index + 2] = transformed.z;
  22749. }
  22750. }
  22751. };
  22752. VertexData.prototype.merge = function (other) {
  22753. var index;
  22754. if (other.indices) {
  22755. if (!this.indices) {
  22756. this.indices = [];
  22757. }
  22758. var offset = this.positions ? this.positions.length / 3 : 0;
  22759. for (index = 0; index < other.indices.length; index++) {
  22760. this.indices.push(other.indices[index] + offset);
  22761. }
  22762. }
  22763. if (other.positions) {
  22764. if (!this.positions) {
  22765. this.positions = [];
  22766. }
  22767. for (index = 0; index < other.positions.length; index++) {
  22768. this.positions.push(other.positions[index]);
  22769. }
  22770. }
  22771. if (other.normals) {
  22772. if (!this.normals) {
  22773. this.normals = [];
  22774. }
  22775. for (index = 0; index < other.normals.length; index++) {
  22776. this.normals.push(other.normals[index]);
  22777. }
  22778. }
  22779. if (other.uvs) {
  22780. if (!this.uvs) {
  22781. this.uvs = [];
  22782. }
  22783. for (index = 0; index < other.uvs.length; index++) {
  22784. this.uvs.push(other.uvs[index]);
  22785. }
  22786. }
  22787. if (other.uvs2) {
  22788. if (!this.uvs2) {
  22789. this.uvs2 = [];
  22790. }
  22791. for (index = 0; index < other.uvs2.length; index++) {
  22792. this.uvs2.push(other.uvs2[index]);
  22793. }
  22794. }
  22795. if (other.uvs3) {
  22796. if (!this.uvs3) {
  22797. this.uvs3 = [];
  22798. }
  22799. for (index = 0; index < other.uvs3.length; index++) {
  22800. this.uvs3.push(other.uvs3[index]);
  22801. }
  22802. }
  22803. if (other.uvs4) {
  22804. if (!this.uvs4) {
  22805. this.uvs4 = [];
  22806. }
  22807. for (index = 0; index < other.uvs4.length; index++) {
  22808. this.uvs4.push(other.uvs4[index]);
  22809. }
  22810. }
  22811. if (other.uvs5) {
  22812. if (!this.uvs5) {
  22813. this.uvs5 = [];
  22814. }
  22815. for (index = 0; index < other.uvs5.length; index++) {
  22816. this.uvs5.push(other.uvs5[index]);
  22817. }
  22818. }
  22819. if (other.uvs6) {
  22820. if (!this.uvs6) {
  22821. this.uvs6 = [];
  22822. }
  22823. for (index = 0; index < other.uvs6.length; index++) {
  22824. this.uvs6.push(other.uvs6[index]);
  22825. }
  22826. }
  22827. if (other.matricesIndices) {
  22828. if (!this.matricesIndices) {
  22829. this.matricesIndices = [];
  22830. }
  22831. for (index = 0; index < other.matricesIndices.length; index++) {
  22832. this.matricesIndices.push(other.matricesIndices[index]);
  22833. }
  22834. }
  22835. if (other.matricesWeights) {
  22836. if (!this.matricesWeights) {
  22837. this.matricesWeights = [];
  22838. }
  22839. for (index = 0; index < other.matricesWeights.length; index++) {
  22840. this.matricesWeights.push(other.matricesWeights[index]);
  22841. }
  22842. }
  22843. if (other.colors) {
  22844. if (!this.colors) {
  22845. this.colors = [];
  22846. }
  22847. for (index = 0; index < other.colors.length; index++) {
  22848. this.colors.push(other.colors[index]);
  22849. }
  22850. }
  22851. };
  22852. // Statics
  22853. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  22854. return VertexData._ExtractFrom(mesh, copyWhenShared);
  22855. };
  22856. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  22857. return VertexData._ExtractFrom(geometry, copyWhenShared);
  22858. };
  22859. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  22860. var result = new VertexData();
  22861. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  22862. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  22863. }
  22864. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22865. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  22866. }
  22867. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  22868. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  22869. }
  22870. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  22871. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  22872. }
  22873. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  22874. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  22875. }
  22876. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  22877. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  22878. }
  22879. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  22880. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  22881. }
  22882. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  22883. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  22884. }
  22885. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  22886. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  22887. }
  22888. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  22889. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  22890. }
  22891. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  22892. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  22893. }
  22894. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  22895. return result;
  22896. };
  22897. VertexData.CreateRibbon = function (options) {
  22898. var pathArray = options.pathArray;
  22899. var closeArray = options.closeArray || false;
  22900. var closePath = options.closePath || false;
  22901. var defaultOffset = Math.floor(pathArray[0].length / 2);
  22902. var offset = options.offset || defaultOffset;
  22903. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  22904. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  22905. var positions = [];
  22906. var indices = [];
  22907. var normals = [];
  22908. var uvs = [];
  22909. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  22910. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  22911. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  22912. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  22913. var minlg; // minimal length among all paths from pathArray
  22914. var lg = []; // array of path lengths : nb of vertex per path
  22915. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  22916. var p; // path iterator
  22917. var i; // point iterator
  22918. var j; // point iterator
  22919. // if single path in pathArray
  22920. if (pathArray.length < 2) {
  22921. var ar1 = [];
  22922. var ar2 = [];
  22923. for (i = 0; i < pathArray[0].length - offset; i++) {
  22924. ar1.push(pathArray[0][i]);
  22925. ar2.push(pathArray[0][i + offset]);
  22926. }
  22927. pathArray = [ar1, ar2];
  22928. }
  22929. // positions and horizontal distances (u)
  22930. var idc = 0;
  22931. var closePathCorr = (closePath) ? 1 : 0;
  22932. var path;
  22933. var l;
  22934. minlg = pathArray[0].length;
  22935. var vectlg;
  22936. var dist;
  22937. for (p = 0; p < pathArray.length; p++) {
  22938. uTotalDistance[p] = 0;
  22939. us[p] = [0];
  22940. path = pathArray[p];
  22941. l = path.length;
  22942. minlg = (minlg < l) ? minlg : l;
  22943. j = 0;
  22944. while (j < l) {
  22945. positions.push(path[j].x, path[j].y, path[j].z);
  22946. if (j > 0) {
  22947. vectlg = path[j].subtract(path[j - 1]).length();
  22948. dist = vectlg + uTotalDistance[p];
  22949. us[p].push(dist);
  22950. uTotalDistance[p] = dist;
  22951. }
  22952. j++;
  22953. }
  22954. if (closePath) {
  22955. j--;
  22956. positions.push(path[0].x, path[0].y, path[0].z);
  22957. vectlg = path[j].subtract(path[0]).length();
  22958. dist = vectlg + uTotalDistance[p];
  22959. us[p].push(dist);
  22960. uTotalDistance[p] = dist;
  22961. }
  22962. lg[p] = l + closePathCorr;
  22963. idx[p] = idc;
  22964. idc += (l + closePathCorr);
  22965. }
  22966. // vertical distances (v)
  22967. var path1;
  22968. var path2;
  22969. var vertex1;
  22970. var vertex2;
  22971. for (i = 0; i < minlg + closePathCorr; i++) {
  22972. vTotalDistance[i] = 0;
  22973. vs[i] = [0];
  22974. for (p = 0; p < pathArray.length - 1; p++) {
  22975. path1 = pathArray[p];
  22976. path2 = pathArray[p + 1];
  22977. if (i === minlg) {
  22978. vertex1 = path1[0];
  22979. vertex2 = path2[0];
  22980. }
  22981. else {
  22982. vertex1 = path1[i];
  22983. vertex2 = path2[i];
  22984. }
  22985. vectlg = vertex2.subtract(vertex1).length();
  22986. dist = vectlg + vTotalDistance[i];
  22987. vs[i].push(dist);
  22988. vTotalDistance[i] = dist;
  22989. }
  22990. if (closeArray) {
  22991. path1 = pathArray[p];
  22992. path2 = pathArray[0];
  22993. if (i === minlg) {
  22994. vertex2 = path2[0];
  22995. }
  22996. vectlg = vertex2.subtract(vertex1).length();
  22997. dist = vectlg + vTotalDistance[i];
  22998. vTotalDistance[i] = dist;
  22999. }
  23000. }
  23001. // uvs
  23002. var u;
  23003. var v;
  23004. for (p = 0; p < pathArray.length; p++) {
  23005. for (i = 0; i < minlg + closePathCorr; i++) {
  23006. u = us[p][i] / uTotalDistance[p];
  23007. v = vs[i][p] / vTotalDistance[i];
  23008. uvs.push(u, v);
  23009. }
  23010. }
  23011. // indices
  23012. p = 0; // path index
  23013. var pi = 0; // positions array index
  23014. var l1 = lg[p] - 1; // path1 length
  23015. var l2 = lg[p + 1] - 1; // path2 length
  23016. var min = (l1 < l2) ? l1 : l2; // current path stop index
  23017. var shft = idx[1] - idx[0]; // shift
  23018. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  23019. while (pi <= min && p < path1nb) {
  23020. // 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
  23021. indices.push(pi, pi + shft, pi + 1);
  23022. indices.push(pi + shft + 1, pi + 1, pi + shft);
  23023. pi += 1;
  23024. if (pi === min) {
  23025. p++;
  23026. if (p === lg.length - 1) {
  23027. shft = idx[0] - idx[p];
  23028. l1 = lg[p] - 1;
  23029. l2 = lg[0] - 1;
  23030. }
  23031. else {
  23032. shft = idx[p + 1] - idx[p];
  23033. l1 = lg[p] - 1;
  23034. l2 = lg[p + 1] - 1;
  23035. }
  23036. pi = idx[p];
  23037. min = (l1 < l2) ? l1 + pi : l2 + pi;
  23038. }
  23039. }
  23040. // normals
  23041. VertexData.ComputeNormals(positions, indices, normals);
  23042. if (closePath) {
  23043. var indexFirst = 0;
  23044. var indexLast = 0;
  23045. for (p = 0; p < pathArray.length; p++) {
  23046. indexFirst = idx[p] * 3;
  23047. if (p + 1 < pathArray.length) {
  23048. indexLast = (idx[p + 1] - 1) * 3;
  23049. }
  23050. else {
  23051. indexLast = normals.length - 3;
  23052. }
  23053. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  23054. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  23055. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  23056. normals[indexLast] = normals[indexFirst];
  23057. normals[indexLast + 1] = normals[indexFirst + 1];
  23058. normals[indexLast + 2] = normals[indexFirst + 2];
  23059. }
  23060. }
  23061. // sides
  23062. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23063. // Result
  23064. var vertexData = new VertexData();
  23065. vertexData.indices = indices;
  23066. vertexData.positions = positions;
  23067. vertexData.normals = normals;
  23068. vertexData.uvs = uvs;
  23069. if (closePath) {
  23070. vertexData._idx = idx;
  23071. }
  23072. return vertexData;
  23073. };
  23074. VertexData.CreateBox = function (options) {
  23075. var normalsSource = [
  23076. new BABYLON.Vector3(0, 0, 1),
  23077. new BABYLON.Vector3(0, 0, -1),
  23078. new BABYLON.Vector3(1, 0, 0),
  23079. new BABYLON.Vector3(-1, 0, 0),
  23080. new BABYLON.Vector3(0, 1, 0),
  23081. new BABYLON.Vector3(0, -1, 0)
  23082. ];
  23083. var indices = [];
  23084. var positions = [];
  23085. var normals = [];
  23086. var uvs = [];
  23087. var width = options.width || options.size || 1;
  23088. var height = options.height || options.size || 1;
  23089. var depth = options.depth || options.size || 1;
  23090. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23091. var faceUV = options.faceUV || new Array(6);
  23092. var faceColors = options.faceColors;
  23093. var colors = [];
  23094. // default face colors and UV if undefined
  23095. for (var f = 0; f < 6; f++) {
  23096. if (faceUV[f] === undefined) {
  23097. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  23098. }
  23099. if (faceColors && faceColors[f] === undefined) {
  23100. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  23101. }
  23102. }
  23103. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  23104. // Create each face in turn.
  23105. for (var index = 0; index < normalsSource.length; index++) {
  23106. var normal = normalsSource[index];
  23107. // Get two vectors perpendicular to the face normal and to each other.
  23108. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  23109. var side2 = BABYLON.Vector3.Cross(normal, side1);
  23110. // Six indices (two triangles) per face.
  23111. var verticesLength = positions.length / 3;
  23112. indices.push(verticesLength);
  23113. indices.push(verticesLength + 1);
  23114. indices.push(verticesLength + 2);
  23115. indices.push(verticesLength);
  23116. indices.push(verticesLength + 2);
  23117. indices.push(verticesLength + 3);
  23118. // Four vertices per face.
  23119. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  23120. positions.push(vertex.x, vertex.y, vertex.z);
  23121. normals.push(normal.x, normal.y, normal.z);
  23122. uvs.push(faceUV[index].z, faceUV[index].w);
  23123. if (faceColors) {
  23124. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23125. }
  23126. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  23127. positions.push(vertex.x, vertex.y, vertex.z);
  23128. normals.push(normal.x, normal.y, normal.z);
  23129. uvs.push(faceUV[index].x, faceUV[index].w);
  23130. if (faceColors) {
  23131. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23132. }
  23133. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  23134. positions.push(vertex.x, vertex.y, vertex.z);
  23135. normals.push(normal.x, normal.y, normal.z);
  23136. uvs.push(faceUV[index].x, faceUV[index].y);
  23137. if (faceColors) {
  23138. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23139. }
  23140. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  23141. positions.push(vertex.x, vertex.y, vertex.z);
  23142. normals.push(normal.x, normal.y, normal.z);
  23143. uvs.push(faceUV[index].z, faceUV[index].y);
  23144. if (faceColors) {
  23145. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  23146. }
  23147. }
  23148. // sides
  23149. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23150. // Result
  23151. var vertexData = new VertexData();
  23152. vertexData.indices = indices;
  23153. vertexData.positions = positions;
  23154. vertexData.normals = normals;
  23155. vertexData.uvs = uvs;
  23156. if (faceColors) {
  23157. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  23158. vertexData.colors = totalColors;
  23159. }
  23160. return vertexData;
  23161. };
  23162. VertexData.CreateSphere = function (options) {
  23163. var segments = options.segments || 32;
  23164. var diameterX = options.diameterX || options.diameter || 1;
  23165. var diameterY = options.diameterY || options.diameter || 1;
  23166. var diameterZ = options.diameterZ || options.diameter || 1;
  23167. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  23168. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  23169. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23170. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  23171. var totalZRotationSteps = 2 + segments;
  23172. var totalYRotationSteps = 2 * totalZRotationSteps;
  23173. var indices = [];
  23174. var positions = [];
  23175. var normals = [];
  23176. var uvs = [];
  23177. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  23178. var normalizedZ = zRotationStep / totalZRotationSteps;
  23179. var angleZ = normalizedZ * Math.PI * slice;
  23180. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  23181. var normalizedY = yRotationStep / totalYRotationSteps;
  23182. var angleY = normalizedY * Math.PI * 2 * arc;
  23183. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  23184. var rotationY = BABYLON.Matrix.RotationY(angleY);
  23185. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  23186. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  23187. var vertex = complete.multiply(radius);
  23188. var normal = BABYLON.Vector3.Normalize(vertex);
  23189. positions.push(vertex.x, vertex.y, vertex.z);
  23190. normals.push(normal.x, normal.y, normal.z);
  23191. uvs.push(normalizedY, normalizedZ);
  23192. }
  23193. if (zRotationStep > 0) {
  23194. var verticesCount = positions.length / 3;
  23195. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  23196. indices.push((firstIndex));
  23197. indices.push((firstIndex + 1));
  23198. indices.push(firstIndex + totalYRotationSteps + 1);
  23199. indices.push((firstIndex + totalYRotationSteps + 1));
  23200. indices.push((firstIndex + 1));
  23201. indices.push((firstIndex + totalYRotationSteps + 2));
  23202. }
  23203. }
  23204. }
  23205. // Sides
  23206. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23207. // Result
  23208. var vertexData = new VertexData();
  23209. vertexData.indices = indices;
  23210. vertexData.positions = positions;
  23211. vertexData.normals = normals;
  23212. vertexData.uvs = uvs;
  23213. return vertexData;
  23214. };
  23215. // Cylinder and cone
  23216. VertexData.CreateCylinder = function (options) {
  23217. var height = options.height || 2;
  23218. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  23219. var diameterBottom = options.diameterBottom || options.diameter || 1;
  23220. var tessellation = options.tessellation || 24;
  23221. var subdivisions = options.subdivisions || 1;
  23222. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  23223. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23224. var faceUV = options.faceUV || new Array(3);
  23225. var faceColors = options.faceColors;
  23226. // default face colors and UV if undefined
  23227. for (var f = 0; f < 3; f++) {
  23228. if (faceColors && faceColors[f] === undefined) {
  23229. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  23230. }
  23231. if (faceUV && faceUV[f] === undefined) {
  23232. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  23233. }
  23234. }
  23235. var indices = [];
  23236. var positions = [];
  23237. var normals = [];
  23238. var uvs = [];
  23239. var colors = [];
  23240. var angle_step = Math.PI * 2 * arc / tessellation;
  23241. var angle;
  23242. var h;
  23243. var radius;
  23244. var tan = (diameterBottom - diameterTop) / 2 / height;
  23245. var ringVertex = BABYLON.Vector3.Zero();
  23246. var ringNormal = BABYLON.Vector3.Zero();
  23247. // positions, normals, uvs
  23248. var i;
  23249. var j;
  23250. for (i = 0; i <= subdivisions; i++) {
  23251. h = i / subdivisions;
  23252. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  23253. for (j = 0; j <= tessellation; j++) {
  23254. angle = j * angle_step;
  23255. ringVertex.x = Math.cos(-angle) * radius;
  23256. ringVertex.y = -height / 2 + h * height;
  23257. ringVertex.z = Math.sin(-angle) * radius;
  23258. if (diameterTop === 0 && i === subdivisions) {
  23259. // if no top cap, reuse former normals
  23260. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  23261. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  23262. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  23263. }
  23264. else {
  23265. ringNormal.x = ringVertex.x;
  23266. ringNormal.z = ringVertex.z;
  23267. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  23268. ringNormal.normalize();
  23269. }
  23270. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  23271. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  23272. uvs.push(faceUV[1].x + (faceUV[1].z - faceUV[1].x) * j / tessellation, faceUV[1].y + (faceUV[1].w - faceUV[1].y) * h);
  23273. if (faceColors) {
  23274. colors.push(faceColors[1].r, faceColors[1].g, faceColors[1].b, faceColors[1].a);
  23275. }
  23276. }
  23277. }
  23278. // indices
  23279. for (i = 0; i < subdivisions; i++) {
  23280. for (j = 0; j < tessellation; j++) {
  23281. var i0 = i * (tessellation + 1) + j;
  23282. var i1 = (i + 1) * (tessellation + 1) + j;
  23283. var i2 = i * (tessellation + 1) + (j + 1);
  23284. var i3 = (i + 1) * (tessellation + 1) + (j + 1);
  23285. indices.push(i0, i1, i2);
  23286. indices.push(i3, i2, i1);
  23287. }
  23288. }
  23289. // Caps
  23290. var createCylinderCap = function (isTop) {
  23291. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  23292. if (radius === 0) {
  23293. return;
  23294. }
  23295. // Cap positions, normals & uvs
  23296. var angle;
  23297. var circleVector;
  23298. var i;
  23299. var u = (isTop) ? faceUV[2] : faceUV[0];
  23300. var c;
  23301. if (faceColors) {
  23302. c = (isTop) ? faceColors[2] : faceColors[0];
  23303. }
  23304. // cap center
  23305. var vbase = positions.length / 3;
  23306. var offset = isTop ? height / 2 : -height / 2;
  23307. var center = new BABYLON.Vector3(0, offset, 0);
  23308. positions.push(center.x, center.y, center.z);
  23309. normals.push(0, isTop ? 1 : -1, 0);
  23310. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  23311. if (faceColors) {
  23312. colors.push(c.r, c.g, c.b, c.a);
  23313. }
  23314. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  23315. for (i = 0; i <= tessellation; i++) {
  23316. angle = Math.PI * 2 * i * arc / tessellation;
  23317. var cos = Math.cos(-angle);
  23318. var sin = Math.sin(-angle);
  23319. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  23320. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  23321. positions.push(circleVector.x, circleVector.y, circleVector.z);
  23322. normals.push(0, isTop ? 1 : -1, 0);
  23323. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  23324. if (faceColors) {
  23325. colors.push(c.r, c.g, c.b, c.a);
  23326. }
  23327. }
  23328. // Cap indices
  23329. for (i = 0; i < tessellation; i++) {
  23330. if (!isTop) {
  23331. indices.push(vbase);
  23332. indices.push(vbase + (i + 1));
  23333. indices.push(vbase + (i + 2));
  23334. }
  23335. else {
  23336. indices.push(vbase);
  23337. indices.push(vbase + (i + 2));
  23338. indices.push(vbase + (i + 1));
  23339. }
  23340. }
  23341. };
  23342. // add caps to geometry
  23343. createCylinderCap(false);
  23344. createCylinderCap(true);
  23345. // Sides
  23346. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23347. var vertexData = new VertexData();
  23348. vertexData.indices = indices;
  23349. vertexData.positions = positions;
  23350. vertexData.normals = normals;
  23351. vertexData.uvs = uvs;
  23352. if (faceColors) {
  23353. vertexData.colors = colors;
  23354. }
  23355. return vertexData;
  23356. };
  23357. VertexData.CreateTorus = function (options) {
  23358. var indices = [];
  23359. var positions = [];
  23360. var normals = [];
  23361. var uvs = [];
  23362. var diameter = options.diameter || 1;
  23363. var thickness = options.thickness || 0.5;
  23364. var tessellation = options.tessellation || 16;
  23365. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23366. var stride = tessellation + 1;
  23367. for (var i = 0; i <= tessellation; i++) {
  23368. var u = i / tessellation;
  23369. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  23370. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  23371. for (var j = 0; j <= tessellation; j++) {
  23372. var v = 1 - j / tessellation;
  23373. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  23374. var dx = Math.cos(innerAngle);
  23375. var dy = Math.sin(innerAngle);
  23376. // Create a vertex.
  23377. var normal = new BABYLON.Vector3(dx, dy, 0);
  23378. var position = normal.scale(thickness / 2);
  23379. var textureCoordinate = new BABYLON.Vector2(u, v);
  23380. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  23381. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  23382. positions.push(position.x, position.y, position.z);
  23383. normals.push(normal.x, normal.y, normal.z);
  23384. uvs.push(textureCoordinate.x, textureCoordinate.y);
  23385. // And create indices for two triangles.
  23386. var nextI = (i + 1) % stride;
  23387. var nextJ = (j + 1) % stride;
  23388. indices.push(i * stride + j);
  23389. indices.push(i * stride + nextJ);
  23390. indices.push(nextI * stride + j);
  23391. indices.push(i * stride + nextJ);
  23392. indices.push(nextI * stride + nextJ);
  23393. indices.push(nextI * stride + j);
  23394. }
  23395. }
  23396. // Sides
  23397. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23398. // Result
  23399. var vertexData = new VertexData();
  23400. vertexData.indices = indices;
  23401. vertexData.positions = positions;
  23402. vertexData.normals = normals;
  23403. vertexData.uvs = uvs;
  23404. return vertexData;
  23405. };
  23406. VertexData.CreateLines = function (options) {
  23407. var indices = [];
  23408. var positions = [];
  23409. var points = options.points;
  23410. for (var index = 0; index < points.length; index++) {
  23411. positions.push(points[index].x, points[index].y, points[index].z);
  23412. if (index > 0) {
  23413. indices.push(index - 1);
  23414. indices.push(index);
  23415. }
  23416. }
  23417. // Result
  23418. var vertexData = new VertexData();
  23419. vertexData.indices = indices;
  23420. vertexData.positions = positions;
  23421. return vertexData;
  23422. };
  23423. VertexData.CreateDashedLines = function (options) {
  23424. var dashSize = options.dashSize || 3;
  23425. var gapSize = options.gapSize || 1;
  23426. var dashNb = options.dashNb || 200;
  23427. var points = options.points;
  23428. var positions = new Array();
  23429. var indices = new Array();
  23430. var curvect = BABYLON.Vector3.Zero();
  23431. var lg = 0;
  23432. var nb = 0;
  23433. var shft = 0;
  23434. var dashshft = 0;
  23435. var curshft = 0;
  23436. var idx = 0;
  23437. var i = 0;
  23438. for (i = 0; i < points.length - 1; i++) {
  23439. points[i + 1].subtractToRef(points[i], curvect);
  23440. lg += curvect.length();
  23441. }
  23442. shft = lg / dashNb;
  23443. dashshft = dashSize * shft / (dashSize + gapSize);
  23444. for (i = 0; i < points.length - 1; i++) {
  23445. points[i + 1].subtractToRef(points[i], curvect);
  23446. nb = Math.floor(curvect.length() / shft);
  23447. curvect.normalize();
  23448. for (var j = 0; j < nb; j++) {
  23449. curshft = shft * j;
  23450. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  23451. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  23452. indices.push(idx, idx + 1);
  23453. idx += 2;
  23454. }
  23455. }
  23456. // Result
  23457. var vertexData = new VertexData();
  23458. vertexData.positions = positions;
  23459. vertexData.indices = indices;
  23460. return vertexData;
  23461. };
  23462. VertexData.CreateGround = function (options) {
  23463. var indices = [];
  23464. var positions = [];
  23465. var normals = [];
  23466. var uvs = [];
  23467. var row, col;
  23468. var width = options.width || 1;
  23469. var height = options.height || 1;
  23470. var subdivisions = options.subdivisions || 1;
  23471. for (row = 0; row <= subdivisions; row++) {
  23472. for (col = 0; col <= subdivisions; col++) {
  23473. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  23474. var normal = new BABYLON.Vector3(0, 1.0, 0);
  23475. positions.push(position.x, position.y, position.z);
  23476. normals.push(normal.x, normal.y, normal.z);
  23477. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  23478. }
  23479. }
  23480. for (row = 0; row < subdivisions; row++) {
  23481. for (col = 0; col < subdivisions; col++) {
  23482. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  23483. indices.push(col + 1 + row * (subdivisions + 1));
  23484. indices.push(col + row * (subdivisions + 1));
  23485. indices.push(col + (row + 1) * (subdivisions + 1));
  23486. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  23487. indices.push(col + row * (subdivisions + 1));
  23488. }
  23489. }
  23490. // Result
  23491. var vertexData = new VertexData();
  23492. vertexData.indices = indices;
  23493. vertexData.positions = positions;
  23494. vertexData.normals = normals;
  23495. vertexData.uvs = uvs;
  23496. return vertexData;
  23497. };
  23498. VertexData.CreateTiledGround = function (options) {
  23499. var xmin = options.xmin;
  23500. var zmin = options.zmin;
  23501. var xmax = options.xmax;
  23502. var zmax = options.zmax;
  23503. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  23504. var precision = options.precision || { w: 1, h: 1 };
  23505. var indices = [];
  23506. var positions = [];
  23507. var normals = [];
  23508. var uvs = [];
  23509. var row, col, tileRow, tileCol;
  23510. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  23511. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  23512. precision.w = (precision.w < 1) ? 1 : precision.w;
  23513. precision.h = (precision.h < 1) ? 1 : precision.h;
  23514. var tileSize = {
  23515. 'w': (xmax - xmin) / subdivisions.w,
  23516. 'h': (zmax - zmin) / subdivisions.h
  23517. };
  23518. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  23519. // Indices
  23520. var base = positions.length / 3;
  23521. var rowLength = precision.w + 1;
  23522. for (row = 0; row < precision.h; row++) {
  23523. for (col = 0; col < precision.w; col++) {
  23524. var square = [
  23525. base + col + row * rowLength,
  23526. base + (col + 1) + row * rowLength,
  23527. base + (col + 1) + (row + 1) * rowLength,
  23528. base + col + (row + 1) * rowLength
  23529. ];
  23530. indices.push(square[1]);
  23531. indices.push(square[2]);
  23532. indices.push(square[3]);
  23533. indices.push(square[0]);
  23534. indices.push(square[1]);
  23535. indices.push(square[3]);
  23536. }
  23537. }
  23538. // Position, normals and uvs
  23539. var position = BABYLON.Vector3.Zero();
  23540. var normal = new BABYLON.Vector3(0, 1.0, 0);
  23541. for (row = 0; row <= precision.h; row++) {
  23542. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  23543. for (col = 0; col <= precision.w; col++) {
  23544. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  23545. position.y = 0;
  23546. positions.push(position.x, position.y, position.z);
  23547. normals.push(normal.x, normal.y, normal.z);
  23548. uvs.push(col / precision.w, row / precision.h);
  23549. }
  23550. }
  23551. }
  23552. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  23553. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  23554. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  23555. }
  23556. }
  23557. // Result
  23558. var vertexData = new VertexData();
  23559. vertexData.indices = indices;
  23560. vertexData.positions = positions;
  23561. vertexData.normals = normals;
  23562. vertexData.uvs = uvs;
  23563. return vertexData;
  23564. };
  23565. VertexData.CreateGroundFromHeightMap = function (options) {
  23566. var indices = [];
  23567. var positions = [];
  23568. var normals = [];
  23569. var uvs = [];
  23570. var row, col;
  23571. // Vertices
  23572. for (row = 0; row <= options.subdivisions; row++) {
  23573. for (col = 0; col <= options.subdivisions; col++) {
  23574. 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));
  23575. // Compute height
  23576. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  23577. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  23578. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  23579. var r = options.buffer[pos] / 255.0;
  23580. var g = options.buffer[pos + 1] / 255.0;
  23581. var b = options.buffer[pos + 2] / 255.0;
  23582. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  23583. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  23584. // Add vertex
  23585. positions.push(position.x, position.y, position.z);
  23586. normals.push(0, 0, 0);
  23587. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  23588. }
  23589. }
  23590. // Indices
  23591. for (row = 0; row < options.subdivisions; row++) {
  23592. for (col = 0; col < options.subdivisions; col++) {
  23593. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  23594. indices.push(col + 1 + row * (options.subdivisions + 1));
  23595. indices.push(col + row * (options.subdivisions + 1));
  23596. indices.push(col + (row + 1) * (options.subdivisions + 1));
  23597. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  23598. indices.push(col + row * (options.subdivisions + 1));
  23599. }
  23600. }
  23601. // Normals
  23602. VertexData.ComputeNormals(positions, indices, normals);
  23603. // Result
  23604. var vertexData = new VertexData();
  23605. vertexData.indices = indices;
  23606. vertexData.positions = positions;
  23607. vertexData.normals = normals;
  23608. vertexData.uvs = uvs;
  23609. return vertexData;
  23610. };
  23611. VertexData.CreatePlane = function (options) {
  23612. var indices = [];
  23613. var positions = [];
  23614. var normals = [];
  23615. var uvs = [];
  23616. var width = options.width || options.size || 1;
  23617. var height = options.height || options.size || 1;
  23618. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23619. // Vertices
  23620. var halfWidth = width / 2.0;
  23621. var halfHeight = height / 2.0;
  23622. positions.push(-halfWidth, -halfHeight, 0);
  23623. normals.push(0, 0, -1.0);
  23624. uvs.push(0.0, 0.0);
  23625. positions.push(halfWidth, -halfHeight, 0);
  23626. normals.push(0, 0, -1.0);
  23627. uvs.push(1.0, 0.0);
  23628. positions.push(halfWidth, halfHeight, 0);
  23629. normals.push(0, 0, -1.0);
  23630. uvs.push(1.0, 1.0);
  23631. positions.push(-halfWidth, halfHeight, 0);
  23632. normals.push(0, 0, -1.0);
  23633. uvs.push(0.0, 1.0);
  23634. // Indices
  23635. indices.push(0);
  23636. indices.push(1);
  23637. indices.push(2);
  23638. indices.push(0);
  23639. indices.push(2);
  23640. indices.push(3);
  23641. // Sides
  23642. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23643. // Result
  23644. var vertexData = new VertexData();
  23645. vertexData.indices = indices;
  23646. vertexData.positions = positions;
  23647. vertexData.normals = normals;
  23648. vertexData.uvs = uvs;
  23649. return vertexData;
  23650. };
  23651. VertexData.CreateDisc = function (options) {
  23652. var positions = [];
  23653. var indices = [];
  23654. var normals = [];
  23655. var uvs = [];
  23656. var radius = options.radius || 0.5;
  23657. var tessellation = options.tessellation || 64;
  23658. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  23659. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23660. // positions and uvs
  23661. positions.push(0, 0, 0); // disc center first
  23662. uvs.push(0.5, 0.5);
  23663. var theta = Math.PI * 2 * arc;
  23664. var step = theta / tessellation;
  23665. for (var a = 0; a < theta; a += step) {
  23666. var x = Math.cos(a);
  23667. var y = Math.sin(a);
  23668. var u = (x + 1) / 2;
  23669. var v = (1 - y) / 2;
  23670. positions.push(radius * x, radius * y, 0);
  23671. uvs.push(u, v);
  23672. }
  23673. if (arc === 1) {
  23674. positions.push(positions[3], positions[4], positions[5]); // close the circle
  23675. uvs.push(uvs[2], uvs[3]);
  23676. }
  23677. //indices
  23678. var vertexNb = positions.length / 3;
  23679. for (var i = 1; i < vertexNb - 1; i++) {
  23680. indices.push(i + 1, 0, i);
  23681. }
  23682. // result
  23683. VertexData.ComputeNormals(positions, indices, normals);
  23684. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23685. var vertexData = new VertexData();
  23686. vertexData.indices = indices;
  23687. vertexData.positions = positions;
  23688. vertexData.normals = normals;
  23689. vertexData.uvs = uvs;
  23690. return vertexData;
  23691. };
  23692. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  23693. VertexData.CreatePolyhedron = function (options) {
  23694. // provided polyhedron types :
  23695. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  23696. // 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)
  23697. var polyhedra = [];
  23698. 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]] };
  23699. 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]] };
  23700. polyhedra[2] = {
  23701. 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]],
  23702. 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]]
  23703. };
  23704. polyhedra[3] = {
  23705. 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]],
  23706. 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]]
  23707. };
  23708. polyhedra[4] = {
  23709. 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]],
  23710. 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]]
  23711. };
  23712. 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]] };
  23713. 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]] };
  23714. 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]] };
  23715. 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]] };
  23716. 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]] };
  23717. 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]] };
  23718. 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]] };
  23719. 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]] };
  23720. 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]] };
  23721. polyhedra[14] = {
  23722. 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]],
  23723. 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]]
  23724. };
  23725. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  23726. var size = options.size;
  23727. var sizeX = options.sizeX || size || 1;
  23728. var sizeY = options.sizeY || size || 1;
  23729. var sizeZ = options.sizeZ || size || 1;
  23730. var data = options.custom || polyhedra[type];
  23731. var nbfaces = data.face.length;
  23732. var faceUV = options.faceUV || new Array(nbfaces);
  23733. var faceColors = options.faceColors;
  23734. var singleFace = options.singleFace;
  23735. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23736. var positions = [];
  23737. var indices = [];
  23738. var normals = [];
  23739. var uvs = [];
  23740. var colors = [];
  23741. var index = 0;
  23742. var faceIdx = 0; // face cursor in the array "indexes"
  23743. var indexes = [];
  23744. var i = 0;
  23745. var f = 0;
  23746. var u, v, ang, x, y, tmp;
  23747. // default face colors and UV if undefined
  23748. if (!singleFace) {
  23749. for (f = 0; f < nbfaces; f++) {
  23750. if (faceColors && faceColors[f] === undefined) {
  23751. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  23752. }
  23753. if (faceUV && faceUV[f] === undefined) {
  23754. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  23755. }
  23756. }
  23757. }
  23758. if (singleFace) {
  23759. for (i = 0; i < data.vertex.length; i++) {
  23760. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  23761. uvs.push(0, 0);
  23762. }
  23763. for (f = 0; f < nbfaces; f++) {
  23764. for (i = 0; i < data.face[f].length - 2; i++) {
  23765. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  23766. }
  23767. }
  23768. }
  23769. else {
  23770. for (f = 0; f < nbfaces; f++) {
  23771. var fl = data.face[f].length; // number of vertices of the current face
  23772. ang = 2 * Math.PI / fl;
  23773. x = 0.5 * Math.tan(ang / 2);
  23774. y = 0.5;
  23775. // positions, uvs, colors
  23776. for (i = 0; i < fl; i++) {
  23777. // positions
  23778. 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);
  23779. indexes.push(index);
  23780. index++;
  23781. // uvs
  23782. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  23783. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  23784. uvs.push(u, v);
  23785. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  23786. y = x * Math.sin(ang) + y * Math.cos(ang);
  23787. x = tmp;
  23788. // colors
  23789. if (faceColors) {
  23790. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  23791. }
  23792. }
  23793. // indices from indexes
  23794. for (i = 0; i < fl - 2; i++) {
  23795. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  23796. }
  23797. faceIdx += fl;
  23798. }
  23799. }
  23800. VertexData.ComputeNormals(positions, indices, normals);
  23801. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23802. var vertexData = new VertexData();
  23803. vertexData.positions = positions;
  23804. vertexData.indices = indices;
  23805. vertexData.normals = normals;
  23806. vertexData.uvs = uvs;
  23807. if (faceColors && !singleFace) {
  23808. vertexData.colors = colors;
  23809. }
  23810. return vertexData;
  23811. };
  23812. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  23813. VertexData.CreateTorusKnot = function (options) {
  23814. var indices = [];
  23815. var positions = [];
  23816. var normals = [];
  23817. var uvs = [];
  23818. var radius = options.radius || 2;
  23819. var tube = options.tube || 0.5;
  23820. var radialSegments = options.radialSegments || 32;
  23821. var tubularSegments = options.tubularSegments || 32;
  23822. var p = options.p || 2;
  23823. var q = options.q || 3;
  23824. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23825. // Helper
  23826. var getPos = function (angle) {
  23827. var cu = Math.cos(angle);
  23828. var su = Math.sin(angle);
  23829. var quOverP = q / p * angle;
  23830. var cs = Math.cos(quOverP);
  23831. var tx = radius * (2 + cs) * 0.5 * cu;
  23832. var ty = radius * (2 + cs) * su * 0.5;
  23833. var tz = radius * Math.sin(quOverP) * 0.5;
  23834. return new BABYLON.Vector3(tx, ty, tz);
  23835. };
  23836. // Vertices
  23837. var i;
  23838. var j;
  23839. for (i = 0; i <= radialSegments; i++) {
  23840. var modI = i % radialSegments;
  23841. var u = modI / radialSegments * 2 * p * Math.PI;
  23842. var p1 = getPos(u);
  23843. var p2 = getPos(u + 0.01);
  23844. var tang = p2.subtract(p1);
  23845. var n = p2.add(p1);
  23846. var bitan = BABYLON.Vector3.Cross(tang, n);
  23847. n = BABYLON.Vector3.Cross(bitan, tang);
  23848. bitan.normalize();
  23849. n.normalize();
  23850. for (j = 0; j < tubularSegments; j++) {
  23851. var modJ = j % tubularSegments;
  23852. var v = modJ / tubularSegments * 2 * Math.PI;
  23853. var cx = -tube * Math.cos(v);
  23854. var cy = tube * Math.sin(v);
  23855. positions.push(p1.x + cx * n.x + cy * bitan.x);
  23856. positions.push(p1.y + cx * n.y + cy * bitan.y);
  23857. positions.push(p1.z + cx * n.z + cy * bitan.z);
  23858. uvs.push(i / radialSegments);
  23859. uvs.push(j / tubularSegments);
  23860. }
  23861. }
  23862. for (i = 0; i < radialSegments; i++) {
  23863. for (j = 0; j < tubularSegments; j++) {
  23864. var jNext = (j + 1) % tubularSegments;
  23865. var a = i * tubularSegments + j;
  23866. var b = (i + 1) * tubularSegments + j;
  23867. var c = (i + 1) * tubularSegments + jNext;
  23868. var d = i * tubularSegments + jNext;
  23869. indices.push(d);
  23870. indices.push(b);
  23871. indices.push(a);
  23872. indices.push(d);
  23873. indices.push(c);
  23874. indices.push(b);
  23875. }
  23876. }
  23877. // Normals
  23878. VertexData.ComputeNormals(positions, indices, normals);
  23879. // Sides
  23880. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23881. // Result
  23882. var vertexData = new VertexData();
  23883. vertexData.indices = indices;
  23884. vertexData.positions = positions;
  23885. vertexData.normals = normals;
  23886. vertexData.uvs = uvs;
  23887. return vertexData;
  23888. };
  23889. // Tools
  23890. /**
  23891. * @param {any} - positions (number[] or Float32Array)
  23892. * @param {any} - indices (number[] or Uint16Array)
  23893. * @param {any} - normals (number[] or Float32Array)
  23894. */
  23895. VertexData.ComputeNormals = function (positions, indices, normals) {
  23896. var index = 0;
  23897. // temp Vector3
  23898. var p1p2 = BABYLON.Vector3.Zero();
  23899. var p3p2 = BABYLON.Vector3.Zero();
  23900. var faceNormal = BABYLON.Vector3.Zero();
  23901. var vertexNormali1 = BABYLON.Vector3.Zero();
  23902. for (index = 0; index < positions.length; index++) {
  23903. normals[index] = 0.0;
  23904. }
  23905. // indice triplet = 1 face
  23906. var nbFaces = indices.length / 3;
  23907. for (index = 0; index < nbFaces; index++) {
  23908. var i1 = indices[index * 3];
  23909. var i2 = indices[index * 3 + 1];
  23910. var i3 = indices[index * 3 + 2];
  23911. p1p2.x = positions[i1 * 3] - positions[i2 * 3];
  23912. p1p2.y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  23913. p1p2.z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  23914. p3p2.x = positions[i3 * 3] - positions[i2 * 3];
  23915. p3p2.y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  23916. p3p2.z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  23917. BABYLON.Vector3.CrossToRef(p1p2, p3p2, faceNormal);
  23918. faceNormal.normalize();
  23919. normals[i1 * 3] += faceNormal.x;
  23920. normals[i1 * 3 + 1] += faceNormal.y;
  23921. normals[i1 * 3 + 2] += faceNormal.z;
  23922. normals[i2 * 3] += faceNormal.x;
  23923. normals[i2 * 3 + 1] += faceNormal.y;
  23924. normals[i2 * 3 + 2] += faceNormal.z;
  23925. normals[i3 * 3] += faceNormal.x;
  23926. normals[i3 * 3 + 1] += faceNormal.y;
  23927. normals[i3 * 3 + 2] += faceNormal.z;
  23928. }
  23929. // last normalization
  23930. for (index = 0; index < normals.length / 3; index++) {
  23931. BABYLON.Vector3.FromFloatsToRef(normals[index * 3], normals[index * 3 + 1], normals[index * 3 + 2], vertexNormali1);
  23932. vertexNormali1.normalize();
  23933. normals[index * 3] = vertexNormali1.x;
  23934. normals[index * 3 + 1] = vertexNormali1.y;
  23935. normals[index * 3 + 2] = vertexNormali1.z;
  23936. }
  23937. };
  23938. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  23939. var li = indices.length;
  23940. var ln = normals.length;
  23941. var i;
  23942. var n;
  23943. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23944. switch (sideOrientation) {
  23945. case BABYLON.Mesh.FRONTSIDE:
  23946. // nothing changed
  23947. break;
  23948. case BABYLON.Mesh.BACKSIDE:
  23949. var tmp;
  23950. // indices
  23951. for (i = 0; i < li; i += 3) {
  23952. tmp = indices[i];
  23953. indices[i] = indices[i + 2];
  23954. indices[i + 2] = tmp;
  23955. }
  23956. // normals
  23957. for (n = 0; n < ln; n++) {
  23958. normals[n] = -normals[n];
  23959. }
  23960. break;
  23961. case BABYLON.Mesh.DOUBLESIDE:
  23962. // positions
  23963. var lp = positions.length;
  23964. var l = lp / 3;
  23965. for (var p = 0; p < lp; p++) {
  23966. positions[lp + p] = positions[p];
  23967. }
  23968. // indices
  23969. for (i = 0; i < li; i += 3) {
  23970. indices[i + li] = indices[i + 2] + l;
  23971. indices[i + 1 + li] = indices[i + 1] + l;
  23972. indices[i + 2 + li] = indices[i] + l;
  23973. }
  23974. // normals
  23975. for (n = 0; n < ln; n++) {
  23976. normals[ln + n] = -normals[n];
  23977. }
  23978. // uvs
  23979. var lu = uvs.length;
  23980. for (var u = 0; u < lu; u++) {
  23981. uvs[u + lu] = uvs[u];
  23982. }
  23983. break;
  23984. }
  23985. };
  23986. return VertexData;
  23987. })();
  23988. BABYLON.VertexData = VertexData;
  23989. })(BABYLON || (BABYLON = {}));
  23990. var BABYLON;
  23991. (function (BABYLON) {
  23992. var Tags = (function () {
  23993. function Tags() {
  23994. }
  23995. Tags.EnableFor = function (obj) {
  23996. obj._tags = obj._tags || {};
  23997. obj.hasTags = function () {
  23998. return Tags.HasTags(obj);
  23999. };
  24000. obj.addTags = function (tagsString) {
  24001. return Tags.AddTagsTo(obj, tagsString);
  24002. };
  24003. obj.removeTags = function (tagsString) {
  24004. return Tags.RemoveTagsFrom(obj, tagsString);
  24005. };
  24006. obj.matchesTagsQuery = function (tagsQuery) {
  24007. return Tags.MatchesQuery(obj, tagsQuery);
  24008. };
  24009. };
  24010. Tags.DisableFor = function (obj) {
  24011. delete obj._tags;
  24012. delete obj.hasTags;
  24013. delete obj.addTags;
  24014. delete obj.removeTags;
  24015. delete obj.matchesTagsQuery;
  24016. };
  24017. Tags.HasTags = function (obj) {
  24018. if (!obj._tags) {
  24019. return false;
  24020. }
  24021. return !BABYLON.Tools.IsEmpty(obj._tags);
  24022. };
  24023. Tags.GetTags = function (obj) {
  24024. if (!obj._tags) {
  24025. return null;
  24026. }
  24027. return obj._tags;
  24028. };
  24029. // the tags 'true' and 'false' are reserved and cannot be used as tags
  24030. // a tag cannot start with '||', '&&', and '!'
  24031. // it cannot contain whitespaces
  24032. Tags.AddTagsTo = function (obj, tagsString) {
  24033. if (!tagsString) {
  24034. return;
  24035. }
  24036. if (typeof tagsString !== "string") {
  24037. return;
  24038. }
  24039. var tags = tagsString.split(" ");
  24040. for (var t in tags) {
  24041. Tags._AddTagTo(obj, tags[t]);
  24042. }
  24043. };
  24044. Tags._AddTagTo = function (obj, tag) {
  24045. tag = tag.trim();
  24046. if (tag === "" || tag === "true" || tag === "false") {
  24047. return;
  24048. }
  24049. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  24050. return;
  24051. }
  24052. Tags.EnableFor(obj);
  24053. obj._tags[tag] = true;
  24054. };
  24055. Tags.RemoveTagsFrom = function (obj, tagsString) {
  24056. if (!Tags.HasTags(obj)) {
  24057. return;
  24058. }
  24059. var tags = tagsString.split(" ");
  24060. for (var t in tags) {
  24061. Tags._RemoveTagFrom(obj, tags[t]);
  24062. }
  24063. };
  24064. Tags._RemoveTagFrom = function (obj, tag) {
  24065. delete obj._tags[tag];
  24066. };
  24067. Tags.MatchesQuery = function (obj, tagsQuery) {
  24068. if (tagsQuery === undefined) {
  24069. return true;
  24070. }
  24071. if (tagsQuery === "") {
  24072. return Tags.HasTags(obj);
  24073. }
  24074. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  24075. };
  24076. return Tags;
  24077. })();
  24078. BABYLON.Tags = Tags;
  24079. })(BABYLON || (BABYLON = {}));
  24080. var BABYLON;
  24081. (function (BABYLON) {
  24082. var Internals;
  24083. (function (Internals) {
  24084. var AndOrNotEvaluator = (function () {
  24085. function AndOrNotEvaluator() {
  24086. }
  24087. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  24088. if (!query.match(/\([^\(\)]*\)/g)) {
  24089. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  24090. }
  24091. else {
  24092. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  24093. // remove parenthesis
  24094. r = r.slice(1, r.length - 1);
  24095. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  24096. });
  24097. }
  24098. if (query === "true") {
  24099. return true;
  24100. }
  24101. if (query === "false") {
  24102. return false;
  24103. }
  24104. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  24105. };
  24106. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  24107. evaluateCallback = evaluateCallback || (function (r) {
  24108. return r === "true" ? true : false;
  24109. });
  24110. var result;
  24111. var or = parenthesisContent.split("||");
  24112. for (var i in or) {
  24113. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  24114. var and = ori.split("&&");
  24115. if (and.length > 1) {
  24116. for (var j = 0; j < and.length; ++j) {
  24117. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  24118. if (andj !== "true" && andj !== "false") {
  24119. if (andj[0] === "!") {
  24120. result = !evaluateCallback(andj.substring(1));
  24121. }
  24122. else {
  24123. result = evaluateCallback(andj);
  24124. }
  24125. }
  24126. else {
  24127. result = andj === "true" ? true : false;
  24128. }
  24129. if (!result) {
  24130. ori = "false";
  24131. break;
  24132. }
  24133. }
  24134. }
  24135. if (result || ori === "true") {
  24136. result = true;
  24137. break;
  24138. }
  24139. // result equals false (or undefined)
  24140. if (ori !== "true" && ori !== "false") {
  24141. if (ori[0] === "!") {
  24142. result = !evaluateCallback(ori.substring(1));
  24143. }
  24144. else {
  24145. result = evaluateCallback(ori);
  24146. }
  24147. }
  24148. else {
  24149. result = ori === "true" ? true : false;
  24150. }
  24151. }
  24152. // the whole parenthesis scope is replaced by 'true' or 'false'
  24153. return result ? "true" : "false";
  24154. };
  24155. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  24156. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  24157. // remove whitespaces
  24158. r = r.replace(/[\s]/g, function () { return ""; });
  24159. return r.length % 2 ? "!" : "";
  24160. });
  24161. booleanString = booleanString.trim();
  24162. if (booleanString === "!true") {
  24163. booleanString = "false";
  24164. }
  24165. else if (booleanString === "!false") {
  24166. booleanString = "true";
  24167. }
  24168. return booleanString;
  24169. };
  24170. return AndOrNotEvaluator;
  24171. })();
  24172. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  24173. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  24174. })(BABYLON || (BABYLON = {}));
  24175. var BABYLON;
  24176. (function (BABYLON) {
  24177. var PostProcessRenderPass = (function () {
  24178. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  24179. this._enabled = true;
  24180. this._refCount = 0;
  24181. this._name = name;
  24182. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  24183. this.setRenderList(renderList);
  24184. this._renderTexture.onBeforeRender = beforeRender;
  24185. this._renderTexture.onAfterRender = afterRender;
  24186. this._scene = scene;
  24187. this._renderList = renderList;
  24188. }
  24189. // private
  24190. PostProcessRenderPass.prototype._incRefCount = function () {
  24191. if (this._refCount === 0) {
  24192. this._scene.customRenderTargets.push(this._renderTexture);
  24193. }
  24194. return ++this._refCount;
  24195. };
  24196. PostProcessRenderPass.prototype._decRefCount = function () {
  24197. this._refCount--;
  24198. if (this._refCount <= 0) {
  24199. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  24200. }
  24201. return this._refCount;
  24202. };
  24203. PostProcessRenderPass.prototype._update = function () {
  24204. this.setRenderList(this._renderList);
  24205. };
  24206. // public
  24207. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  24208. this._renderTexture.renderList = renderList;
  24209. };
  24210. PostProcessRenderPass.prototype.getRenderTexture = function () {
  24211. return this._renderTexture;
  24212. };
  24213. return PostProcessRenderPass;
  24214. })();
  24215. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  24216. })(BABYLON || (BABYLON = {}));
  24217. var BABYLON;
  24218. (function (BABYLON) {
  24219. var PostProcessRenderEffect = (function () {
  24220. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  24221. this._engine = engine;
  24222. this._name = name;
  24223. this._singleInstance = singleInstance || true;
  24224. this._getPostProcess = getPostProcess;
  24225. this._cameras = [];
  24226. this._indicesForCamera = [];
  24227. this._postProcesses = {};
  24228. this._renderPasses = {};
  24229. this._renderEffectAsPasses = {};
  24230. }
  24231. PostProcessRenderEffect.prototype._update = function () {
  24232. for (var renderPassName in this._renderPasses) {
  24233. this._renderPasses[renderPassName]._update();
  24234. }
  24235. };
  24236. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  24237. this._renderPasses[renderPass._name] = renderPass;
  24238. this._linkParameters();
  24239. };
  24240. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  24241. delete this._renderPasses[renderPass._name];
  24242. this._linkParameters();
  24243. };
  24244. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  24245. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  24246. this._linkParameters();
  24247. };
  24248. PostProcessRenderEffect.prototype.getPass = function (passName) {
  24249. for (var renderPassName in this._renderPasses) {
  24250. if (renderPassName === passName) {
  24251. return this._renderPasses[passName];
  24252. }
  24253. }
  24254. };
  24255. PostProcessRenderEffect.prototype.emptyPasses = function () {
  24256. this._renderPasses = {};
  24257. this._linkParameters();
  24258. };
  24259. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  24260. var cameraKey;
  24261. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24262. for (var i = 0; i < _cam.length; i++) {
  24263. var camera = _cam[i];
  24264. var cameraName = camera.name;
  24265. if (this._singleInstance) {
  24266. cameraKey = 0;
  24267. }
  24268. else {
  24269. cameraKey = cameraName;
  24270. }
  24271. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  24272. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  24273. if (!this._indicesForCamera[cameraName]) {
  24274. this._indicesForCamera[cameraName] = [];
  24275. }
  24276. this._indicesForCamera[cameraName].push(index);
  24277. if (this._cameras.indexOf(camera) === -1) {
  24278. this._cameras[cameraName] = camera;
  24279. }
  24280. for (var passName in this._renderPasses) {
  24281. this._renderPasses[passName]._incRefCount();
  24282. }
  24283. }
  24284. this._linkParameters();
  24285. };
  24286. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  24287. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24288. for (var i = 0; i < _cam.length; i++) {
  24289. var camera = _cam[i];
  24290. var cameraName = camera.name;
  24291. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  24292. var index = this._cameras.indexOf(cameraName);
  24293. this._indicesForCamera.splice(index, 1);
  24294. this._cameras.splice(index, 1);
  24295. for (var passName in this._renderPasses) {
  24296. this._renderPasses[passName]._decRefCount();
  24297. }
  24298. }
  24299. };
  24300. PostProcessRenderEffect.prototype._enable = function (cameras) {
  24301. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24302. for (var i = 0; i < _cam.length; i++) {
  24303. var camera = _cam[i];
  24304. var cameraName = camera.name;
  24305. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  24306. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  24307. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  24308. }
  24309. }
  24310. for (var passName in this._renderPasses) {
  24311. this._renderPasses[passName]._incRefCount();
  24312. }
  24313. }
  24314. };
  24315. PostProcessRenderEffect.prototype._disable = function (cameras) {
  24316. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24317. for (var i = 0; i < _cam.length; i++) {
  24318. var camera = _cam[i];
  24319. var cameraName = camera.Name;
  24320. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  24321. for (var passName in this._renderPasses) {
  24322. this._renderPasses[passName]._decRefCount();
  24323. }
  24324. }
  24325. };
  24326. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  24327. if (this._singleInstance) {
  24328. return this._postProcesses[0];
  24329. }
  24330. else {
  24331. return this._postProcesses[camera.name];
  24332. }
  24333. };
  24334. PostProcessRenderEffect.prototype._linkParameters = function () {
  24335. var _this = this;
  24336. for (var index in this._postProcesses) {
  24337. if (this.applyParameters) {
  24338. this.applyParameters(this._postProcesses[index]);
  24339. }
  24340. this._postProcesses[index].onBeforeRender = function (effect) {
  24341. _this._linkTextures(effect);
  24342. };
  24343. }
  24344. };
  24345. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  24346. for (var renderPassName in this._renderPasses) {
  24347. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  24348. }
  24349. for (var renderEffectName in this._renderEffectAsPasses) {
  24350. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  24351. }
  24352. };
  24353. return PostProcessRenderEffect;
  24354. })();
  24355. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  24356. })(BABYLON || (BABYLON = {}));
  24357. var BABYLON;
  24358. (function (BABYLON) {
  24359. var PostProcessRenderPipeline = (function () {
  24360. function PostProcessRenderPipeline(engine, name) {
  24361. this._engine = engine;
  24362. this._name = name;
  24363. this._renderEffects = {};
  24364. this._renderEffectsForIsolatedPass = {};
  24365. this._cameras = [];
  24366. }
  24367. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  24368. this._renderEffects[renderEffect._name] = renderEffect;
  24369. };
  24370. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  24371. var renderEffects = this._renderEffects[renderEffectName];
  24372. if (!renderEffects) {
  24373. return;
  24374. }
  24375. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  24376. };
  24377. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  24378. var renderEffects = this._renderEffects[renderEffectName];
  24379. if (!renderEffects) {
  24380. return;
  24381. }
  24382. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  24383. };
  24384. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  24385. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24386. var indicesToDelete = [];
  24387. for (var i = 0; i < _cam.length; i++) {
  24388. var camera = _cam[i];
  24389. var cameraName = camera.name;
  24390. if (this._cameras.indexOf(camera) === -1) {
  24391. this._cameras[cameraName] = camera;
  24392. }
  24393. else if (unique) {
  24394. indicesToDelete.push(i);
  24395. }
  24396. }
  24397. for (var i = 0; i < indicesToDelete.length; i++) {
  24398. cameras.splice(indicesToDelete[i], 1);
  24399. }
  24400. for (var renderEffectName in this._renderEffects) {
  24401. this._renderEffects[renderEffectName]._attachCameras(_cam);
  24402. }
  24403. };
  24404. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  24405. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24406. for (var renderEffectName in this._renderEffects) {
  24407. this._renderEffects[renderEffectName]._detachCameras(_cam);
  24408. }
  24409. for (var i = 0; i < _cam.length; i++) {
  24410. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  24411. }
  24412. };
  24413. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  24414. var _this = this;
  24415. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24416. var pass = null;
  24417. for (var renderEffectName in this._renderEffects) {
  24418. pass = this._renderEffects[renderEffectName].getPass(passName);
  24419. if (pass != null) {
  24420. break;
  24421. }
  24422. }
  24423. if (pass === null) {
  24424. return;
  24425. }
  24426. for (var renderEffectName in this._renderEffects) {
  24427. this._renderEffects[renderEffectName]._disable(_cam);
  24428. }
  24429. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  24430. for (var i = 0; i < _cam.length; i++) {
  24431. var camera = _cam[i];
  24432. var cameraName = camera.name;
  24433. 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); });
  24434. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  24435. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  24436. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  24437. }
  24438. };
  24439. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  24440. var _this = this;
  24441. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  24442. for (var i = 0; i < _cam.length; i++) {
  24443. var camera = _cam[i];
  24444. var cameraName = camera.name;
  24445. 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); });
  24446. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  24447. }
  24448. for (var renderEffectName in this._renderEffects) {
  24449. this._renderEffects[renderEffectName]._enable(_cam);
  24450. }
  24451. };
  24452. PostProcessRenderPipeline.prototype._update = function () {
  24453. for (var renderEffectName in this._renderEffects) {
  24454. this._renderEffects[renderEffectName]._update();
  24455. }
  24456. for (var i = 0; i < this._cameras.length; i++) {
  24457. var cameraName = this._cameras[i].name;
  24458. if (this._renderEffectsForIsolatedPass[cameraName]) {
  24459. this._renderEffectsForIsolatedPass[cameraName]._update();
  24460. }
  24461. }
  24462. };
  24463. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  24464. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  24465. return PostProcessRenderPipeline;
  24466. })();
  24467. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  24468. })(BABYLON || (BABYLON = {}));
  24469. var BABYLON;
  24470. (function (BABYLON) {
  24471. var PostProcessRenderPipelineManager = (function () {
  24472. function PostProcessRenderPipelineManager() {
  24473. this._renderPipelines = {};
  24474. }
  24475. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  24476. this._renderPipelines[renderPipeline._name] = renderPipeline;
  24477. };
  24478. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  24479. var renderPipeline = this._renderPipelines[renderPipelineName];
  24480. if (!renderPipeline) {
  24481. return;
  24482. }
  24483. renderPipeline._attachCameras(cameras, unique);
  24484. };
  24485. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  24486. var renderPipeline = this._renderPipelines[renderPipelineName];
  24487. if (!renderPipeline) {
  24488. return;
  24489. }
  24490. renderPipeline._detachCameras(cameras);
  24491. };
  24492. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  24493. var renderPipeline = this._renderPipelines[renderPipelineName];
  24494. if (!renderPipeline) {
  24495. return;
  24496. }
  24497. renderPipeline._enableEffect(renderEffectName, cameras);
  24498. };
  24499. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  24500. var renderPipeline = this._renderPipelines[renderPipelineName];
  24501. if (!renderPipeline) {
  24502. return;
  24503. }
  24504. renderPipeline._disableEffect(renderEffectName, cameras);
  24505. };
  24506. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  24507. var renderPipeline = this._renderPipelines[renderPipelineName];
  24508. if (!renderPipeline) {
  24509. return;
  24510. }
  24511. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  24512. };
  24513. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  24514. var renderPipeline = this._renderPipelines[renderPipelineName];
  24515. if (!renderPipeline) {
  24516. return;
  24517. }
  24518. renderPipeline._disableDisplayOnlyPass(cameras);
  24519. };
  24520. PostProcessRenderPipelineManager.prototype.update = function () {
  24521. for (var renderPipelineName in this._renderPipelines) {
  24522. this._renderPipelines[renderPipelineName]._update();
  24523. }
  24524. };
  24525. return PostProcessRenderPipelineManager;
  24526. })();
  24527. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  24528. })(BABYLON || (BABYLON = {}));
  24529. var BABYLON;
  24530. (function (BABYLON) {
  24531. var BoundingBoxRenderer = (function () {
  24532. function BoundingBoxRenderer(scene) {
  24533. this.frontColor = new BABYLON.Color3(1, 1, 1);
  24534. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  24535. this.showBackLines = true;
  24536. this.renderList = new BABYLON.SmartArray(32);
  24537. this._scene = scene;
  24538. }
  24539. BoundingBoxRenderer.prototype._prepareRessources = function () {
  24540. if (this._colorShader) {
  24541. return;
  24542. }
  24543. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  24544. attributes: ["position"],
  24545. uniforms: ["worldViewProjection", "color"]
  24546. });
  24547. var engine = this._scene.getEngine();
  24548. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  24549. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  24550. 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]);
  24551. };
  24552. BoundingBoxRenderer.prototype.reset = function () {
  24553. this.renderList.reset();
  24554. };
  24555. BoundingBoxRenderer.prototype.render = function () {
  24556. if (this.renderList.length === 0) {
  24557. return;
  24558. }
  24559. this._prepareRessources();
  24560. if (!this._colorShader.isReady()) {
  24561. return;
  24562. }
  24563. var engine = this._scene.getEngine();
  24564. engine.setDepthWrite(false);
  24565. this._colorShader._preBind();
  24566. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  24567. var boundingBox = this.renderList.data[boundingBoxIndex];
  24568. var min = boundingBox.minimum;
  24569. var max = boundingBox.maximum;
  24570. var diff = max.subtract(min);
  24571. var median = min.add(diff.scale(0.5));
  24572. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  24573. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  24574. .multiply(boundingBox.getWorldMatrix());
  24575. // VBOs
  24576. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  24577. if (this.showBackLines) {
  24578. // Back
  24579. engine.setDepthFunctionToGreaterOrEqual();
  24580. this._scene.resetCachedMaterial();
  24581. this._colorShader.setColor4("color", this.backColor.toColor4());
  24582. this._colorShader.bind(worldMatrix);
  24583. // Draw order
  24584. engine.draw(false, 0, 24);
  24585. }
  24586. // Front
  24587. engine.setDepthFunctionToLess();
  24588. this._scene.resetCachedMaterial();
  24589. this._colorShader.setColor4("color", this.frontColor.toColor4());
  24590. this._colorShader.bind(worldMatrix);
  24591. // Draw order
  24592. engine.draw(false, 0, 24);
  24593. }
  24594. this._colorShader.unbind();
  24595. engine.setDepthFunctionToLessOrEqual();
  24596. engine.setDepthWrite(true);
  24597. };
  24598. BoundingBoxRenderer.prototype.dispose = function () {
  24599. if (!this._colorShader) {
  24600. return;
  24601. }
  24602. this._colorShader.dispose();
  24603. this._vb.dispose();
  24604. this._scene.getEngine()._releaseBuffer(this._ib);
  24605. };
  24606. return BoundingBoxRenderer;
  24607. })();
  24608. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  24609. })(BABYLON || (BABYLON = {}));
  24610. var BABYLON;
  24611. (function (BABYLON) {
  24612. var Condition = (function () {
  24613. function Condition(actionManager) {
  24614. this._actionManager = actionManager;
  24615. }
  24616. Condition.prototype.isValid = function () {
  24617. return true;
  24618. };
  24619. Condition.prototype._getProperty = function (propertyPath) {
  24620. return this._actionManager._getProperty(propertyPath);
  24621. };
  24622. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  24623. return this._actionManager._getEffectiveTarget(target, propertyPath);
  24624. };
  24625. return Condition;
  24626. })();
  24627. BABYLON.Condition = Condition;
  24628. var ValueCondition = (function (_super) {
  24629. __extends(ValueCondition, _super);
  24630. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  24631. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  24632. _super.call(this, actionManager);
  24633. this.propertyPath = propertyPath;
  24634. this.value = value;
  24635. this.operator = operator;
  24636. this._target = this._getEffectiveTarget(target, this.propertyPath);
  24637. this._property = this._getProperty(this.propertyPath);
  24638. }
  24639. Object.defineProperty(ValueCondition, "IsEqual", {
  24640. get: function () {
  24641. return ValueCondition._IsEqual;
  24642. },
  24643. enumerable: true,
  24644. configurable: true
  24645. });
  24646. Object.defineProperty(ValueCondition, "IsDifferent", {
  24647. get: function () {
  24648. return ValueCondition._IsDifferent;
  24649. },
  24650. enumerable: true,
  24651. configurable: true
  24652. });
  24653. Object.defineProperty(ValueCondition, "IsGreater", {
  24654. get: function () {
  24655. return ValueCondition._IsGreater;
  24656. },
  24657. enumerable: true,
  24658. configurable: true
  24659. });
  24660. Object.defineProperty(ValueCondition, "IsLesser", {
  24661. get: function () {
  24662. return ValueCondition._IsLesser;
  24663. },
  24664. enumerable: true,
  24665. configurable: true
  24666. });
  24667. // Methods
  24668. ValueCondition.prototype.isValid = function () {
  24669. switch (this.operator) {
  24670. case ValueCondition.IsGreater:
  24671. return this._target[this._property] > this.value;
  24672. case ValueCondition.IsLesser:
  24673. return this._target[this._property] < this.value;
  24674. case ValueCondition.IsEqual:
  24675. case ValueCondition.IsDifferent:
  24676. var check;
  24677. if (this.value.equals) {
  24678. check = this.value.equals(this._target[this._property]);
  24679. }
  24680. else {
  24681. check = this.value === this._target[this._property];
  24682. }
  24683. return this.operator === ValueCondition.IsEqual ? check : !check;
  24684. }
  24685. return false;
  24686. };
  24687. // Statics
  24688. ValueCondition._IsEqual = 0;
  24689. ValueCondition._IsDifferent = 1;
  24690. ValueCondition._IsGreater = 2;
  24691. ValueCondition._IsLesser = 3;
  24692. return ValueCondition;
  24693. })(Condition);
  24694. BABYLON.ValueCondition = ValueCondition;
  24695. var PredicateCondition = (function (_super) {
  24696. __extends(PredicateCondition, _super);
  24697. function PredicateCondition(actionManager, predicate) {
  24698. _super.call(this, actionManager);
  24699. this.predicate = predicate;
  24700. }
  24701. PredicateCondition.prototype.isValid = function () {
  24702. return this.predicate();
  24703. };
  24704. return PredicateCondition;
  24705. })(Condition);
  24706. BABYLON.PredicateCondition = PredicateCondition;
  24707. var StateCondition = (function (_super) {
  24708. __extends(StateCondition, _super);
  24709. function StateCondition(actionManager, target, value) {
  24710. _super.call(this, actionManager);
  24711. this.value = value;
  24712. this._target = target;
  24713. }
  24714. // Methods
  24715. StateCondition.prototype.isValid = function () {
  24716. return this._target.state === this.value;
  24717. };
  24718. return StateCondition;
  24719. })(Condition);
  24720. BABYLON.StateCondition = StateCondition;
  24721. })(BABYLON || (BABYLON = {}));
  24722. var BABYLON;
  24723. (function (BABYLON) {
  24724. var Action = (function () {
  24725. function Action(triggerOptions, condition) {
  24726. this.triggerOptions = triggerOptions;
  24727. if (triggerOptions.parameter) {
  24728. this.trigger = triggerOptions.trigger;
  24729. this._triggerParameter = triggerOptions.parameter;
  24730. }
  24731. else {
  24732. this.trigger = triggerOptions;
  24733. }
  24734. this._nextActiveAction = this;
  24735. this._condition = condition;
  24736. }
  24737. // Methods
  24738. Action.prototype._prepare = function () {
  24739. };
  24740. Action.prototype.getTriggerParameter = function () {
  24741. return this._triggerParameter;
  24742. };
  24743. Action.prototype._executeCurrent = function (evt) {
  24744. if (this._nextActiveAction._condition) {
  24745. var condition = this._nextActiveAction._condition;
  24746. var currentRenderId = this._actionManager.getScene().getRenderId();
  24747. // We cache the current evaluation for the current frame
  24748. if (condition._evaluationId === currentRenderId) {
  24749. if (!condition._currentResult) {
  24750. return;
  24751. }
  24752. }
  24753. else {
  24754. condition._evaluationId = currentRenderId;
  24755. if (!condition.isValid()) {
  24756. condition._currentResult = false;
  24757. return;
  24758. }
  24759. condition._currentResult = true;
  24760. }
  24761. }
  24762. this._nextActiveAction.execute(evt);
  24763. if (this._nextActiveAction._child) {
  24764. if (!this._nextActiveAction._child._actionManager) {
  24765. this._nextActiveAction._child._actionManager = this._actionManager;
  24766. }
  24767. this._nextActiveAction = this._nextActiveAction._child;
  24768. }
  24769. else {
  24770. this._nextActiveAction = this;
  24771. }
  24772. };
  24773. Action.prototype.execute = function (evt) {
  24774. };
  24775. Action.prototype.then = function (action) {
  24776. this._child = action;
  24777. action._actionManager = this._actionManager;
  24778. action._prepare();
  24779. return action;
  24780. };
  24781. Action.prototype._getProperty = function (propertyPath) {
  24782. return this._actionManager._getProperty(propertyPath);
  24783. };
  24784. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  24785. return this._actionManager._getEffectiveTarget(target, propertyPath);
  24786. };
  24787. return Action;
  24788. })();
  24789. BABYLON.Action = Action;
  24790. })(BABYLON || (BABYLON = {}));
  24791. var BABYLON;
  24792. (function (BABYLON) {
  24793. /**
  24794. * ActionEvent is the event beint sent when an action is triggered.
  24795. */
  24796. var ActionEvent = (function () {
  24797. /**
  24798. * @constructor
  24799. * @param source The mesh or sprite that triggered the action.
  24800. * @param pointerX The X mouse cursor position at the time of the event
  24801. * @param pointerY The Y mouse cursor position at the time of the event
  24802. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  24803. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  24804. */
  24805. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  24806. this.source = source;
  24807. this.pointerX = pointerX;
  24808. this.pointerY = pointerY;
  24809. this.meshUnderPointer = meshUnderPointer;
  24810. this.sourceEvent = sourceEvent;
  24811. this.additionalData = additionalData;
  24812. }
  24813. /**
  24814. * Helper function to auto-create an ActionEvent from a source mesh.
  24815. * @param source The source mesh that triggered the event
  24816. * @param evt {Event} The original (browser) event
  24817. */
  24818. ActionEvent.CreateNew = function (source, evt, additionalData) {
  24819. var scene = source.getScene();
  24820. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  24821. };
  24822. /**
  24823. * Helper function to auto-create an ActionEvent from a source mesh.
  24824. * @param source The source sprite that triggered the event
  24825. * @param scene Scene associated with the sprite
  24826. * @param evt {Event} The original (browser) event
  24827. */
  24828. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  24829. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  24830. };
  24831. /**
  24832. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  24833. * @param scene the scene where the event occurred
  24834. * @param evt {Event} The original (browser) event
  24835. */
  24836. ActionEvent.CreateNewFromScene = function (scene, evt) {
  24837. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  24838. };
  24839. return ActionEvent;
  24840. })();
  24841. BABYLON.ActionEvent = ActionEvent;
  24842. /**
  24843. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  24844. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  24845. */
  24846. var ActionManager = (function () {
  24847. function ActionManager(scene) {
  24848. // Members
  24849. this.actions = new Array();
  24850. this._scene = scene;
  24851. scene._actionManagers.push(this);
  24852. }
  24853. Object.defineProperty(ActionManager, "NothingTrigger", {
  24854. get: function () {
  24855. return ActionManager._NothingTrigger;
  24856. },
  24857. enumerable: true,
  24858. configurable: true
  24859. });
  24860. Object.defineProperty(ActionManager, "OnPickTrigger", {
  24861. get: function () {
  24862. return ActionManager._OnPickTrigger;
  24863. },
  24864. enumerable: true,
  24865. configurable: true
  24866. });
  24867. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  24868. get: function () {
  24869. return ActionManager._OnLeftPickTrigger;
  24870. },
  24871. enumerable: true,
  24872. configurable: true
  24873. });
  24874. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  24875. get: function () {
  24876. return ActionManager._OnRightPickTrigger;
  24877. },
  24878. enumerable: true,
  24879. configurable: true
  24880. });
  24881. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  24882. get: function () {
  24883. return ActionManager._OnCenterPickTrigger;
  24884. },
  24885. enumerable: true,
  24886. configurable: true
  24887. });
  24888. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  24889. get: function () {
  24890. return ActionManager._OnPointerOverTrigger;
  24891. },
  24892. enumerable: true,
  24893. configurable: true
  24894. });
  24895. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  24896. get: function () {
  24897. return ActionManager._OnPointerOutTrigger;
  24898. },
  24899. enumerable: true,
  24900. configurable: true
  24901. });
  24902. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  24903. get: function () {
  24904. return ActionManager._OnEveryFrameTrigger;
  24905. },
  24906. enumerable: true,
  24907. configurable: true
  24908. });
  24909. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  24910. get: function () {
  24911. return ActionManager._OnIntersectionEnterTrigger;
  24912. },
  24913. enumerable: true,
  24914. configurable: true
  24915. });
  24916. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  24917. get: function () {
  24918. return ActionManager._OnIntersectionExitTrigger;
  24919. },
  24920. enumerable: true,
  24921. configurable: true
  24922. });
  24923. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  24924. get: function () {
  24925. return ActionManager._OnKeyDownTrigger;
  24926. },
  24927. enumerable: true,
  24928. configurable: true
  24929. });
  24930. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  24931. get: function () {
  24932. return ActionManager._OnKeyUpTrigger;
  24933. },
  24934. enumerable: true,
  24935. configurable: true
  24936. });
  24937. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  24938. get: function () {
  24939. return ActionManager._OnPickUpTrigger;
  24940. },
  24941. enumerable: true,
  24942. configurable: true
  24943. });
  24944. // Methods
  24945. ActionManager.prototype.dispose = function () {
  24946. var index = this._scene._actionManagers.indexOf(this);
  24947. if (index > -1) {
  24948. this._scene._actionManagers.splice(index, 1);
  24949. }
  24950. };
  24951. ActionManager.prototype.getScene = function () {
  24952. return this._scene;
  24953. };
  24954. /**
  24955. * Does this action manager handles actions of any of the given triggers
  24956. * @param {number[]} triggers - the triggers to be tested
  24957. * @return {boolean} whether one (or more) of the triggers is handeled
  24958. */
  24959. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  24960. for (var index = 0; index < this.actions.length; index++) {
  24961. var action = this.actions[index];
  24962. if (triggers.indexOf(action.trigger) > -1) {
  24963. return true;
  24964. }
  24965. }
  24966. return false;
  24967. };
  24968. /**
  24969. * Does this action manager handles actions of a given trigger
  24970. * @param {number} trigger - the trigger to be tested
  24971. * @return {boolean} whether the trigger is handeled
  24972. */
  24973. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  24974. for (var index = 0; index < this.actions.length; index++) {
  24975. var action = this.actions[index];
  24976. if (action.trigger === trigger) {
  24977. return true;
  24978. }
  24979. }
  24980. return false;
  24981. };
  24982. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  24983. /**
  24984. * Does this action manager has pointer triggers
  24985. * @return {boolean} whether or not it has pointer triggers
  24986. */
  24987. get: function () {
  24988. for (var index = 0; index < this.actions.length; index++) {
  24989. var action = this.actions[index];
  24990. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  24991. return true;
  24992. }
  24993. if (action.trigger === ActionManager._OnPickUpTrigger) {
  24994. return true;
  24995. }
  24996. }
  24997. return false;
  24998. },
  24999. enumerable: true,
  25000. configurable: true
  25001. });
  25002. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  25003. /**
  25004. * Does this action manager has pick triggers
  25005. * @return {boolean} whether or not it has pick triggers
  25006. */
  25007. get: function () {
  25008. for (var index = 0; index < this.actions.length; index++) {
  25009. var action = this.actions[index];
  25010. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  25011. return true;
  25012. }
  25013. if (action.trigger === ActionManager._OnPickUpTrigger) {
  25014. return true;
  25015. }
  25016. }
  25017. return false;
  25018. },
  25019. enumerable: true,
  25020. configurable: true
  25021. });
  25022. /**
  25023. * Registers an action to this action manager
  25024. * @param {BABYLON.Action} action - the action to be registered
  25025. * @return {BABYLON.Action} the action amended (prepared) after registration
  25026. */
  25027. ActionManager.prototype.registerAction = function (action) {
  25028. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  25029. if (this.getScene().actionManager !== this) {
  25030. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  25031. return null;
  25032. }
  25033. }
  25034. this.actions.push(action);
  25035. action._actionManager = this;
  25036. action._prepare();
  25037. return action;
  25038. };
  25039. /**
  25040. * Process a specific trigger
  25041. * @param {number} trigger - the trigger to process
  25042. * @param evt {BABYLON.ActionEvent} the event details to be processed
  25043. */
  25044. ActionManager.prototype.processTrigger = function (trigger, evt) {
  25045. for (var index = 0; index < this.actions.length; index++) {
  25046. var action = this.actions[index];
  25047. if (action.trigger === trigger) {
  25048. if (trigger === ActionManager.OnKeyUpTrigger
  25049. || trigger === ActionManager.OnKeyDownTrigger) {
  25050. var parameter = action.getTriggerParameter();
  25051. if (parameter) {
  25052. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  25053. var actualkey = String.fromCharCode(unicode).toLowerCase();
  25054. if (actualkey !== parameter.toLowerCase()) {
  25055. continue;
  25056. }
  25057. }
  25058. }
  25059. action._executeCurrent(evt);
  25060. }
  25061. }
  25062. };
  25063. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  25064. var properties = propertyPath.split(".");
  25065. for (var index = 0; index < properties.length - 1; index++) {
  25066. target = target[properties[index]];
  25067. }
  25068. return target;
  25069. };
  25070. ActionManager.prototype._getProperty = function (propertyPath) {
  25071. var properties = propertyPath.split(".");
  25072. return properties[properties.length - 1];
  25073. };
  25074. // Statics
  25075. ActionManager._NothingTrigger = 0;
  25076. ActionManager._OnPickTrigger = 1;
  25077. ActionManager._OnLeftPickTrigger = 2;
  25078. ActionManager._OnRightPickTrigger = 3;
  25079. ActionManager._OnCenterPickTrigger = 4;
  25080. ActionManager._OnPointerOverTrigger = 5;
  25081. ActionManager._OnPointerOutTrigger = 6;
  25082. ActionManager._OnEveryFrameTrigger = 7;
  25083. ActionManager._OnIntersectionEnterTrigger = 8;
  25084. ActionManager._OnIntersectionExitTrigger = 9;
  25085. ActionManager._OnKeyDownTrigger = 10;
  25086. ActionManager._OnKeyUpTrigger = 11;
  25087. ActionManager._OnPickUpTrigger = 12;
  25088. return ActionManager;
  25089. })();
  25090. BABYLON.ActionManager = ActionManager;
  25091. })(BABYLON || (BABYLON = {}));
  25092. var BABYLON;
  25093. (function (BABYLON) {
  25094. var InterpolateValueAction = (function (_super) {
  25095. __extends(InterpolateValueAction, _super);
  25096. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  25097. if (duration === void 0) { duration = 1000; }
  25098. _super.call(this, triggerOptions, condition);
  25099. this.propertyPath = propertyPath;
  25100. this.value = value;
  25101. this.duration = duration;
  25102. this.stopOtherAnimations = stopOtherAnimations;
  25103. this.onInterpolationDone = onInterpolationDone;
  25104. this._target = target;
  25105. }
  25106. InterpolateValueAction.prototype._prepare = function () {
  25107. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25108. this._property = this._getProperty(this.propertyPath);
  25109. };
  25110. InterpolateValueAction.prototype.execute = function () {
  25111. var scene = this._actionManager.getScene();
  25112. var keys = [
  25113. {
  25114. frame: 0,
  25115. value: this._target[this._property]
  25116. }, {
  25117. frame: 100,
  25118. value: this.value
  25119. }
  25120. ];
  25121. var dataType;
  25122. if (typeof this.value === "number") {
  25123. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  25124. }
  25125. else if (this.value instanceof BABYLON.Color3) {
  25126. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  25127. }
  25128. else if (this.value instanceof BABYLON.Vector3) {
  25129. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  25130. }
  25131. else if (this.value instanceof BABYLON.Matrix) {
  25132. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  25133. }
  25134. else if (this.value instanceof BABYLON.Quaternion) {
  25135. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  25136. }
  25137. else {
  25138. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  25139. return;
  25140. }
  25141. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  25142. animation.setKeys(keys);
  25143. if (this.stopOtherAnimations) {
  25144. scene.stopAnimation(this._target);
  25145. }
  25146. scene.beginDirectAnimation(this._target, [animation], 0, 100, false, 1, this.onInterpolationDone);
  25147. };
  25148. return InterpolateValueAction;
  25149. })(BABYLON.Action);
  25150. BABYLON.InterpolateValueAction = InterpolateValueAction;
  25151. })(BABYLON || (BABYLON = {}));
  25152. var BABYLON;
  25153. (function (BABYLON) {
  25154. var SwitchBooleanAction = (function (_super) {
  25155. __extends(SwitchBooleanAction, _super);
  25156. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  25157. _super.call(this, triggerOptions, condition);
  25158. this.propertyPath = propertyPath;
  25159. this._target = target;
  25160. }
  25161. SwitchBooleanAction.prototype._prepare = function () {
  25162. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25163. this._property = this._getProperty(this.propertyPath);
  25164. };
  25165. SwitchBooleanAction.prototype.execute = function () {
  25166. this._target[this._property] = !this._target[this._property];
  25167. };
  25168. return SwitchBooleanAction;
  25169. })(BABYLON.Action);
  25170. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  25171. var SetStateAction = (function (_super) {
  25172. __extends(SetStateAction, _super);
  25173. function SetStateAction(triggerOptions, target, value, condition) {
  25174. _super.call(this, triggerOptions, condition);
  25175. this.value = value;
  25176. this._target = target;
  25177. }
  25178. SetStateAction.prototype.execute = function () {
  25179. this._target.state = this.value;
  25180. };
  25181. return SetStateAction;
  25182. })(BABYLON.Action);
  25183. BABYLON.SetStateAction = SetStateAction;
  25184. var SetValueAction = (function (_super) {
  25185. __extends(SetValueAction, _super);
  25186. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  25187. _super.call(this, triggerOptions, condition);
  25188. this.propertyPath = propertyPath;
  25189. this.value = value;
  25190. this._target = target;
  25191. }
  25192. SetValueAction.prototype._prepare = function () {
  25193. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25194. this._property = this._getProperty(this.propertyPath);
  25195. };
  25196. SetValueAction.prototype.execute = function () {
  25197. this._target[this._property] = this.value;
  25198. };
  25199. return SetValueAction;
  25200. })(BABYLON.Action);
  25201. BABYLON.SetValueAction = SetValueAction;
  25202. var IncrementValueAction = (function (_super) {
  25203. __extends(IncrementValueAction, _super);
  25204. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  25205. _super.call(this, triggerOptions, condition);
  25206. this.propertyPath = propertyPath;
  25207. this.value = value;
  25208. this._target = target;
  25209. }
  25210. IncrementValueAction.prototype._prepare = function () {
  25211. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25212. this._property = this._getProperty(this.propertyPath);
  25213. if (typeof this._target[this._property] !== "number") {
  25214. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  25215. }
  25216. };
  25217. IncrementValueAction.prototype.execute = function () {
  25218. this._target[this._property] += this.value;
  25219. };
  25220. return IncrementValueAction;
  25221. })(BABYLON.Action);
  25222. BABYLON.IncrementValueAction = IncrementValueAction;
  25223. var PlayAnimationAction = (function (_super) {
  25224. __extends(PlayAnimationAction, _super);
  25225. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  25226. _super.call(this, triggerOptions, condition);
  25227. this.from = from;
  25228. this.to = to;
  25229. this.loop = loop;
  25230. this._target = target;
  25231. }
  25232. PlayAnimationAction.prototype._prepare = function () {
  25233. };
  25234. PlayAnimationAction.prototype.execute = function () {
  25235. var scene = this._actionManager.getScene();
  25236. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  25237. };
  25238. return PlayAnimationAction;
  25239. })(BABYLON.Action);
  25240. BABYLON.PlayAnimationAction = PlayAnimationAction;
  25241. var StopAnimationAction = (function (_super) {
  25242. __extends(StopAnimationAction, _super);
  25243. function StopAnimationAction(triggerOptions, target, condition) {
  25244. _super.call(this, triggerOptions, condition);
  25245. this._target = target;
  25246. }
  25247. StopAnimationAction.prototype._prepare = function () {
  25248. };
  25249. StopAnimationAction.prototype.execute = function () {
  25250. var scene = this._actionManager.getScene();
  25251. scene.stopAnimation(this._target);
  25252. };
  25253. return StopAnimationAction;
  25254. })(BABYLON.Action);
  25255. BABYLON.StopAnimationAction = StopAnimationAction;
  25256. var DoNothingAction = (function (_super) {
  25257. __extends(DoNothingAction, _super);
  25258. function DoNothingAction(triggerOptions, condition) {
  25259. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  25260. _super.call(this, triggerOptions, condition);
  25261. }
  25262. DoNothingAction.prototype.execute = function () {
  25263. };
  25264. return DoNothingAction;
  25265. })(BABYLON.Action);
  25266. BABYLON.DoNothingAction = DoNothingAction;
  25267. var CombineAction = (function (_super) {
  25268. __extends(CombineAction, _super);
  25269. function CombineAction(triggerOptions, children, condition) {
  25270. _super.call(this, triggerOptions, condition);
  25271. this.children = children;
  25272. }
  25273. CombineAction.prototype._prepare = function () {
  25274. for (var index = 0; index < this.children.length; index++) {
  25275. this.children[index]._actionManager = this._actionManager;
  25276. this.children[index]._prepare();
  25277. }
  25278. };
  25279. CombineAction.prototype.execute = function (evt) {
  25280. for (var index = 0; index < this.children.length; index++) {
  25281. this.children[index].execute(evt);
  25282. }
  25283. };
  25284. return CombineAction;
  25285. })(BABYLON.Action);
  25286. BABYLON.CombineAction = CombineAction;
  25287. var ExecuteCodeAction = (function (_super) {
  25288. __extends(ExecuteCodeAction, _super);
  25289. function ExecuteCodeAction(triggerOptions, func, condition) {
  25290. _super.call(this, triggerOptions, condition);
  25291. this.func = func;
  25292. }
  25293. ExecuteCodeAction.prototype.execute = function (evt) {
  25294. this.func(evt);
  25295. };
  25296. return ExecuteCodeAction;
  25297. })(BABYLON.Action);
  25298. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  25299. var SetParentAction = (function (_super) {
  25300. __extends(SetParentAction, _super);
  25301. function SetParentAction(triggerOptions, target, parent, condition) {
  25302. _super.call(this, triggerOptions, condition);
  25303. this._target = target;
  25304. this._parent = parent;
  25305. }
  25306. SetParentAction.prototype._prepare = function () {
  25307. };
  25308. SetParentAction.prototype.execute = function () {
  25309. if (this._target.parent === this._parent) {
  25310. return;
  25311. }
  25312. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  25313. invertParentWorldMatrix.invert();
  25314. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  25315. this._target.parent = this._parent;
  25316. };
  25317. return SetParentAction;
  25318. })(BABYLON.Action);
  25319. BABYLON.SetParentAction = SetParentAction;
  25320. var PlaySoundAction = (function (_super) {
  25321. __extends(PlaySoundAction, _super);
  25322. function PlaySoundAction(triggerOptions, sound, condition) {
  25323. _super.call(this, triggerOptions, condition);
  25324. this._sound = sound;
  25325. }
  25326. PlaySoundAction.prototype._prepare = function () {
  25327. };
  25328. PlaySoundAction.prototype.execute = function () {
  25329. if (this._sound !== undefined)
  25330. this._sound.play();
  25331. };
  25332. return PlaySoundAction;
  25333. })(BABYLON.Action);
  25334. BABYLON.PlaySoundAction = PlaySoundAction;
  25335. var StopSoundAction = (function (_super) {
  25336. __extends(StopSoundAction, _super);
  25337. function StopSoundAction(triggerOptions, sound, condition) {
  25338. _super.call(this, triggerOptions, condition);
  25339. this._sound = sound;
  25340. }
  25341. StopSoundAction.prototype._prepare = function () {
  25342. };
  25343. StopSoundAction.prototype.execute = function () {
  25344. if (this._sound !== undefined)
  25345. this._sound.stop();
  25346. };
  25347. return StopSoundAction;
  25348. })(BABYLON.Action);
  25349. BABYLON.StopSoundAction = StopSoundAction;
  25350. })(BABYLON || (BABYLON = {}));
  25351. var BABYLON;
  25352. (function (BABYLON) {
  25353. var Geometry = (function () {
  25354. function Geometry(id, scene, vertexData, updatable, mesh) {
  25355. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  25356. this._totalVertices = 0;
  25357. this._isDisposed = false;
  25358. this.id = id;
  25359. this._engine = scene.getEngine();
  25360. this._meshes = [];
  25361. this._scene = scene;
  25362. //Init vertex buffer cache
  25363. this._vertexBuffers = {};
  25364. this._indices = [];
  25365. // vertexData
  25366. if (vertexData) {
  25367. this.setAllVerticesData(vertexData, updatable);
  25368. }
  25369. else {
  25370. this._totalVertices = 0;
  25371. this._indices = [];
  25372. }
  25373. // applyToMesh
  25374. if (mesh) {
  25375. this.applyToMesh(mesh);
  25376. mesh.computeWorldMatrix(true);
  25377. }
  25378. }
  25379. Object.defineProperty(Geometry.prototype, "extend", {
  25380. get: function () {
  25381. return this._extend;
  25382. },
  25383. enumerable: true,
  25384. configurable: true
  25385. });
  25386. Geometry.prototype.getScene = function () {
  25387. return this._scene;
  25388. };
  25389. Geometry.prototype.getEngine = function () {
  25390. return this._engine;
  25391. };
  25392. Geometry.prototype.isReady = function () {
  25393. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  25394. };
  25395. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  25396. vertexData.applyToGeometry(this, updatable);
  25397. this.notifyUpdate();
  25398. };
  25399. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  25400. if (this._vertexBuffers[kind]) {
  25401. this._vertexBuffers[kind].dispose();
  25402. }
  25403. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  25404. if (kind === BABYLON.VertexBuffer.PositionKind) {
  25405. stride = this._vertexBuffers[kind].getStrideSize();
  25406. this._totalVertices = data.length / stride;
  25407. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  25408. var meshes = this._meshes;
  25409. var numOfMeshes = meshes.length;
  25410. for (var index = 0; index < numOfMeshes; index++) {
  25411. var mesh = meshes[index];
  25412. mesh._resetPointsArrayCache();
  25413. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  25414. mesh._createGlobalSubMesh();
  25415. mesh.computeWorldMatrix(true);
  25416. }
  25417. }
  25418. this.notifyUpdate(kind);
  25419. };
  25420. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  25421. var vertexBuffer = this.getVertexBuffer(kind);
  25422. if (!vertexBuffer) {
  25423. return;
  25424. }
  25425. vertexBuffer.updateDirectly(data, offset);
  25426. this.notifyUpdate(kind);
  25427. };
  25428. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  25429. var vertexBuffer = this.getVertexBuffer(kind);
  25430. if (!vertexBuffer) {
  25431. return;
  25432. }
  25433. vertexBuffer.update(data);
  25434. if (kind === BABYLON.VertexBuffer.PositionKind) {
  25435. var stride = vertexBuffer.getStrideSize();
  25436. this._totalVertices = data.length / stride;
  25437. if (updateExtends) {
  25438. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  25439. }
  25440. var meshes = this._meshes;
  25441. var numOfMeshes = meshes.length;
  25442. for (var index = 0; index < numOfMeshes; index++) {
  25443. var mesh = meshes[index];
  25444. mesh._resetPointsArrayCache();
  25445. if (updateExtends) {
  25446. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  25447. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  25448. var subMesh = mesh.subMeshes[subIndex];
  25449. subMesh.refreshBoundingInfo();
  25450. }
  25451. }
  25452. }
  25453. }
  25454. this.notifyUpdate(kind);
  25455. };
  25456. Geometry.prototype.getTotalVertices = function () {
  25457. if (!this.isReady()) {
  25458. return 0;
  25459. }
  25460. return this._totalVertices;
  25461. };
  25462. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  25463. var vertexBuffer = this.getVertexBuffer(kind);
  25464. if (!vertexBuffer) {
  25465. return null;
  25466. }
  25467. var orig = vertexBuffer.getData();
  25468. if (!copyWhenShared || this._meshes.length === 1) {
  25469. return orig;
  25470. }
  25471. else {
  25472. var len = orig.length;
  25473. var copy = [];
  25474. for (var i = 0; i < len; i++) {
  25475. copy.push(orig[i]);
  25476. }
  25477. return copy;
  25478. }
  25479. };
  25480. Geometry.prototype.getVertexBuffer = function (kind) {
  25481. if (!this.isReady()) {
  25482. return null;
  25483. }
  25484. return this._vertexBuffers[kind];
  25485. };
  25486. Geometry.prototype.getVertexBuffers = function () {
  25487. if (!this.isReady()) {
  25488. return null;
  25489. }
  25490. return this._vertexBuffers;
  25491. };
  25492. Geometry.prototype.isVerticesDataPresent = function (kind) {
  25493. if (!this._vertexBuffers) {
  25494. if (this._delayInfo) {
  25495. return this._delayInfo.indexOf(kind) !== -1;
  25496. }
  25497. return false;
  25498. }
  25499. return this._vertexBuffers[kind] !== undefined;
  25500. };
  25501. Geometry.prototype.getVerticesDataKinds = function () {
  25502. var result = [];
  25503. var kind;
  25504. if (!this._vertexBuffers && this._delayInfo) {
  25505. for (kind in this._delayInfo) {
  25506. result.push(kind);
  25507. }
  25508. }
  25509. else {
  25510. for (kind in this._vertexBuffers) {
  25511. result.push(kind);
  25512. }
  25513. }
  25514. return result;
  25515. };
  25516. Geometry.prototype.setIndices = function (indices, totalVertices) {
  25517. if (this._indexBuffer) {
  25518. this._engine._releaseBuffer(this._indexBuffer);
  25519. }
  25520. this._indices = indices;
  25521. if (this._meshes.length !== 0 && this._indices) {
  25522. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  25523. }
  25524. if (totalVertices !== undefined) {
  25525. this._totalVertices = totalVertices;
  25526. }
  25527. var meshes = this._meshes;
  25528. var numOfMeshes = meshes.length;
  25529. for (var index = 0; index < numOfMeshes; index++) {
  25530. meshes[index]._createGlobalSubMesh();
  25531. }
  25532. this.notifyUpdate();
  25533. };
  25534. Geometry.prototype.getTotalIndices = function () {
  25535. if (!this.isReady()) {
  25536. return 0;
  25537. }
  25538. return this._indices.length;
  25539. };
  25540. Geometry.prototype.getIndices = function (copyWhenShared) {
  25541. if (!this.isReady()) {
  25542. return null;
  25543. }
  25544. var orig = this._indices;
  25545. if (!copyWhenShared || this._meshes.length === 1) {
  25546. return orig;
  25547. }
  25548. else {
  25549. var len = orig.length;
  25550. var copy = [];
  25551. for (var i = 0; i < len; i++) {
  25552. copy.push(orig[i]);
  25553. }
  25554. return copy;
  25555. }
  25556. };
  25557. Geometry.prototype.getIndexBuffer = function () {
  25558. if (!this.isReady()) {
  25559. return null;
  25560. }
  25561. return this._indexBuffer;
  25562. };
  25563. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  25564. var meshes = this._meshes;
  25565. var index = meshes.indexOf(mesh);
  25566. if (index === -1) {
  25567. return;
  25568. }
  25569. for (var kind in this._vertexBuffers) {
  25570. this._vertexBuffers[kind].dispose();
  25571. }
  25572. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  25573. this._indexBuffer = null;
  25574. }
  25575. meshes.splice(index, 1);
  25576. mesh._geometry = null;
  25577. if (meshes.length === 0 && shouldDispose) {
  25578. this.dispose();
  25579. }
  25580. };
  25581. Geometry.prototype.applyToMesh = function (mesh) {
  25582. if (mesh._geometry === this) {
  25583. return;
  25584. }
  25585. var previousGeometry = mesh._geometry;
  25586. if (previousGeometry) {
  25587. previousGeometry.releaseForMesh(mesh);
  25588. }
  25589. var meshes = this._meshes;
  25590. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  25591. mesh._geometry = this;
  25592. this._scene.pushGeometry(this);
  25593. meshes.push(mesh);
  25594. if (this.isReady()) {
  25595. this._applyToMesh(mesh);
  25596. }
  25597. else {
  25598. mesh._boundingInfo = this._boundingInfo;
  25599. }
  25600. };
  25601. Geometry.prototype._applyToMesh = function (mesh) {
  25602. var numOfMeshes = this._meshes.length;
  25603. // vertexBuffers
  25604. for (var kind in this._vertexBuffers) {
  25605. if (numOfMeshes === 1) {
  25606. this._vertexBuffers[kind].create();
  25607. }
  25608. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  25609. if (kind === BABYLON.VertexBuffer.PositionKind) {
  25610. mesh._resetPointsArrayCache();
  25611. if (!this._extend) {
  25612. this._extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  25613. }
  25614. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  25615. mesh._createGlobalSubMesh();
  25616. //bounding info was just created again, world matrix should be applied again.
  25617. mesh._updateBoundingInfo();
  25618. }
  25619. }
  25620. // indexBuffer
  25621. if (numOfMeshes === 1 && this._indices) {
  25622. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  25623. }
  25624. if (this._indexBuffer) {
  25625. this._indexBuffer.references = numOfMeshes;
  25626. }
  25627. };
  25628. Geometry.prototype.notifyUpdate = function (kind) {
  25629. if (this.onGeometryUpdated) {
  25630. this.onGeometryUpdated(this, kind);
  25631. }
  25632. };
  25633. Geometry.prototype.load = function (scene, onLoaded) {
  25634. var _this = this;
  25635. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25636. return;
  25637. }
  25638. if (this.isReady()) {
  25639. if (onLoaded) {
  25640. onLoaded();
  25641. }
  25642. return;
  25643. }
  25644. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  25645. scene._addPendingData(this);
  25646. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  25647. _this._delayLoadingFunction(JSON.parse(data), _this);
  25648. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  25649. _this._delayInfo = [];
  25650. scene._removePendingData(_this);
  25651. var meshes = _this._meshes;
  25652. var numOfMeshes = meshes.length;
  25653. for (var index = 0; index < numOfMeshes; index++) {
  25654. _this._applyToMesh(meshes[index]);
  25655. }
  25656. if (onLoaded) {
  25657. onLoaded();
  25658. }
  25659. }, function () { }, scene.database);
  25660. };
  25661. Geometry.prototype.isDisposed = function () {
  25662. return this._isDisposed;
  25663. };
  25664. Geometry.prototype.dispose = function () {
  25665. var meshes = this._meshes;
  25666. var numOfMeshes = meshes.length;
  25667. var index;
  25668. for (index = 0; index < numOfMeshes; index++) {
  25669. this.releaseForMesh(meshes[index]);
  25670. }
  25671. this._meshes = [];
  25672. for (var kind in this._vertexBuffers) {
  25673. this._vertexBuffers[kind].dispose();
  25674. }
  25675. this._vertexBuffers = [];
  25676. this._totalVertices = 0;
  25677. if (this._indexBuffer) {
  25678. this._engine._releaseBuffer(this._indexBuffer);
  25679. }
  25680. this._indexBuffer = null;
  25681. this._indices = [];
  25682. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  25683. this.delayLoadingFile = null;
  25684. this._delayLoadingFunction = null;
  25685. this._delayInfo = [];
  25686. this._boundingInfo = null;
  25687. this._scene.removeGeometry(this);
  25688. this._isDisposed = true;
  25689. };
  25690. Geometry.prototype.copy = function (id) {
  25691. var vertexData = new BABYLON.VertexData();
  25692. vertexData.indices = [];
  25693. var indices = this.getIndices();
  25694. for (var index = 0; index < indices.length; index++) {
  25695. vertexData.indices.push(indices[index]);
  25696. }
  25697. var updatable = false;
  25698. var stopChecking = false;
  25699. var kind;
  25700. for (kind in this._vertexBuffers) {
  25701. // using slice() to make a copy of the array and not just reference it
  25702. var data = this.getVerticesData(kind);
  25703. if (data instanceof Float32Array) {
  25704. vertexData.set(new Float32Array(data), kind);
  25705. }
  25706. else {
  25707. vertexData.set(data.slice(0), kind);
  25708. }
  25709. if (!stopChecking) {
  25710. updatable = this.getVertexBuffer(kind).isUpdatable();
  25711. stopChecking = !updatable;
  25712. }
  25713. }
  25714. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  25715. geometry.delayLoadState = this.delayLoadState;
  25716. geometry.delayLoadingFile = this.delayLoadingFile;
  25717. geometry._delayLoadingFunction = this._delayLoadingFunction;
  25718. for (kind in this._delayInfo) {
  25719. geometry._delayInfo = geometry._delayInfo || [];
  25720. geometry._delayInfo.push(kind);
  25721. }
  25722. // Bounding info
  25723. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  25724. return geometry;
  25725. };
  25726. // Statics
  25727. Geometry.ExtractFromMesh = function (mesh, id) {
  25728. var geometry = mesh._geometry;
  25729. if (!geometry) {
  25730. return null;
  25731. }
  25732. return geometry.copy(id);
  25733. };
  25734. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  25735. // be aware Math.random() could cause collisions
  25736. Geometry.RandomId = function () {
  25737. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  25738. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  25739. return v.toString(16);
  25740. });
  25741. };
  25742. return Geometry;
  25743. })();
  25744. BABYLON.Geometry = Geometry;
  25745. /////// Primitives //////////////////////////////////////////////
  25746. var Geometry;
  25747. (function (Geometry) {
  25748. var Primitives;
  25749. (function (Primitives) {
  25750. /// Abstract class
  25751. var _Primitive = (function (_super) {
  25752. __extends(_Primitive, _super);
  25753. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  25754. this._beingRegenerated = true;
  25755. this._canBeRegenerated = canBeRegenerated;
  25756. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  25757. this._beingRegenerated = false;
  25758. }
  25759. _Primitive.prototype.canBeRegenerated = function () {
  25760. return this._canBeRegenerated;
  25761. };
  25762. _Primitive.prototype.regenerate = function () {
  25763. if (!this._canBeRegenerated) {
  25764. return;
  25765. }
  25766. this._beingRegenerated = true;
  25767. this.setAllVerticesData(this._regenerateVertexData(), false);
  25768. this._beingRegenerated = false;
  25769. };
  25770. _Primitive.prototype.asNewGeometry = function (id) {
  25771. return _super.prototype.copy.call(this, id);
  25772. };
  25773. // overrides
  25774. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  25775. if (!this._beingRegenerated) {
  25776. return;
  25777. }
  25778. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  25779. };
  25780. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  25781. if (!this._beingRegenerated) {
  25782. return;
  25783. }
  25784. _super.prototype.setVerticesData.call(this, kind, data, false);
  25785. };
  25786. // to override
  25787. // protected
  25788. _Primitive.prototype._regenerateVertexData = function () {
  25789. throw new Error("Abstract method");
  25790. };
  25791. _Primitive.prototype.copy = function (id) {
  25792. throw new Error("Must be overriden in sub-classes.");
  25793. };
  25794. return _Primitive;
  25795. })(Geometry);
  25796. Primitives._Primitive = _Primitive;
  25797. var Ribbon = (function (_super) {
  25798. __extends(Ribbon, _super);
  25799. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  25800. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25801. this.pathArray = pathArray;
  25802. this.closeArray = closeArray;
  25803. this.closePath = closePath;
  25804. this.offset = offset;
  25805. this.side = side;
  25806. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25807. }
  25808. Ribbon.prototype._regenerateVertexData = function () {
  25809. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  25810. };
  25811. Ribbon.prototype.copy = function (id) {
  25812. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  25813. };
  25814. return Ribbon;
  25815. })(_Primitive);
  25816. Primitives.Ribbon = Ribbon;
  25817. var Box = (function (_super) {
  25818. __extends(Box, _super);
  25819. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  25820. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25821. this.size = size;
  25822. this.side = side;
  25823. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25824. }
  25825. Box.prototype._regenerateVertexData = function () {
  25826. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  25827. };
  25828. Box.prototype.copy = function (id) {
  25829. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  25830. };
  25831. return Box;
  25832. })(_Primitive);
  25833. Primitives.Box = Box;
  25834. var Sphere = (function (_super) {
  25835. __extends(Sphere, _super);
  25836. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  25837. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25838. this.segments = segments;
  25839. this.diameter = diameter;
  25840. this.side = side;
  25841. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25842. }
  25843. Sphere.prototype._regenerateVertexData = function () {
  25844. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  25845. };
  25846. Sphere.prototype.copy = function (id) {
  25847. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  25848. };
  25849. return Sphere;
  25850. })(_Primitive);
  25851. Primitives.Sphere = Sphere;
  25852. var Disc = (function (_super) {
  25853. __extends(Disc, _super);
  25854. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  25855. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25856. this.radius = radius;
  25857. this.tessellation = tessellation;
  25858. this.side = side;
  25859. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25860. }
  25861. Disc.prototype._regenerateVertexData = function () {
  25862. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  25863. };
  25864. Disc.prototype.copy = function (id) {
  25865. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  25866. };
  25867. return Disc;
  25868. })(_Primitive);
  25869. Primitives.Disc = Disc;
  25870. var Cylinder = (function (_super) {
  25871. __extends(Cylinder, _super);
  25872. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  25873. if (subdivisions === void 0) { subdivisions = 1; }
  25874. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25875. this.height = height;
  25876. this.diameterTop = diameterTop;
  25877. this.diameterBottom = diameterBottom;
  25878. this.tessellation = tessellation;
  25879. this.subdivisions = subdivisions;
  25880. this.side = side;
  25881. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25882. }
  25883. Cylinder.prototype._regenerateVertexData = function () {
  25884. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  25885. };
  25886. Cylinder.prototype.copy = function (id) {
  25887. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  25888. };
  25889. return Cylinder;
  25890. })(_Primitive);
  25891. Primitives.Cylinder = Cylinder;
  25892. var Torus = (function (_super) {
  25893. __extends(Torus, _super);
  25894. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  25895. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25896. this.diameter = diameter;
  25897. this.thickness = thickness;
  25898. this.tessellation = tessellation;
  25899. this.side = side;
  25900. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25901. }
  25902. Torus.prototype._regenerateVertexData = function () {
  25903. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  25904. };
  25905. Torus.prototype.copy = function (id) {
  25906. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  25907. };
  25908. return Torus;
  25909. })(_Primitive);
  25910. Primitives.Torus = Torus;
  25911. var Ground = (function (_super) {
  25912. __extends(Ground, _super);
  25913. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  25914. this.width = width;
  25915. this.height = height;
  25916. this.subdivisions = subdivisions;
  25917. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25918. }
  25919. Ground.prototype._regenerateVertexData = function () {
  25920. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  25921. };
  25922. Ground.prototype.copy = function (id) {
  25923. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  25924. };
  25925. return Ground;
  25926. })(_Primitive);
  25927. Primitives.Ground = Ground;
  25928. var TiledGround = (function (_super) {
  25929. __extends(TiledGround, _super);
  25930. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  25931. this.xmin = xmin;
  25932. this.zmin = zmin;
  25933. this.xmax = xmax;
  25934. this.zmax = zmax;
  25935. this.subdivisions = subdivisions;
  25936. this.precision = precision;
  25937. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25938. }
  25939. TiledGround.prototype._regenerateVertexData = function () {
  25940. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  25941. };
  25942. TiledGround.prototype.copy = function (id) {
  25943. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  25944. };
  25945. return TiledGround;
  25946. })(_Primitive);
  25947. Primitives.TiledGround = TiledGround;
  25948. var Plane = (function (_super) {
  25949. __extends(Plane, _super);
  25950. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  25951. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25952. this.size = size;
  25953. this.side = side;
  25954. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25955. }
  25956. Plane.prototype._regenerateVertexData = function () {
  25957. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  25958. };
  25959. Plane.prototype.copy = function (id) {
  25960. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  25961. };
  25962. return Plane;
  25963. })(_Primitive);
  25964. Primitives.Plane = Plane;
  25965. var TorusKnot = (function (_super) {
  25966. __extends(TorusKnot, _super);
  25967. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  25968. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25969. this.radius = radius;
  25970. this.tube = tube;
  25971. this.radialSegments = radialSegments;
  25972. this.tubularSegments = tubularSegments;
  25973. this.p = p;
  25974. this.q = q;
  25975. this.side = side;
  25976. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25977. }
  25978. TorusKnot.prototype._regenerateVertexData = function () {
  25979. 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 });
  25980. };
  25981. TorusKnot.prototype.copy = function (id) {
  25982. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  25983. };
  25984. return TorusKnot;
  25985. })(_Primitive);
  25986. Primitives.TorusKnot = TorusKnot;
  25987. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  25988. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  25989. })(BABYLON || (BABYLON = {}));
  25990. var BABYLON;
  25991. (function (BABYLON) {
  25992. var GroundMesh = (function (_super) {
  25993. __extends(GroundMesh, _super);
  25994. function GroundMesh(name, scene) {
  25995. _super.call(this, name, scene);
  25996. this.generateOctree = false;
  25997. this._worldInverse = new BABYLON.Matrix();
  25998. }
  25999. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  26000. get: function () {
  26001. return this._subdivisions;
  26002. },
  26003. enumerable: true,
  26004. configurable: true
  26005. });
  26006. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  26007. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  26008. this._subdivisions = chunksCount;
  26009. this.subdivide(this._subdivisions);
  26010. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  26011. };
  26012. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  26013. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  26014. this.getWorldMatrix().invertToRef(this._worldInverse);
  26015. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  26016. var pickInfo = this.intersects(ray);
  26017. if (pickInfo.hit) {
  26018. return pickInfo.pickedPoint.y;
  26019. }
  26020. return 0;
  26021. };
  26022. return GroundMesh;
  26023. })(BABYLON.Mesh);
  26024. BABYLON.GroundMesh = GroundMesh;
  26025. })(BABYLON || (BABYLON = {}));
  26026. var BABYLON;
  26027. (function (BABYLON) {
  26028. var LinesMesh = (function (_super) {
  26029. __extends(LinesMesh, _super);
  26030. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  26031. if (parent === void 0) { parent = null; }
  26032. _super.call(this, name, scene, parent, source, doNotCloneChildren);
  26033. this.color = new BABYLON.Color3(1, 1, 1);
  26034. this.alpha = 1;
  26035. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  26036. attributes: ["position"],
  26037. uniforms: ["worldViewProjection", "color"],
  26038. needAlphaBlending: true
  26039. });
  26040. }
  26041. Object.defineProperty(LinesMesh.prototype, "material", {
  26042. get: function () {
  26043. return this._colorShader;
  26044. },
  26045. enumerable: true,
  26046. configurable: true
  26047. });
  26048. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  26049. get: function () {
  26050. return false;
  26051. },
  26052. enumerable: true,
  26053. configurable: true
  26054. });
  26055. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  26056. get: function () {
  26057. return false;
  26058. },
  26059. enumerable: true,
  26060. configurable: true
  26061. });
  26062. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  26063. var engine = this.getScene().getEngine();
  26064. var indexToBind = this._geometry.getIndexBuffer();
  26065. // VBOs
  26066. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  26067. // Color
  26068. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  26069. };
  26070. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  26071. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  26072. return;
  26073. }
  26074. var engine = this.getScene().getEngine();
  26075. // Draw order
  26076. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  26077. };
  26078. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  26079. return null;
  26080. };
  26081. LinesMesh.prototype.dispose = function (doNotRecurse) {
  26082. this._colorShader.dispose();
  26083. _super.prototype.dispose.call(this, doNotRecurse);
  26084. };
  26085. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  26086. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  26087. };
  26088. return LinesMesh;
  26089. })(BABYLON.Mesh);
  26090. BABYLON.LinesMesh = LinesMesh;
  26091. })(BABYLON || (BABYLON = {}));
  26092. var BABYLON;
  26093. (function (BABYLON) {
  26094. var DebugLayer = (function () {
  26095. function DebugLayer(scene) {
  26096. var _this = this;
  26097. this._transformationMatrix = BABYLON.Matrix.Identity();
  26098. this._enabled = false;
  26099. this._labelsEnabled = false;
  26100. this._displayStatistics = true;
  26101. this._displayTree = false;
  26102. this._displayLogs = false;
  26103. this._identityMatrix = BABYLON.Matrix.Identity();
  26104. this.axisRatio = 0.02;
  26105. this.accentColor = "orange";
  26106. this._scene = scene;
  26107. this._syncPositions = function () {
  26108. var engine = _this._scene.getEngine();
  26109. var canvasRect = engine.getRenderingCanvasClientRect();
  26110. if (_this._showUI) {
  26111. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  26112. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  26113. _this._statsDiv.style.width = "400px";
  26114. _this._statsDiv.style.height = "auto";
  26115. _this._statsSubsetDiv.style.maxHeight = "240px";
  26116. _this._optionsDiv.style.left = "0px";
  26117. _this._optionsDiv.style.top = "10px";
  26118. _this._optionsDiv.style.width = "200px";
  26119. _this._optionsDiv.style.height = "auto";
  26120. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  26121. _this._logDiv.style.left = "0px";
  26122. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  26123. _this._logDiv.style.width = "600px";
  26124. _this._logDiv.style.height = "160px";
  26125. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  26126. _this._treeDiv.style.top = "10px";
  26127. _this._treeDiv.style.width = "300px";
  26128. _this._treeDiv.style.height = "auto";
  26129. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  26130. }
  26131. _this._globalDiv.style.left = canvasRect.left + "px";
  26132. _this._globalDiv.style.top = canvasRect.top + "px";
  26133. _this._drawingCanvas.style.left = "0px";
  26134. _this._drawingCanvas.style.top = "0px";
  26135. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  26136. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  26137. var devicePixelRatio = window.devicePixelRatio || 1;
  26138. var context = _this._drawingContext;
  26139. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  26140. context.mozBackingStorePixelRatio ||
  26141. context.msBackingStorePixelRatio ||
  26142. context.oBackingStorePixelRatio ||
  26143. context.backingStorePixelRatio || 1;
  26144. _this._ratio = devicePixelRatio / backingStoreRatio;
  26145. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  26146. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  26147. };
  26148. this._onCanvasClick = function (evt) {
  26149. _this._clickPosition = {
  26150. x: evt.clientX * _this._ratio,
  26151. y: evt.clientY * _this._ratio
  26152. };
  26153. };
  26154. this._syncUI = function () {
  26155. if (_this._showUI) {
  26156. if (_this._displayStatistics) {
  26157. _this._displayStats();
  26158. _this._statsDiv.style.display = "";
  26159. }
  26160. else {
  26161. _this._statsDiv.style.display = "none";
  26162. }
  26163. if (_this._displayLogs) {
  26164. _this._logDiv.style.display = "";
  26165. }
  26166. else {
  26167. _this._logDiv.style.display = "none";
  26168. }
  26169. if (_this._displayTree) {
  26170. _this._treeDiv.style.display = "";
  26171. if (_this._needToRefreshMeshesTree) {
  26172. _this._needToRefreshMeshesTree = false;
  26173. _this._refreshMeshesTreeContent();
  26174. }
  26175. }
  26176. else {
  26177. _this._treeDiv.style.display = "none";
  26178. }
  26179. }
  26180. };
  26181. this._syncData = function () {
  26182. if (_this._labelsEnabled || !_this._showUI) {
  26183. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  26184. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  26185. var engine = _this._scene.getEngine();
  26186. var viewport = _this._camera.viewport;
  26187. var globalViewport = viewport.toGlobal(engine);
  26188. // Meshes
  26189. var meshes = _this._camera.getActiveMeshes();
  26190. for (var index = 0; index < meshes.length; index++) {
  26191. var mesh = meshes.data[index];
  26192. var position = mesh.getBoundingInfo().boundingSphere.center;
  26193. var projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  26194. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  26195. _this._renderAxis(projectedPosition, mesh, globalViewport);
  26196. }
  26197. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  26198. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  26199. }
  26200. }
  26201. // Cameras
  26202. var cameras = _this._scene.cameras;
  26203. for (index = 0; index < cameras.length; index++) {
  26204. var camera = cameras[index];
  26205. if (camera === _this._camera) {
  26206. continue;
  26207. }
  26208. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  26209. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  26210. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  26211. _this._camera.detachControl(engine.getRenderingCanvas());
  26212. _this._camera = camera;
  26213. _this._camera.attachControl(engine.getRenderingCanvas());
  26214. }, function () { return "purple"; });
  26215. }
  26216. }
  26217. // Lights
  26218. var lights = _this._scene.lights;
  26219. for (index = 0; index < lights.length; index++) {
  26220. var light = lights[index];
  26221. if (light.position) {
  26222. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  26223. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  26224. _this._renderLabel(light.name, projectedPosition, -20, function () {
  26225. light.setEnabled(!light.isEnabled());
  26226. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  26227. }
  26228. }
  26229. }
  26230. }
  26231. _this._clickPosition = undefined;
  26232. };
  26233. }
  26234. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  26235. while (this._treeSubsetDiv.hasChildNodes()) {
  26236. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  26237. }
  26238. // Add meshes
  26239. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  26240. sortedArray.sort(function (a, b) {
  26241. if (a.name === b.name) {
  26242. return 0;
  26243. }
  26244. return (a.name > b.name) ? 1 : -1;
  26245. });
  26246. for (var index = 0; index < sortedArray.length; index++) {
  26247. var mesh = sortedArray[index];
  26248. if (!mesh.isEnabled()) {
  26249. continue;
  26250. }
  26251. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  26252. m.isVisible = element.checked;
  26253. }, mesh);
  26254. }
  26255. };
  26256. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  26257. this._drawingContext.beginPath();
  26258. this._drawingContext.moveTo(zero.x, zero.y);
  26259. this._drawingContext.lineTo(unit.x, unit.y);
  26260. this._drawingContext.strokeStyle = color;
  26261. this._drawingContext.lineWidth = 4;
  26262. this._drawingContext.stroke();
  26263. this._drawingContext.font = "normal 14px Segoe UI";
  26264. this._drawingContext.fillStyle = color;
  26265. this._drawingContext.fillText(label, unitText.x, unitText.y);
  26266. };
  26267. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  26268. var position = mesh.getBoundingInfo().boundingSphere.center;
  26269. var worldMatrix = mesh.getWorldMatrix();
  26270. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  26271. var unit = (unprojectedVector.subtract(position)).length();
  26272. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  26273. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  26274. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  26275. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  26276. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  26277. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  26278. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  26279. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  26280. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  26281. };
  26282. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  26283. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  26284. this._drawingContext.font = "normal 12px Segoe UI";
  26285. var textMetrics = this._drawingContext.measureText(text);
  26286. var centerX = projectedPosition.x - textMetrics.width / 2;
  26287. var centerY = projectedPosition.y;
  26288. var clientRect = this._drawingCanvas.getBoundingClientRect();
  26289. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  26290. onClick();
  26291. }
  26292. this._drawingContext.beginPath();
  26293. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  26294. this._drawingContext.fillStyle = getFillStyle();
  26295. this._drawingContext.globalAlpha = 0.5;
  26296. this._drawingContext.fill();
  26297. this._drawingContext.globalAlpha = 1.0;
  26298. this._drawingContext.strokeStyle = '#FFFFFF';
  26299. this._drawingContext.lineWidth = 1;
  26300. this._drawingContext.stroke();
  26301. this._drawingContext.fillStyle = "#FFFFFF";
  26302. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  26303. this._drawingContext.beginPath();
  26304. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  26305. this._drawingContext.fill();
  26306. }
  26307. };
  26308. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  26309. if (!this._clickPosition) {
  26310. return false;
  26311. }
  26312. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  26313. return false;
  26314. }
  26315. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  26316. return false;
  26317. }
  26318. return true;
  26319. };
  26320. DebugLayer.prototype.isVisible = function () {
  26321. return this._enabled;
  26322. };
  26323. DebugLayer.prototype.hide = function () {
  26324. if (!this._enabled) {
  26325. return;
  26326. }
  26327. this._enabled = false;
  26328. var engine = this._scene.getEngine();
  26329. this._scene.unregisterBeforeRender(this._syncData);
  26330. this._scene.unregisterAfterRender(this._syncUI);
  26331. this._rootElement.removeChild(this._globalDiv);
  26332. window.removeEventListener("resize", this._syncPositions);
  26333. this._scene.forceShowBoundingBoxes = false;
  26334. this._scene.forceWireframe = false;
  26335. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  26336. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  26337. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  26338. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  26339. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  26340. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  26341. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  26342. BABYLON.StandardMaterial.LightmapEnabled = true;
  26343. this._scene.shadowsEnabled = true;
  26344. this._scene.particlesEnabled = true;
  26345. this._scene.postProcessesEnabled = true;
  26346. this._scene.collisionsEnabled = true;
  26347. this._scene.lightsEnabled = true;
  26348. this._scene.texturesEnabled = true;
  26349. this._scene.lensFlaresEnabled = true;
  26350. this._scene.proceduralTexturesEnabled = true;
  26351. this._scene.renderTargetsEnabled = true;
  26352. this._scene.probesEnabled = true;
  26353. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  26354. };
  26355. DebugLayer.prototype.show = function (showUI, camera, rootElement) {
  26356. if (showUI === void 0) { showUI = true; }
  26357. if (camera === void 0) { camera = null; }
  26358. if (rootElement === void 0) { rootElement = null; }
  26359. if (this._enabled) {
  26360. return;
  26361. }
  26362. this._enabled = true;
  26363. if (camera) {
  26364. this._camera = camera;
  26365. }
  26366. else {
  26367. this._camera = this._scene.activeCamera;
  26368. }
  26369. this._showUI = showUI;
  26370. var engine = this._scene.getEngine();
  26371. this._globalDiv = document.createElement("div");
  26372. this._rootElement = rootElement || document.body;
  26373. this._rootElement.appendChild(this._globalDiv);
  26374. this._generateDOMelements();
  26375. window.addEventListener("resize", this._syncPositions);
  26376. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  26377. this._syncPositions();
  26378. this._scene.registerBeforeRender(this._syncData);
  26379. this._scene.registerAfterRender(this._syncUI);
  26380. };
  26381. DebugLayer.prototype._clearLabels = function () {
  26382. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  26383. for (var index = 0; index < this._scene.meshes.length; index++) {
  26384. var mesh = this._scene.meshes[index];
  26385. mesh.renderOverlay = false;
  26386. }
  26387. };
  26388. DebugLayer.prototype._generateheader = function (root, text) {
  26389. var header = document.createElement("div");
  26390. header.innerHTML = text + "&nbsp;";
  26391. header.style.textAlign = "right";
  26392. header.style.width = "100%";
  26393. header.style.color = "white";
  26394. header.style.backgroundColor = "Black";
  26395. header.style.padding = "5px 5px 4px 0px";
  26396. header.style.marginLeft = "-5px";
  26397. header.style.fontWeight = "bold";
  26398. root.appendChild(header);
  26399. };
  26400. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  26401. var label = document.createElement("label");
  26402. label.innerHTML = title;
  26403. label.style.color = color;
  26404. root.appendChild(label);
  26405. root.appendChild(document.createElement("br"));
  26406. };
  26407. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  26408. if (tag === void 0) { tag = null; }
  26409. var label = document.createElement("label");
  26410. var boundingBoxesCheckbox = document.createElement("input");
  26411. boundingBoxesCheckbox.type = "checkbox";
  26412. boundingBoxesCheckbox.checked = initialState;
  26413. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  26414. task(evt.target, tag);
  26415. });
  26416. label.appendChild(boundingBoxesCheckbox);
  26417. var container = document.createElement("span");
  26418. var leftPart = document.createElement("span");
  26419. var rightPart = document.createElement("span");
  26420. rightPart.style.cssFloat = "right";
  26421. leftPart.innerHTML = leftTitle;
  26422. rightPart.innerHTML = rightTitle;
  26423. rightPart.style.fontSize = "12px";
  26424. rightPart.style.maxWidth = "200px";
  26425. container.appendChild(leftPart);
  26426. container.appendChild(rightPart);
  26427. label.appendChild(container);
  26428. root.appendChild(label);
  26429. root.appendChild(document.createElement("br"));
  26430. };
  26431. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  26432. if (tag === void 0) { tag = null; }
  26433. var label = document.createElement("label");
  26434. var checkBox = document.createElement("input");
  26435. checkBox.type = "checkbox";
  26436. checkBox.checked = initialState;
  26437. checkBox.addEventListener("change", function (evt) {
  26438. task(evt.target, tag);
  26439. });
  26440. label.appendChild(checkBox);
  26441. label.appendChild(document.createTextNode(title));
  26442. root.appendChild(label);
  26443. root.appendChild(document.createElement("br"));
  26444. };
  26445. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  26446. if (tag === void 0) { tag = null; }
  26447. var button = document.createElement("button");
  26448. button.innerHTML = title;
  26449. button.style.height = "24px";
  26450. button.style.color = "#444444";
  26451. button.style.border = "1px solid white";
  26452. button.className = "debugLayerButton";
  26453. button.addEventListener("click", function (evt) {
  26454. task(evt.target, tag);
  26455. });
  26456. root.appendChild(button);
  26457. root.appendChild(document.createElement("br"));
  26458. };
  26459. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  26460. if (tag === void 0) { tag = null; }
  26461. var label = document.createElement("label");
  26462. var boundingBoxesRadio = document.createElement("input");
  26463. boundingBoxesRadio.type = "radio";
  26464. boundingBoxesRadio.name = name;
  26465. boundingBoxesRadio.checked = initialState;
  26466. boundingBoxesRadio.addEventListener("change", function (evt) {
  26467. task(evt.target, tag);
  26468. });
  26469. label.appendChild(boundingBoxesRadio);
  26470. label.appendChild(document.createTextNode(title));
  26471. root.appendChild(label);
  26472. root.appendChild(document.createElement("br"));
  26473. };
  26474. DebugLayer.prototype._generateDOMelements = function () {
  26475. var _this = this;
  26476. this._globalDiv.id = "DebugLayer";
  26477. this._globalDiv.style.position = "absolute";
  26478. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  26479. this._globalDiv.style.fontSize = "14px";
  26480. this._globalDiv.style.color = "white";
  26481. // Drawing canvas
  26482. this._drawingCanvas = document.createElement("canvas");
  26483. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  26484. this._drawingCanvas.style.position = "absolute";
  26485. this._drawingCanvas.style.pointerEvents = "none";
  26486. this._drawingCanvas.style.backgroundColor = "transparent";
  26487. this._drawingContext = this._drawingCanvas.getContext("2d");
  26488. this._globalDiv.appendChild(this._drawingCanvas);
  26489. if (this._showUI) {
  26490. var background = "rgba(128, 128, 128, 0.4)";
  26491. var border = "rgb(180, 180, 180) solid 1px";
  26492. // Stats
  26493. this._statsDiv = document.createElement("div");
  26494. this._statsDiv.id = "DebugLayerStats";
  26495. this._statsDiv.style.border = border;
  26496. this._statsDiv.style.position = "absolute";
  26497. this._statsDiv.style.background = background;
  26498. this._statsDiv.style.padding = "0px 0px 0px 5px";
  26499. this._generateheader(this._statsDiv, "STATISTICS");
  26500. this._statsSubsetDiv = document.createElement("div");
  26501. this._statsSubsetDiv.style.paddingTop = "5px";
  26502. this._statsSubsetDiv.style.paddingBottom = "5px";
  26503. this._statsSubsetDiv.style.overflowY = "auto";
  26504. this._statsDiv.appendChild(this._statsSubsetDiv);
  26505. // Tree
  26506. this._treeDiv = document.createElement("div");
  26507. this._treeDiv.id = "DebugLayerTree";
  26508. this._treeDiv.style.border = border;
  26509. this._treeDiv.style.position = "absolute";
  26510. this._treeDiv.style.background = background;
  26511. this._treeDiv.style.padding = "0px 0px 0px 5px";
  26512. this._treeDiv.style.display = "none";
  26513. this._generateheader(this._treeDiv, "MESHES TREE");
  26514. this._treeSubsetDiv = document.createElement("div");
  26515. this._treeSubsetDiv.style.paddingTop = "5px";
  26516. this._treeSubsetDiv.style.paddingRight = "5px";
  26517. this._treeSubsetDiv.style.overflowY = "auto";
  26518. this._treeSubsetDiv.style.maxHeight = "300px";
  26519. this._treeDiv.appendChild(this._treeSubsetDiv);
  26520. this._needToRefreshMeshesTree = true;
  26521. // Logs
  26522. this._logDiv = document.createElement("div");
  26523. this._logDiv.style.border = border;
  26524. this._logDiv.id = "DebugLayerLogs";
  26525. this._logDiv.style.position = "absolute";
  26526. this._logDiv.style.background = background;
  26527. this._logDiv.style.padding = "0px 0px 0px 5px";
  26528. this._logDiv.style.display = "none";
  26529. this._generateheader(this._logDiv, "LOGS");
  26530. this._logSubsetDiv = document.createElement("div");
  26531. this._logSubsetDiv.style.height = "127px";
  26532. this._logSubsetDiv.style.paddingTop = "5px";
  26533. this._logSubsetDiv.style.overflowY = "auto";
  26534. this._logSubsetDiv.style.fontSize = "12px";
  26535. this._logSubsetDiv.style.fontFamily = "consolas";
  26536. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  26537. this._logDiv.appendChild(this._logSubsetDiv);
  26538. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  26539. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  26540. };
  26541. // Options
  26542. this._optionsDiv = document.createElement("div");
  26543. this._optionsDiv.id = "DebugLayerOptions";
  26544. this._optionsDiv.style.border = border;
  26545. this._optionsDiv.style.position = "absolute";
  26546. this._optionsDiv.style.background = background;
  26547. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  26548. this._optionsDiv.style.overflowY = "auto";
  26549. this._generateheader(this._optionsDiv, "OPTIONS");
  26550. this._optionsSubsetDiv = document.createElement("div");
  26551. this._optionsSubsetDiv.style.paddingTop = "5px";
  26552. this._optionsSubsetDiv.style.paddingBottom = "5px";
  26553. this._optionsSubsetDiv.style.overflowY = "auto";
  26554. this._optionsSubsetDiv.style.maxHeight = "200px";
  26555. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  26556. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  26557. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  26558. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  26559. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  26560. _this._displayTree = element.checked;
  26561. _this._needToRefreshMeshesTree = true;
  26562. });
  26563. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  26564. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  26565. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  26566. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  26567. _this._labelsEnabled = element.checked;
  26568. if (!_this._labelsEnabled) {
  26569. _this._clearLabels();
  26570. }
  26571. });
  26572. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  26573. if (element.checked) {
  26574. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  26575. }
  26576. else {
  26577. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  26578. }
  26579. });
  26580. ;
  26581. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  26582. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  26583. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  26584. if (element.checked) {
  26585. _this._scene.forceWireframe = false;
  26586. _this._scene.forcePointsCloud = false;
  26587. }
  26588. });
  26589. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  26590. if (element.checked) {
  26591. _this._scene.forceWireframe = true;
  26592. _this._scene.forcePointsCloud = false;
  26593. }
  26594. });
  26595. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  26596. if (element.checked) {
  26597. _this._scene.forceWireframe = false;
  26598. _this._scene.forcePointsCloud = true;
  26599. }
  26600. });
  26601. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  26602. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  26603. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  26604. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  26605. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  26606. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  26607. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  26608. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  26609. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  26610. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  26611. this._generateCheckBox(this._optionsSubsetDiv, "Lightmap", BABYLON.StandardMaterial.LightmapEnabled, function (element) { BABYLON.StandardMaterial.LightmapEnabled = element.checked; });
  26612. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  26613. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  26614. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  26615. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  26616. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  26617. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  26618. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  26619. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  26620. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  26621. this._generateCheckBox(this._optionsSubsetDiv, "Probes", this._scene.probesEnabled, function (element) { _this._scene.probesEnabled = element.checked; });
  26622. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  26623. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  26624. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  26625. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  26626. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  26627. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  26628. if (BABYLON.AudioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  26629. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  26630. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  26631. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  26632. if (element.checked) {
  26633. _this._scene.headphone = true;
  26634. }
  26635. });
  26636. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  26637. if (element.checked) {
  26638. _this._scene.headphone = false;
  26639. }
  26640. });
  26641. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  26642. _this._scene.audioEnabled = !element.checked;
  26643. });
  26644. }
  26645. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  26646. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  26647. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  26648. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  26649. this._globalDiv.appendChild(this._statsDiv);
  26650. this._globalDiv.appendChild(this._logDiv);
  26651. this._globalDiv.appendChild(this._optionsDiv);
  26652. this._globalDiv.appendChild(this._treeDiv);
  26653. }
  26654. };
  26655. DebugLayer.prototype._displayStats = function () {
  26656. var scene = this._scene;
  26657. var engine = scene.getEngine();
  26658. var glInfo = engine.getGlInfo();
  26659. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  26660. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  26661. + "<b>Count</b><br>"
  26662. + "Total meshes: " + scene.meshes.length + "<br>"
  26663. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  26664. + "Total materials: " + scene.materials.length + "<br>"
  26665. + "Total textures: " + scene.textures.length + "<br>"
  26666. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  26667. + "Active indices: " + scene.getActiveIndices() + "<br>"
  26668. + "Active bones: " + scene.getActiveBones() + "<br>"
  26669. + "Active particles: " + scene.getActiveParticles() + "<br>"
  26670. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>"
  26671. + "<b>Duration</b><br>"
  26672. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  26673. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  26674. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  26675. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  26676. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  26677. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  26678. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br><br>"
  26679. + "</div>"
  26680. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  26681. + "<b>Extensions</b><br>"
  26682. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  26683. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  26684. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  26685. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br>"
  26686. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  26687. + "<b>Caps.</b><br>"
  26688. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  26689. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  26690. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br><br><br>"
  26691. + "</div><br>"
  26692. + "<b>Info</b><br>"
  26693. + glInfo.version + "<br>"
  26694. + glInfo.renderer + "<br>";
  26695. if (this.customStatsFunction) {
  26696. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  26697. }
  26698. };
  26699. return DebugLayer;
  26700. })();
  26701. BABYLON.DebugLayer = DebugLayer;
  26702. })(BABYLON || (BABYLON = {}));
  26703. var BABYLON;
  26704. (function (BABYLON) {
  26705. var DefaultLoadingScreen = (function () {
  26706. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  26707. var _this = this;
  26708. if (_loadingText === void 0) { _loadingText = ""; }
  26709. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  26710. this._renderingCanvas = _renderingCanvas;
  26711. this._loadingText = _loadingText;
  26712. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  26713. // Resize
  26714. this._resizeLoadingUI = function () {
  26715. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  26716. _this._loadingDiv.style.position = "absolute";
  26717. _this._loadingDiv.style.left = canvasRect.left + "px";
  26718. _this._loadingDiv.style.top = canvasRect.top + "px";
  26719. _this._loadingDiv.style.width = canvasRect.width + "px";
  26720. _this._loadingDiv.style.height = canvasRect.height + "px";
  26721. };
  26722. }
  26723. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  26724. var _this = this;
  26725. this._loadingDiv = document.createElement("div");
  26726. this._loadingDiv.style.opacity = "0";
  26727. this._loadingDiv.style.transition = "opacity 1.5s ease";
  26728. // Loading text
  26729. this._loadingTextDiv = document.createElement("div");
  26730. this._loadingTextDiv.style.position = "absolute";
  26731. this._loadingTextDiv.style.left = "0";
  26732. this._loadingTextDiv.style.top = "50%";
  26733. this._loadingTextDiv.style.marginTop = "80px";
  26734. this._loadingTextDiv.style.width = "100%";
  26735. this._loadingTextDiv.style.height = "20px";
  26736. this._loadingTextDiv.style.fontFamily = "Arial";
  26737. this._loadingTextDiv.style.fontSize = "14px";
  26738. this._loadingTextDiv.style.color = "white";
  26739. this._loadingTextDiv.style.textAlign = "center";
  26740. this._loadingTextDiv.innerHTML = "Loading";
  26741. this._loadingDiv.appendChild(this._loadingTextDiv);
  26742. //set the predefined text
  26743. this._loadingTextDiv.innerHTML = this._loadingText;
  26744. // Loading img
  26745. var imgBack = new Image();
  26746. 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==";
  26747. imgBack.style.position = "absolute";
  26748. imgBack.style.left = "50%";
  26749. imgBack.style.top = "50%";
  26750. imgBack.style.marginLeft = "-50px";
  26751. imgBack.style.marginTop = "-50px";
  26752. imgBack.style.transition = "transform 1.0s ease";
  26753. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  26754. var deg = 360;
  26755. var onTransitionEnd = function () {
  26756. deg += 360;
  26757. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  26758. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  26759. };
  26760. imgBack.addEventListener("transitionend", onTransitionEnd);
  26761. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  26762. this._loadingDiv.appendChild(imgBack);
  26763. // front image
  26764. var imgFront = new Image();
  26765. 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=";
  26766. imgFront.style.position = "absolute";
  26767. imgFront.style.left = "50%";
  26768. imgFront.style.top = "50%";
  26769. imgFront.style.marginLeft = "-50px";
  26770. imgFront.style.marginTop = "-50px";
  26771. this._loadingDiv.appendChild(imgFront);
  26772. this._resizeLoadingUI();
  26773. window.addEventListener("resize", this._resizeLoadingUI);
  26774. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  26775. document.body.appendChild(this._loadingDiv);
  26776. setTimeout(function () {
  26777. _this._loadingDiv.style.opacity = "1";
  26778. imgBack.style.transform = "rotateZ(360deg)";
  26779. imgBack.style.webkitTransform = "rotateZ(360deg)";
  26780. }, 0);
  26781. };
  26782. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  26783. var _this = this;
  26784. if (!this._loadingDiv) {
  26785. return;
  26786. }
  26787. var onTransitionEnd = function () {
  26788. if (!_this._loadingDiv) {
  26789. return;
  26790. }
  26791. document.body.removeChild(_this._loadingDiv);
  26792. window.removeEventListener("resize", _this._resizeLoadingUI);
  26793. _this._loadingDiv = null;
  26794. };
  26795. this._loadingDiv.style.opacity = "0";
  26796. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  26797. };
  26798. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  26799. set: function (text) {
  26800. this._loadingText = text;
  26801. if (this._loadingTextDiv) {
  26802. this._loadingTextDiv.innerHTML = this._loadingText;
  26803. }
  26804. },
  26805. enumerable: true,
  26806. configurable: true
  26807. });
  26808. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  26809. get: function () {
  26810. return this._loadingDivBackgroundColor;
  26811. },
  26812. set: function (color) {
  26813. this._loadingDivBackgroundColor = color;
  26814. if (!this._loadingDiv) {
  26815. return;
  26816. }
  26817. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  26818. },
  26819. enumerable: true,
  26820. configurable: true
  26821. });
  26822. return DefaultLoadingScreen;
  26823. })();
  26824. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  26825. })(BABYLON || (BABYLON = {}));
  26826. var BABYLON;
  26827. (function (BABYLON) {
  26828. var SIMDVector3 = (function () {
  26829. function SIMDVector3() {
  26830. }
  26831. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  26832. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  26833. var m0 = SIMD.float32x4.load(transformation.m, 0);
  26834. var m1 = SIMD.float32x4.load(transformation.m, 4);
  26835. var m2 = SIMD.float32x4.load(transformation.m, 8);
  26836. var m3 = SIMD.float32x4.load(transformation.m, 12);
  26837. 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));
  26838. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  26839. SIMD.float32x4.storeXYZ(result._data, 0, r);
  26840. };
  26841. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  26842. var v0 = SIMD.float32x4.splat(x);
  26843. var v1 = SIMD.float32x4.splat(y);
  26844. var v2 = SIMD.float32x4.splat(z);
  26845. var m0 = SIMD.float32x4.load(transformation.m, 0);
  26846. var m1 = SIMD.float32x4.load(transformation.m, 4);
  26847. var m2 = SIMD.float32x4.load(transformation.m, 8);
  26848. var m3 = SIMD.float32x4.load(transformation.m, 12);
  26849. 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));
  26850. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  26851. SIMD.float32x4.storeXYZ(result._data, 0, r);
  26852. };
  26853. return SIMDVector3;
  26854. })();
  26855. BABYLON.SIMDVector3 = SIMDVector3;
  26856. var SIMDMatrix = (function () {
  26857. function SIMDMatrix() {
  26858. }
  26859. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  26860. if (offset === void 0) { offset = 0; }
  26861. var tm = this.m;
  26862. var om = other.m;
  26863. var om0 = SIMD.float32x4.load(om, 0);
  26864. var om1 = SIMD.float32x4.load(om, 4);
  26865. var om2 = SIMD.float32x4.load(om, 8);
  26866. var om3 = SIMD.float32x4.load(om, 12);
  26867. var tm0 = SIMD.float32x4.load(tm, 0);
  26868. 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)))));
  26869. var tm1 = SIMD.float32x4.load(tm, 4);
  26870. 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)))));
  26871. var tm2 = SIMD.float32x4.load(tm, 8);
  26872. 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)))));
  26873. var tm3 = SIMD.float32x4.load(tm, 12);
  26874. 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)))));
  26875. };
  26876. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  26877. var src = this.m;
  26878. var dest = other.m;
  26879. var row0, row1, row2, row3;
  26880. var tmp1;
  26881. var minor0, minor1, minor2, minor3;
  26882. var det;
  26883. // Load the 4 rows
  26884. var src0 = SIMD.float32x4.load(src, 0);
  26885. var src1 = SIMD.float32x4.load(src, 4);
  26886. var src2 = SIMD.float32x4.load(src, 8);
  26887. var src3 = SIMD.float32x4.load(src, 12);
  26888. // Transpose the source matrix. Sort of. Not a true transpose operation
  26889. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  26890. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  26891. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  26892. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  26893. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  26894. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  26895. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  26896. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  26897. // This is a true transposition, but it will lead to an incorrect result
  26898. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  26899. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  26900. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  26901. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  26902. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  26903. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  26904. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  26905. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  26906. // ----
  26907. tmp1 = SIMD.float32x4.mul(row2, row3);
  26908. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  26909. minor0 = SIMD.float32x4.mul(row1, tmp1);
  26910. minor1 = SIMD.float32x4.mul(row0, tmp1);
  26911. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  26912. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  26913. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  26914. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  26915. // ----
  26916. tmp1 = SIMD.float32x4.mul(row1, row2);
  26917. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  26918. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  26919. minor3 = SIMD.float32x4.mul(row0, tmp1);
  26920. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  26921. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  26922. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  26923. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  26924. // ----
  26925. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  26926. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  26927. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  26928. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  26929. minor2 = SIMD.float32x4.mul(row0, tmp1);
  26930. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  26931. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  26932. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  26933. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  26934. // ----
  26935. tmp1 = SIMD.float32x4.mul(row0, row1);
  26936. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  26937. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  26938. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  26939. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  26940. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  26941. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  26942. // ----
  26943. tmp1 = SIMD.float32x4.mul(row0, row3);
  26944. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  26945. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  26946. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  26947. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  26948. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  26949. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  26950. // ----
  26951. tmp1 = SIMD.float32x4.mul(row0, row2);
  26952. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  26953. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  26954. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  26955. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  26956. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  26957. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  26958. // Compute determinant
  26959. det = SIMD.float32x4.mul(row0, minor0);
  26960. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  26961. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  26962. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  26963. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  26964. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  26965. // These shuffles aren't necessary if the faulty transposition is done
  26966. // up at the top of this function.
  26967. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  26968. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  26969. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  26970. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  26971. // Compute final values by multiplying with 1/det
  26972. minor0 = SIMD.float32x4.mul(det, minor0);
  26973. minor1 = SIMD.float32x4.mul(det, minor1);
  26974. minor2 = SIMD.float32x4.mul(det, minor2);
  26975. minor3 = SIMD.float32x4.mul(det, minor3);
  26976. SIMD.float32x4.store(dest, 0, minor0);
  26977. SIMD.float32x4.store(dest, 4, minor1);
  26978. SIMD.float32x4.store(dest, 8, minor2);
  26979. SIMD.float32x4.store(dest, 12, minor3);
  26980. return this;
  26981. };
  26982. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  26983. var out = result.m;
  26984. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  26985. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  26986. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  26987. // cc.kmVec3Subtract(f, pCenter, pEye);
  26988. var f = SIMD.float32x4.sub(center, eye);
  26989. // cc.kmVec3Normalize(f, f);
  26990. var tmp = SIMD.float32x4.mul(f, f);
  26991. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  26992. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  26993. // cc.kmVec3Assign(up, pUp);
  26994. // cc.kmVec3Normalize(up, up);
  26995. tmp = SIMD.float32x4.mul(up, up);
  26996. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  26997. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  26998. // cc.kmVec3Cross(s, f, up);
  26999. 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)));
  27000. // cc.kmVec3Normalize(s, s);
  27001. tmp = SIMD.float32x4.mul(s, s);
  27002. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  27003. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  27004. // cc.kmVec3Cross(u, s, f);
  27005. 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)));
  27006. // cc.kmVec3Normalize(s, s);
  27007. tmp = SIMD.float32x4.mul(s, s);
  27008. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  27009. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  27010. var zero = SIMD.float32x4.splat(0.0);
  27011. s = SIMD.float32x4.neg(s);
  27012. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  27013. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  27014. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  27015. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  27016. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  27017. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  27018. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  27019. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  27020. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  27021. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  27022. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  27023. var b3 = SIMD.float32x4.neg(eye);
  27024. b3 = SIMD.float32x4.withW(b3, 1.0);
  27025. 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)))));
  27026. 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)))));
  27027. 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)))));
  27028. 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)))));
  27029. };
  27030. return SIMDMatrix;
  27031. })();
  27032. BABYLON.SIMDMatrix = SIMDMatrix;
  27033. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  27034. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  27035. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  27036. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  27037. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  27038. var SIMDHelper = (function () {
  27039. function SIMDHelper() {
  27040. }
  27041. Object.defineProperty(SIMDHelper, "IsEnabled", {
  27042. get: function () {
  27043. return SIMDHelper._isEnabled;
  27044. },
  27045. enumerable: true,
  27046. configurable: true
  27047. });
  27048. SIMDHelper.DisableSIMD = function () {
  27049. // Replace functions
  27050. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  27051. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  27052. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  27053. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  27054. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  27055. SIMDHelper._isEnabled = false;
  27056. };
  27057. SIMDHelper.EnableSIMD = function () {
  27058. if (window.SIMD === undefined) {
  27059. return;
  27060. }
  27061. // Replace functions
  27062. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  27063. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  27064. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  27065. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  27066. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  27067. Object.defineProperty(BABYLON.Vector3.prototype, "x", {
  27068. get: function () { return this._data[0]; },
  27069. set: function (value) {
  27070. if (!this._data) {
  27071. this._data = new Float32Array(3);
  27072. }
  27073. this._data[0] = value;
  27074. }
  27075. });
  27076. Object.defineProperty(BABYLON.Vector3.prototype, "y", {
  27077. get: function () { return this._data[1]; },
  27078. set: function (value) {
  27079. this._data[1] = value;
  27080. }
  27081. });
  27082. Object.defineProperty(BABYLON.Vector3.prototype, "z", {
  27083. get: function () { return this._data[2]; },
  27084. set: function (value) {
  27085. this._data[2] = value;
  27086. }
  27087. });
  27088. SIMDHelper._isEnabled = true;
  27089. };
  27090. SIMDHelper._isEnabled = false;
  27091. return SIMDHelper;
  27092. })();
  27093. BABYLON.SIMDHelper = SIMDHelper;
  27094. })(BABYLON || (BABYLON = {}));
  27095. var BABYLON;
  27096. (function (BABYLON) {
  27097. var ShaderMaterial = (function (_super) {
  27098. __extends(ShaderMaterial, _super);
  27099. function ShaderMaterial(name, scene, shaderPath, options) {
  27100. _super.call(this, name, scene);
  27101. this._textures = new Array();
  27102. this._floats = new Array();
  27103. this._floatsArrays = {};
  27104. this._colors3 = new Array();
  27105. this._colors4 = new Array();
  27106. this._vectors2 = new Array();
  27107. this._vectors3 = new Array();
  27108. this._vectors4 = new Array();
  27109. this._matrices = new Array();
  27110. this._matrices3x3 = new Array();
  27111. this._matrices2x2 = new Array();
  27112. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  27113. this._shaderPath = shaderPath;
  27114. options.needAlphaBlending = options.needAlphaBlending || false;
  27115. options.needAlphaTesting = options.needAlphaTesting || false;
  27116. options.attributes = options.attributes || ["position", "normal", "uv"];
  27117. options.uniforms = options.uniforms || ["worldViewProjection"];
  27118. options.samplers = options.samplers || [];
  27119. options.defines = options.defines || [];
  27120. this._options = options;
  27121. }
  27122. ShaderMaterial.prototype.needAlphaBlending = function () {
  27123. return this._options.needAlphaBlending;
  27124. };
  27125. ShaderMaterial.prototype.needAlphaTesting = function () {
  27126. return this._options.needAlphaTesting;
  27127. };
  27128. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  27129. if (this._options.uniforms.indexOf(uniformName) === -1) {
  27130. this._options.uniforms.push(uniformName);
  27131. }
  27132. };
  27133. ShaderMaterial.prototype.setTexture = function (name, texture) {
  27134. if (this._options.samplers.indexOf(name) === -1) {
  27135. this._options.samplers.push(name);
  27136. }
  27137. this._textures[name] = texture;
  27138. return this;
  27139. };
  27140. ShaderMaterial.prototype.setFloat = function (name, value) {
  27141. this._checkUniform(name);
  27142. this._floats[name] = value;
  27143. return this;
  27144. };
  27145. ShaderMaterial.prototype.setFloats = function (name, value) {
  27146. this._checkUniform(name);
  27147. this._floatsArrays[name] = value;
  27148. return this;
  27149. };
  27150. ShaderMaterial.prototype.setColor3 = function (name, value) {
  27151. this._checkUniform(name);
  27152. this._colors3[name] = value;
  27153. return this;
  27154. };
  27155. ShaderMaterial.prototype.setColor4 = function (name, value) {
  27156. this._checkUniform(name);
  27157. this._colors4[name] = value;
  27158. return this;
  27159. };
  27160. ShaderMaterial.prototype.setVector2 = function (name, value) {
  27161. this._checkUniform(name);
  27162. this._vectors2[name] = value;
  27163. return this;
  27164. };
  27165. ShaderMaterial.prototype.setVector3 = function (name, value) {
  27166. this._checkUniform(name);
  27167. this._vectors3[name] = value;
  27168. return this;
  27169. };
  27170. ShaderMaterial.prototype.setVector4 = function (name, value) {
  27171. this._checkUniform(name);
  27172. this._vectors4[name] = value;
  27173. return this;
  27174. };
  27175. ShaderMaterial.prototype.setMatrix = function (name, value) {
  27176. this._checkUniform(name);
  27177. this._matrices[name] = value;
  27178. return this;
  27179. };
  27180. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  27181. this._checkUniform(name);
  27182. this._matrices3x3[name] = value;
  27183. return this;
  27184. };
  27185. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  27186. this._checkUniform(name);
  27187. this._matrices2x2[name] = value;
  27188. return this;
  27189. };
  27190. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  27191. var scene = this.getScene();
  27192. var engine = scene.getEngine();
  27193. if (!this.checkReadyOnEveryCall) {
  27194. if (this._renderId === scene.getRenderId()) {
  27195. return true;
  27196. }
  27197. }
  27198. // Instances
  27199. var defines = [];
  27200. var fallbacks = new BABYLON.EffectFallbacks();
  27201. if (useInstances) {
  27202. defines.push("#define INSTANCES");
  27203. }
  27204. for (var index = 0; index < this._options.defines.length; index++) {
  27205. defines.push(this._options.defines[index]);
  27206. }
  27207. // Bones
  27208. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  27209. defines.push("#define BONES");
  27210. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  27211. defines.push("#define BONES4");
  27212. fallbacks.addFallback(0, "BONES4");
  27213. }
  27214. // Alpha test
  27215. if (engine.getAlphaTesting()) {
  27216. defines.push("#define ALPHATEST");
  27217. }
  27218. var previousEffect = this._effect;
  27219. var join = defines.join("\n");
  27220. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  27221. if (!this._effect.isReady()) {
  27222. return false;
  27223. }
  27224. if (previousEffect !== this._effect) {
  27225. scene.resetCachedMaterial();
  27226. }
  27227. this._renderId = scene.getRenderId();
  27228. return true;
  27229. };
  27230. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  27231. var scene = this.getScene();
  27232. if (this._options.uniforms.indexOf("world") !== -1) {
  27233. this._effect.setMatrix("world", world);
  27234. }
  27235. if (this._options.uniforms.indexOf("worldView") !== -1) {
  27236. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  27237. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  27238. }
  27239. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  27240. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  27241. }
  27242. };
  27243. ShaderMaterial.prototype.bind = function (world, mesh) {
  27244. // Std values
  27245. this.bindOnlyWorldMatrix(world);
  27246. if (this.getScene().getCachedMaterial() !== this) {
  27247. if (this._options.uniforms.indexOf("view") !== -1) {
  27248. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  27249. }
  27250. if (this._options.uniforms.indexOf("projection") !== -1) {
  27251. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  27252. }
  27253. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  27254. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  27255. }
  27256. // Bones
  27257. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  27258. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  27259. }
  27260. // Texture
  27261. for (var name in this._textures) {
  27262. this._effect.setTexture(name, this._textures[name]);
  27263. }
  27264. // Float
  27265. for (name in this._floats) {
  27266. this._effect.setFloat(name, this._floats[name]);
  27267. }
  27268. // Float s
  27269. for (name in this._floatsArrays) {
  27270. this._effect.setArray(name, this._floatsArrays[name]);
  27271. }
  27272. // Color3
  27273. for (name in this._colors3) {
  27274. this._effect.setColor3(name, this._colors3[name]);
  27275. }
  27276. // Color4
  27277. for (name in this._colors4) {
  27278. var color = this._colors4[name];
  27279. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  27280. }
  27281. // Vector2
  27282. for (name in this._vectors2) {
  27283. this._effect.setVector2(name, this._vectors2[name]);
  27284. }
  27285. // Vector3
  27286. for (name in this._vectors3) {
  27287. this._effect.setVector3(name, this._vectors3[name]);
  27288. }
  27289. // Vector4
  27290. for (name in this._vectors4) {
  27291. this._effect.setVector4(name, this._vectors4[name]);
  27292. }
  27293. // Matrix
  27294. for (name in this._matrices) {
  27295. this._effect.setMatrix(name, this._matrices[name]);
  27296. }
  27297. // Matrix 3x3
  27298. for (name in this._matrices3x3) {
  27299. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  27300. }
  27301. // Matrix 2x2
  27302. for (name in this._matrices2x2) {
  27303. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  27304. }
  27305. }
  27306. _super.prototype.bind.call(this, world, mesh);
  27307. };
  27308. ShaderMaterial.prototype.clone = function (name) {
  27309. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  27310. return newShaderMaterial;
  27311. };
  27312. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  27313. for (var name in this._textures) {
  27314. this._textures[name].dispose();
  27315. }
  27316. this._textures = [];
  27317. _super.prototype.dispose.call(this, forceDisposeEffect);
  27318. };
  27319. return ShaderMaterial;
  27320. })(BABYLON.Material);
  27321. BABYLON.ShaderMaterial = ShaderMaterial;
  27322. })(BABYLON || (BABYLON = {}));
  27323. var BABYLON;
  27324. (function (BABYLON) {
  27325. var Internals;
  27326. (function (Internals) {
  27327. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  27328. // All values and structures referenced from:
  27329. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  27330. var DDS_MAGIC = 0x20534444;
  27331. 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;
  27332. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  27333. 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;
  27334. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  27335. function FourCCToInt32(value) {
  27336. return value.charCodeAt(0) +
  27337. (value.charCodeAt(1) << 8) +
  27338. (value.charCodeAt(2) << 16) +
  27339. (value.charCodeAt(3) << 24);
  27340. }
  27341. function Int32ToFourCC(value) {
  27342. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  27343. }
  27344. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  27345. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  27346. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  27347. var headerLengthInt = 31; // The header length in 32 bit ints
  27348. // Offsets into the header array
  27349. var off_magic = 0;
  27350. var off_size = 1;
  27351. var off_flags = 2;
  27352. var off_height = 3;
  27353. var off_width = 4;
  27354. var off_mipmapCount = 7;
  27355. var off_pfFlags = 20;
  27356. var off_pfFourCC = 21;
  27357. var off_RGBbpp = 22;
  27358. var off_RMask = 23;
  27359. var off_GMask = 24;
  27360. var off_BMask = 25;
  27361. var off_AMask = 26;
  27362. var off_caps1 = 27;
  27363. var off_caps2 = 28;
  27364. ;
  27365. var DDSTools = (function () {
  27366. function DDSTools() {
  27367. }
  27368. DDSTools.GetDDSInfo = function (arrayBuffer) {
  27369. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  27370. var mipmapCount = 1;
  27371. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  27372. mipmapCount = Math.max(1, header[off_mipmapCount]);
  27373. }
  27374. return {
  27375. width: header[off_width],
  27376. height: header[off_height],
  27377. mipmapCount: mipmapCount,
  27378. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  27379. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  27380. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  27381. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  27382. };
  27383. };
  27384. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  27385. var byteArray = new Uint8Array(dataLength);
  27386. var srcData = new Uint8Array(arrayBuffer);
  27387. var index = 0;
  27388. for (var y = height - 1; y >= 0; y--) {
  27389. for (var x = 0; x < width; x++) {
  27390. var srcPos = dataOffset + (x + y * width) * 4;
  27391. byteArray[index + 2] = srcData[srcPos];
  27392. byteArray[index + 1] = srcData[srcPos + 1];
  27393. byteArray[index] = srcData[srcPos + 2];
  27394. byteArray[index + 3] = srcData[srcPos + 3];
  27395. index += 4;
  27396. }
  27397. }
  27398. return byteArray;
  27399. };
  27400. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  27401. var byteArray = new Uint8Array(dataLength);
  27402. var srcData = new Uint8Array(arrayBuffer);
  27403. var index = 0;
  27404. for (var y = height - 1; y >= 0; y--) {
  27405. for (var x = 0; x < width; x++) {
  27406. var srcPos = dataOffset + (x + y * width) * 3;
  27407. byteArray[index + 2] = srcData[srcPos];
  27408. byteArray[index + 1] = srcData[srcPos + 1];
  27409. byteArray[index] = srcData[srcPos + 2];
  27410. index += 3;
  27411. }
  27412. }
  27413. return byteArray;
  27414. };
  27415. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  27416. var byteArray = new Uint8Array(dataLength);
  27417. var srcData = new Uint8Array(arrayBuffer);
  27418. var index = 0;
  27419. for (var y = height - 1; y >= 0; y--) {
  27420. for (var x = 0; x < width; x++) {
  27421. var srcPos = dataOffset + (x + y * width);
  27422. byteArray[index] = srcData[srcPos];
  27423. index++;
  27424. }
  27425. }
  27426. return byteArray;
  27427. };
  27428. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  27429. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  27430. if (header[off_magic] != DDS_MAGIC) {
  27431. BABYLON.Tools.Error("Invalid magic number in DDS header");
  27432. return;
  27433. }
  27434. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  27435. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  27436. return;
  27437. }
  27438. if (info.isFourCC) {
  27439. fourCC = header[off_pfFourCC];
  27440. switch (fourCC) {
  27441. case FOURCC_DXT1:
  27442. blockBytes = 8;
  27443. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  27444. break;
  27445. case FOURCC_DXT3:
  27446. blockBytes = 16;
  27447. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  27448. break;
  27449. case FOURCC_DXT5:
  27450. blockBytes = 16;
  27451. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  27452. break;
  27453. default:
  27454. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  27455. return;
  27456. }
  27457. }
  27458. mipmapCount = 1;
  27459. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  27460. mipmapCount = Math.max(1, header[off_mipmapCount]);
  27461. }
  27462. var bpp = header[off_RGBbpp];
  27463. for (var face = 0; face < faces; face++) {
  27464. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  27465. width = header[off_width];
  27466. height = header[off_height];
  27467. dataOffset = header[off_size] + 4;
  27468. for (i = 0; i < mipmapCount; ++i) {
  27469. if (info.isRGB) {
  27470. if (bpp === 24) {
  27471. dataLength = width * height * 3;
  27472. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  27473. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  27474. }
  27475. else {
  27476. dataLength = width * height * 4;
  27477. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  27478. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  27479. }
  27480. }
  27481. else if (info.isLuminance) {
  27482. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  27483. var unpaddedRowSize = width;
  27484. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  27485. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  27486. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  27487. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  27488. }
  27489. else {
  27490. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  27491. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  27492. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  27493. }
  27494. dataOffset += dataLength;
  27495. width *= 0.5;
  27496. height *= 0.5;
  27497. width = Math.max(1.0, width);
  27498. height = Math.max(1.0, height);
  27499. }
  27500. }
  27501. };
  27502. return DDSTools;
  27503. })();
  27504. Internals.DDSTools = DDSTools;
  27505. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  27506. })(BABYLON || (BABYLON = {}));
  27507. var BABYLON;
  27508. (function (BABYLON) {
  27509. var CannonJSPlugin = (function () {
  27510. function CannonJSPlugin() {
  27511. this._registeredMeshes = [];
  27512. this._physicsMaterials = [];
  27513. this.updateBodyPosition = function (mesh) {
  27514. for (var index = 0; index < this._registeredMeshes.length; index++) {
  27515. var registeredMesh = this._registeredMeshes[index];
  27516. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  27517. var body = registeredMesh.body;
  27518. var center = mesh.getBoundingInfo().boundingBox.center;
  27519. body.position.set(center.x, center.y, center.z);
  27520. body.quaternion.copy(mesh.rotationQuaternion);
  27521. if (registeredMesh.deltaRotation) {
  27522. var tmpQ = new CANNON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  27523. body.quaternion = body.quaternion.mult(tmpQ);
  27524. }
  27525. //TODO - If the body is heightmap-based, this won't work correctly. find a good fix.
  27526. return;
  27527. }
  27528. }
  27529. };
  27530. }
  27531. CannonJSPlugin.prototype.initialize = function (iterations) {
  27532. if (iterations === void 0) { iterations = 10; }
  27533. this._world = new CANNON.World();
  27534. this._world.broadphase = new CANNON.NaiveBroadphase();
  27535. this._world.solver.iterations = iterations;
  27536. };
  27537. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  27538. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  27539. };
  27540. CannonJSPlugin.prototype.runOneStep = function (delta) {
  27541. this._world.step(delta);
  27542. for (var index = 0; index < this._registeredMeshes.length; index++) {
  27543. var registeredMesh = this._registeredMeshes[index];
  27544. if (registeredMesh.isChild) {
  27545. continue;
  27546. }
  27547. // Body position
  27548. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  27549. registeredMesh.mesh.position.x = bodyX + registeredMesh.delta.x;
  27550. registeredMesh.mesh.position.y = bodyY + registeredMesh.delta.y;
  27551. registeredMesh.mesh.position.z = bodyZ + registeredMesh.delta.z;
  27552. registeredMesh.mesh.rotationQuaternion.copyFrom(registeredMesh.body.quaternion);
  27553. if (registeredMesh.deltaRotation) {
  27554. registeredMesh.mesh.rotationQuaternion.multiplyInPlace(registeredMesh.deltaRotation);
  27555. }
  27556. }
  27557. };
  27558. CannonJSPlugin.prototype.setGravity = function (gravity) {
  27559. this._world.gravity.set(gravity.x, gravity.y, gravity.z);
  27560. };
  27561. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  27562. this.unregisterMesh(mesh);
  27563. if (!mesh.rotationQuaternion) {
  27564. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  27565. }
  27566. mesh.computeWorldMatrix(true);
  27567. var shape = this._createShape(mesh, impostor);
  27568. return this._createRigidBodyFromShape(shape, mesh, options);
  27569. };
  27570. CannonJSPlugin.prototype._createShape = function (mesh, impostor) {
  27571. //get the correct bounding box
  27572. var oldQuaternion = mesh.rotationQuaternion;
  27573. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  27574. mesh.computeWorldMatrix(true);
  27575. var returnValue;
  27576. switch (impostor) {
  27577. case BABYLON.PhysicsEngine.SphereImpostor:
  27578. var bbox = mesh.getBoundingInfo().boundingBox;
  27579. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  27580. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  27581. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  27582. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  27583. break;
  27584. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  27585. case BABYLON.PhysicsEngine.CylinderImpostor:
  27586. BABYLON.Tools.Warn("CylinderImposter not yet implemented, using BoxImposter instead");
  27587. case BABYLON.PhysicsEngine.BoxImpostor:
  27588. bbox = mesh.getBoundingInfo().boundingBox;
  27589. var min = bbox.minimumWorld;
  27590. var max = bbox.maximumWorld;
  27591. var box = max.subtract(min).scale(0.5);
  27592. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  27593. break;
  27594. case BABYLON.PhysicsEngine.PlaneImpostor:
  27595. BABYLON.Tools.Warn("Attention, Cannon.js PlaneImposter might not behave as you wish. Consider using BoxImposter instead");
  27596. returnValue = new CANNON.Plane();
  27597. break;
  27598. case BABYLON.PhysicsEngine.MeshImpostor:
  27599. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27600. var rawFaces = mesh.getIndices();
  27601. returnValue = this._createConvexPolyhedron(rawVerts, rawFaces, mesh);
  27602. break;
  27603. case BABYLON.PhysicsEngine.HeightmapImpostor:
  27604. returnValue = this._createHeightmap(mesh);
  27605. break;
  27606. }
  27607. mesh.rotationQuaternion = oldQuaternion;
  27608. return returnValue;
  27609. };
  27610. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh) {
  27611. var verts = [], faces = [];
  27612. mesh.computeWorldMatrix(true);
  27613. // Get vertices
  27614. for (var i = 0; i < rawVerts.length; i += 3) {
  27615. var transformed = BABYLON.Vector3.Zero();
  27616. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  27617. verts.push(new CANNON.Vec3(transformed.x, transformed.y, transformed.z));
  27618. }
  27619. // Get faces
  27620. for (var j = 0; j < rawFaces.length; j += 3) {
  27621. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  27622. }
  27623. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  27624. return shape;
  27625. };
  27626. CannonJSPlugin.prototype._createHeightmap = function (mesh) {
  27627. var pos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27628. if (pos[0] !== pos[pos.length - 1]) {
  27629. console.log("ERROR");
  27630. return;
  27631. }
  27632. var matrix = [];
  27633. //dimension
  27634. var dim = -pos[0];
  27635. //array size
  27636. var arraySize = -1;
  27637. for (var i = 0; i < pos.length; i = i + 3) {
  27638. if (pos[i + 2] === pos[2]) {
  27639. arraySize++;
  27640. }
  27641. else {
  27642. break;
  27643. }
  27644. }
  27645. //calculate element size
  27646. var elementSize = dim * 2 / arraySize;
  27647. //calculate the matrix for cannon's heightfield
  27648. for (var i = 0; i < pos.length; i = i + 3) {
  27649. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  27650. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  27651. if (!matrix[x]) {
  27652. matrix[x] = [];
  27653. }
  27654. matrix[x][z] = pos[i + 1];
  27655. }
  27656. var shape = new CANNON.Heightfield(matrix, {
  27657. elementSize: elementSize
  27658. });
  27659. //For future reference, needed for body transformation
  27660. shape.dim = dim;
  27661. return shape;
  27662. };
  27663. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  27664. var index;
  27665. var mat;
  27666. for (index = 0; index < this._physicsMaterials.length; index++) {
  27667. mat = this._physicsMaterials[index];
  27668. if (mat.friction === friction && mat.restitution === restitution) {
  27669. return mat;
  27670. }
  27671. }
  27672. var currentMat = new CANNON.Material("mat");
  27673. this._physicsMaterials.push(currentMat);
  27674. for (index = 0; index < this._physicsMaterials.length; index++) {
  27675. mat = this._physicsMaterials[index];
  27676. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, { friction: friction, restitution: restitution });
  27677. this._world.addContactMaterial(contactMaterial);
  27678. }
  27679. return currentMat;
  27680. };
  27681. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, options) {
  27682. if (!mesh.rotationQuaternion) {
  27683. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  27684. }
  27685. // The delta between the mesh position and the mesh bounding box center
  27686. var bbox = mesh.getBoundingInfo().boundingBox;
  27687. var deltaPosition = mesh.position.subtract(bbox.center);
  27688. var deltaRotation;
  27689. var material = this._addMaterial(options.friction, options.restitution);
  27690. var body = new CANNON.Body({
  27691. mass: options.mass,
  27692. material: material,
  27693. position: new CANNON.Vec3(bbox.center.x, bbox.center.y, bbox.center.z)
  27694. });
  27695. body.quaternion = new CANNON.Quaternion(mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z, mesh.rotationQuaternion.w);
  27696. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  27697. if (shape.type === CANNON.Shape.types.PLANE || shape.type === CANNON.Shape.types.HEIGHTFIELD) {
  27698. //-90 DEG in X, precalculated
  27699. var tmpQ = new CANNON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  27700. body.quaternion = body.quaternion.mult(tmpQ);
  27701. //Invert!
  27702. deltaRotation = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  27703. }
  27704. //If it is a heightfield, if should be centered.
  27705. if (shape.type === CANNON.Shape.types.HEIGHTFIELD) {
  27706. body.position = new CANNON.Vec3(-shape.dim, 0, shape.dim).vadd(mesh.position);
  27707. //add it inverted to the delta
  27708. deltaPosition = mesh.position.add(new BABYLON.Vector3(shape.dim, 0, -shape.dim));
  27709. }
  27710. //add the shape
  27711. body.addShape(shape);
  27712. this._world.add(body);
  27713. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition, deltaRotation: deltaRotation });
  27714. return body;
  27715. };
  27716. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  27717. var initialMesh = parts[0].mesh;
  27718. this.unregisterMesh(initialMesh);
  27719. initialMesh.computeWorldMatrix(true);
  27720. var initialShape = this._createShape(initialMesh, parts[0].impostor);
  27721. var body = this._createRigidBodyFromShape(initialShape, initialMesh, options);
  27722. for (var index = 1; index < parts.length; index++) {
  27723. var mesh = parts[index].mesh;
  27724. mesh.computeWorldMatrix(true);
  27725. var shape = this._createShape(mesh, parts[index].impostor);
  27726. var localPosition = mesh.position;
  27727. body.addShape(shape, new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  27728. }
  27729. return body;
  27730. };
  27731. CannonJSPlugin.prototype._unbindBody = function (body) {
  27732. for (var index = 0; index < this._registeredMeshes.length; index++) {
  27733. var registeredMesh = this._registeredMeshes[index];
  27734. if (registeredMesh.body === body) {
  27735. this._world.remove(registeredMesh.body);
  27736. registeredMesh.body = null;
  27737. registeredMesh.delta = null;
  27738. registeredMesh.deltaRotation = null;
  27739. }
  27740. }
  27741. };
  27742. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  27743. for (var index = 0; index < this._registeredMeshes.length; index++) {
  27744. var registeredMesh = this._registeredMeshes[index];
  27745. if (registeredMesh.mesh === mesh) {
  27746. // Remove body
  27747. if (registeredMesh.body) {
  27748. this._unbindBody(registeredMesh.body);
  27749. }
  27750. this._registeredMeshes.splice(index, 1);
  27751. return;
  27752. }
  27753. }
  27754. };
  27755. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  27756. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  27757. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  27758. for (var index = 0; index < this._registeredMeshes.length; index++) {
  27759. var registeredMesh = this._registeredMeshes[index];
  27760. if (registeredMesh.mesh === mesh) {
  27761. registeredMesh.body.applyImpulse(impulse, worldPoint);
  27762. return;
  27763. }
  27764. }
  27765. };
  27766. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  27767. var body1 = null, body2 = null;
  27768. for (var index = 0; index < this._registeredMeshes.length; index++) {
  27769. var registeredMesh = this._registeredMeshes[index];
  27770. if (registeredMesh.mesh === mesh1) {
  27771. body1 = registeredMesh.body;
  27772. }
  27773. else if (registeredMesh.mesh === mesh2) {
  27774. body2 = registeredMesh.body;
  27775. }
  27776. }
  27777. if (!body1 || !body2) {
  27778. return false;
  27779. }
  27780. 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));
  27781. this._world.addConstraint(constraint);
  27782. return true;
  27783. };
  27784. CannonJSPlugin.prototype.dispose = function () {
  27785. while (this._registeredMeshes.length) {
  27786. this.unregisterMesh(this._registeredMeshes[0].mesh);
  27787. }
  27788. };
  27789. CannonJSPlugin.prototype.isSupported = function () {
  27790. return window.CANNON !== undefined;
  27791. };
  27792. CannonJSPlugin.prototype.getWorldObject = function () {
  27793. return this._world;
  27794. };
  27795. CannonJSPlugin.prototype.getPhysicsBodyOfMesh = function (mesh) {
  27796. for (var index = 0; index < this._registeredMeshes.length; index++) {
  27797. var registeredMesh = this._registeredMeshes[index];
  27798. if (registeredMesh.mesh === mesh) {
  27799. return registeredMesh.body;
  27800. }
  27801. }
  27802. return null;
  27803. };
  27804. return CannonJSPlugin;
  27805. })();
  27806. BABYLON.CannonJSPlugin = CannonJSPlugin;
  27807. })(BABYLON || (BABYLON = {}));
  27808. var BABYLON;
  27809. (function (BABYLON) {
  27810. var OimoJSPlugin = (function () {
  27811. function OimoJSPlugin() {
  27812. this._registeredMeshes = [];
  27813. /**
  27814. * Update the body position according to the mesh position
  27815. * @param mesh
  27816. */
  27817. this.updateBodyPosition = function (mesh) {
  27818. for (var index = 0; index < this._registeredMeshes.length; index++) {
  27819. var registeredMesh = this._registeredMeshes[index];
  27820. var body = registeredMesh.body.body;
  27821. var updated = false;
  27822. var newPosition;
  27823. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  27824. mesh.computeWorldMatrix(true);
  27825. newPosition = mesh.getBoundingInfo().boundingBox.center;
  27826. updated = true;
  27827. }
  27828. else if (registeredMesh.mesh.parent === mesh) {
  27829. mesh.computeWorldMatrix(true);
  27830. registeredMesh.mesh.computeWorldMatrix(true);
  27831. newPosition = registeredMesh.mesh.getAbsolutePosition();
  27832. updated = true;
  27833. }
  27834. if (updated) {
  27835. body.setPosition(new OIMO.Vec3(newPosition.x, newPosition.y, newPosition.z));
  27836. body.setQuaternion(mesh.rotationQuaternion);
  27837. body.sleeping = false;
  27838. //force Oimo to update the body's position
  27839. body.updatePosition(1);
  27840. }
  27841. }
  27842. };
  27843. }
  27844. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  27845. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  27846. };
  27847. OimoJSPlugin.prototype.initialize = function (iterations) {
  27848. this._world = new OIMO.World(null, null, iterations);
  27849. this._world.clear();
  27850. };
  27851. OimoJSPlugin.prototype.setGravity = function (gravity) {
  27852. this._world.gravity = gravity;
  27853. };
  27854. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  27855. this.unregisterMesh(mesh);
  27856. if (!mesh.rotationQuaternion) {
  27857. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  27858. }
  27859. mesh.computeWorldMatrix(true);
  27860. var bbox = mesh.getBoundingInfo().boundingBox;
  27861. // The delta between the mesh position and the mesh bounding box center
  27862. var deltaPosition = mesh.position.subtract(bbox.center);
  27863. //calculate rotation to fit Oimo's needs (Euler...)
  27864. var rot = new OIMO.Euler().setFromQuaternion({ x: mesh.rotationQuaternion.x, y: mesh.rotationQuaternion.y, z: mesh.rotationQuaternion.z, s: mesh.rotationQuaternion.w });
  27865. //get the correct bounding box
  27866. var oldQuaternion = mesh.rotationQuaternion;
  27867. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  27868. mesh.computeWorldMatrix(true);
  27869. var bodyConfig = {
  27870. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  27871. rot: [rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD],
  27872. move: options.mass != 0,
  27873. config: [options.mass, options.friction, options.restitution],
  27874. world: this._world
  27875. };
  27876. // register mesh
  27877. switch (impostor) {
  27878. case BABYLON.PhysicsEngine.SphereImpostor:
  27879. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  27880. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  27881. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  27882. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  27883. bodyConfig.type = 'sphere';
  27884. bodyConfig.size = [size];
  27885. break;
  27886. case BABYLON.PhysicsEngine.PlaneImpostor:
  27887. //Oimo "fakes" a cylinder as a box, so why don't we!
  27888. case BABYLON.PhysicsEngine.CylinderImpostor:
  27889. case BABYLON.PhysicsEngine.BoxImpostor:
  27890. var min = bbox.minimumWorld;
  27891. var max = bbox.maximumWorld;
  27892. var box = max.subtract(min);
  27893. var sizeX = this._checkWithEpsilon(box.x);
  27894. var sizeY = this._checkWithEpsilon(box.y);
  27895. var sizeZ = this._checkWithEpsilon(box.z);
  27896. bodyConfig.type = 'box';
  27897. bodyConfig.size = [sizeX, sizeY, sizeZ];
  27898. break;
  27899. }
  27900. var body = new OIMO.Body(bodyConfig);
  27901. //We have to access the rigid body's properties to set the quaternion.
  27902. //The setQuaternion function of Oimo only sets the newOrientation that is only set after an impulse is given or a collision.
  27903. //body.body.orientation = new OIMO.Quat(mesh.rotationQuaternion.w, mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z);
  27904. //TEST
  27905. //body.body.resetQuaternion(new OIMO.Quat(mesh.rotationQuaternion.w, mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z));
  27906. //update the internal rotation matrix
  27907. //body.body.syncShapes();
  27908. this._registeredMeshes.push({
  27909. mesh: mesh,
  27910. body: body,
  27911. delta: deltaPosition
  27912. });
  27913. //for the sake of consistency.
  27914. mesh.rotationQuaternion = oldQuaternion;
  27915. return body;
  27916. };
  27917. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  27918. var types = [], sizes = [], positions = [], rotations = [];
  27919. var initialMesh = parts[0].mesh;
  27920. for (var index = 0; index < parts.length; index++) {
  27921. var part = parts[index];
  27922. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  27923. types.push(bodyParameters.type);
  27924. sizes.push.apply(sizes, bodyParameters.size);
  27925. positions.push.apply(positions, bodyParameters.pos);
  27926. rotations.push.apply(rotations, bodyParameters.rot);
  27927. }
  27928. var body = new OIMO.Body({
  27929. type: types,
  27930. size: sizes,
  27931. pos: positions,
  27932. rot: rotations,
  27933. move: options.mass != 0,
  27934. config: [options.mass, options.friction, options.restitution],
  27935. world: this._world
  27936. });
  27937. //Reset the body's rotation to be of the initial mesh's.
  27938. var rot = new OIMO.Euler().setFromQuaternion({ x: initialMesh.rotationQuaternion.x, y: initialMesh.rotationQuaternion.y, z: initialMesh.rotationQuaternion.z, s: initialMesh.rotationQuaternion.w });
  27939. body.resetRotation(rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD);
  27940. this._registeredMeshes.push({
  27941. mesh: initialMesh,
  27942. body: body
  27943. });
  27944. return body;
  27945. };
  27946. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  27947. var mesh = part.mesh;
  27948. if (!mesh.rotationQuaternion) {
  27949. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  27950. }
  27951. // We need the bounding box/sphere info to compute the physics body
  27952. mesh.computeWorldMatrix(true);
  27953. var rot = new OIMO.Euler().setFromQuaternion({ x: mesh.rotationQuaternion.x, y: mesh.rotationQuaternion.y, z: mesh.rotationQuaternion.z, s: mesh.rotationQuaternion.w });
  27954. var bodyParameters = {
  27955. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  27956. //A bug in Oimo (Body class) prevents us from using rot directly.
  27957. rot: [0, 0, 0],
  27958. //For future reference, if the bug will ever be fixed.
  27959. realRot: [rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD]
  27960. };
  27961. var oldQuaternion = mesh.rotationQuaternion;
  27962. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  27963. mesh.computeWorldMatrix(true);
  27964. switch (part.impostor) {
  27965. case BABYLON.PhysicsEngine.SphereImpostor:
  27966. var bbox = mesh.getBoundingInfo().boundingBox;
  27967. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  27968. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  27969. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  27970. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  27971. bodyParameters.type = 'sphere';
  27972. bodyParameters.size = [size, size, size];
  27973. break;
  27974. case BABYLON.PhysicsEngine.PlaneImpostor:
  27975. case BABYLON.PhysicsEngine.CylinderImpostor:
  27976. case BABYLON.PhysicsEngine.BoxImpostor:
  27977. bbox = mesh.getBoundingInfo().boundingBox;
  27978. var min = bbox.minimumWorld;
  27979. var max = bbox.maximumWorld;
  27980. var box = max.subtract(min);
  27981. var sizeX = this._checkWithEpsilon(box.x);
  27982. var sizeY = this._checkWithEpsilon(box.y);
  27983. var sizeZ = this._checkWithEpsilon(box.z);
  27984. bodyParameters.type = 'box';
  27985. bodyParameters.size = [sizeX, sizeY, sizeZ];
  27986. break;
  27987. }
  27988. mesh.rotationQuaternion = oldQuaternion;
  27989. return bodyParameters;
  27990. };
  27991. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  27992. for (var index = 0; index < this._registeredMeshes.length; index++) {
  27993. var registeredMesh = this._registeredMeshes[index];
  27994. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  27995. if (registeredMesh.body) {
  27996. this._world.removeRigidBody(registeredMesh.body.body);
  27997. this._unbindBody(registeredMesh.body);
  27998. }
  27999. this._registeredMeshes.splice(index, 1);
  28000. return;
  28001. }
  28002. }
  28003. };
  28004. OimoJSPlugin.prototype._unbindBody = function (body) {
  28005. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28006. var registeredMesh = this._registeredMeshes[index];
  28007. if (registeredMesh.body === body) {
  28008. registeredMesh.body = null;
  28009. }
  28010. }
  28011. };
  28012. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  28013. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28014. var registeredMesh = this._registeredMeshes[index];
  28015. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  28016. // Get object mass to have a behaviour similar to cannon.js
  28017. var mass = registeredMesh.body.body.massInfo.mass;
  28018. // The force is scaled with the mass of object
  28019. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  28020. return;
  28021. }
  28022. }
  28023. };
  28024. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  28025. var body1 = null, body2 = null;
  28026. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28027. var registeredMesh = this._registeredMeshes[index];
  28028. if (registeredMesh.mesh === mesh1) {
  28029. body1 = registeredMesh.body.body;
  28030. }
  28031. else if (registeredMesh.mesh === mesh2) {
  28032. body2 = registeredMesh.body.body;
  28033. }
  28034. }
  28035. if (!body1 || !body2) {
  28036. return false;
  28037. }
  28038. if (!options) {
  28039. options = {};
  28040. }
  28041. new OIMO.Link({
  28042. type: options.type,
  28043. body1: body1,
  28044. body2: body2,
  28045. min: options.min,
  28046. max: options.max,
  28047. axe1: options.axe1,
  28048. axe2: options.axe2,
  28049. pos1: [pivot1.x, pivot1.y, pivot1.z],
  28050. pos2: [pivot2.x, pivot2.y, pivot2.z],
  28051. collision: options.collision,
  28052. spring: options.spring,
  28053. world: this._world
  28054. });
  28055. return true;
  28056. };
  28057. OimoJSPlugin.prototype.dispose = function () {
  28058. this._world.clear();
  28059. while (this._registeredMeshes.length) {
  28060. this.unregisterMesh(this._registeredMeshes[0].mesh);
  28061. }
  28062. };
  28063. OimoJSPlugin.prototype.isSupported = function () {
  28064. return OIMO !== undefined;
  28065. };
  28066. OimoJSPlugin.prototype.getWorldObject = function () {
  28067. return this._world;
  28068. };
  28069. OimoJSPlugin.prototype.getPhysicsBodyOfMesh = function (mesh) {
  28070. for (var index = 0; index < this._registeredMeshes.length; index++) {
  28071. var registeredMesh = this._registeredMeshes[index];
  28072. if (registeredMesh.mesh === mesh) {
  28073. return registeredMesh.body;
  28074. }
  28075. }
  28076. return null;
  28077. };
  28078. OimoJSPlugin.prototype._getLastShape = function (body) {
  28079. var lastShape = body.shapes;
  28080. while (lastShape.next) {
  28081. lastShape = lastShape.next;
  28082. }
  28083. return lastShape;
  28084. };
  28085. OimoJSPlugin.prototype.runOneStep = function (time) {
  28086. this._world.step();
  28087. // Update the position of all registered meshes
  28088. var i = this._registeredMeshes.length;
  28089. var m;
  28090. while (i--) {
  28091. var body = this._registeredMeshes[i].body.body;
  28092. var mesh = this._registeredMeshes[i].mesh;
  28093. if (!this._registeredMeshes[i].delta) {
  28094. this._registeredMeshes[i].delta = BABYLON.Vector3.Zero();
  28095. }
  28096. if (!body.sleeping) {
  28097. //TODO check that
  28098. if (body.shapes.next) {
  28099. var parentShape = this._getLastShape(body);
  28100. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  28101. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  28102. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  28103. }
  28104. else {
  28105. mesh.position.copyFrom(body.getPosition()).addInPlace(this._registeredMeshes[i].delta);
  28106. }
  28107. mesh.rotationQuaternion.copyFrom(body.getQuaternion());
  28108. mesh.computeWorldMatrix();
  28109. }
  28110. }
  28111. };
  28112. return OimoJSPlugin;
  28113. })();
  28114. BABYLON.OimoJSPlugin = OimoJSPlugin;
  28115. })(BABYLON || (BABYLON = {}));
  28116. var BABYLON;
  28117. (function (BABYLON) {
  28118. var DisplayPassPostProcess = (function (_super) {
  28119. __extends(DisplayPassPostProcess, _super);
  28120. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  28121. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  28122. }
  28123. return DisplayPassPostProcess;
  28124. })(BABYLON.PostProcess);
  28125. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  28126. })(BABYLON || (BABYLON = {}));
  28127. var BABYLON;
  28128. (function (BABYLON) {
  28129. var SimplificationSettings = (function () {
  28130. function SimplificationSettings(quality, distance, optimizeMesh) {
  28131. this.quality = quality;
  28132. this.distance = distance;
  28133. this.optimizeMesh = optimizeMesh;
  28134. }
  28135. return SimplificationSettings;
  28136. })();
  28137. BABYLON.SimplificationSettings = SimplificationSettings;
  28138. var SimplificationQueue = (function () {
  28139. function SimplificationQueue() {
  28140. this.running = false;
  28141. this._simplificationArray = [];
  28142. }
  28143. SimplificationQueue.prototype.addTask = function (task) {
  28144. this._simplificationArray.push(task);
  28145. };
  28146. SimplificationQueue.prototype.executeNext = function () {
  28147. var task = this._simplificationArray.pop();
  28148. if (task) {
  28149. this.running = true;
  28150. this.runSimplification(task);
  28151. }
  28152. else {
  28153. this.running = false;
  28154. }
  28155. };
  28156. SimplificationQueue.prototype.runSimplification = function (task) {
  28157. var _this = this;
  28158. if (task.parallelProcessing) {
  28159. //parallel simplifier
  28160. task.settings.forEach(function (setting) {
  28161. var simplifier = _this.getSimplifier(task);
  28162. simplifier.simplify(setting, function (newMesh) {
  28163. task.mesh.addLODLevel(setting.distance, newMesh);
  28164. newMesh.isVisible = true;
  28165. //check if it is the last
  28166. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  28167. //all done, run the success callback.
  28168. task.successCallback();
  28169. }
  28170. _this.executeNext();
  28171. });
  28172. });
  28173. }
  28174. else {
  28175. //single simplifier.
  28176. var simplifier = this.getSimplifier(task);
  28177. var runDecimation = function (setting, callback) {
  28178. simplifier.simplify(setting, function (newMesh) {
  28179. task.mesh.addLODLevel(setting.distance, newMesh);
  28180. newMesh.isVisible = true;
  28181. //run the next quality level
  28182. callback();
  28183. });
  28184. };
  28185. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  28186. runDecimation(task.settings[loop.index], function () {
  28187. loop.executeNext();
  28188. });
  28189. }, function () {
  28190. //execution ended, run the success callback.
  28191. if (task.successCallback) {
  28192. task.successCallback();
  28193. }
  28194. _this.executeNext();
  28195. });
  28196. }
  28197. };
  28198. SimplificationQueue.prototype.getSimplifier = function (task) {
  28199. switch (task.simplificationType) {
  28200. case SimplificationType.QUADRATIC:
  28201. default:
  28202. return new QuadraticErrorSimplification(task.mesh);
  28203. }
  28204. };
  28205. return SimplificationQueue;
  28206. })();
  28207. BABYLON.SimplificationQueue = SimplificationQueue;
  28208. /**
  28209. * The implemented types of simplification.
  28210. * At the moment only Quadratic Error Decimation is implemented.
  28211. */
  28212. (function (SimplificationType) {
  28213. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  28214. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  28215. var SimplificationType = BABYLON.SimplificationType;
  28216. var DecimationTriangle = (function () {
  28217. function DecimationTriangle(vertices) {
  28218. this.vertices = vertices;
  28219. this.error = new Array(4);
  28220. this.deleted = false;
  28221. this.isDirty = false;
  28222. this.deletePending = false;
  28223. this.borderFactor = 0;
  28224. }
  28225. return DecimationTriangle;
  28226. })();
  28227. BABYLON.DecimationTriangle = DecimationTriangle;
  28228. var DecimationVertex = (function () {
  28229. function DecimationVertex(position, id) {
  28230. this.position = position;
  28231. this.id = id;
  28232. this.isBorder = true;
  28233. this.q = new QuadraticMatrix();
  28234. this.triangleCount = 0;
  28235. this.triangleStart = 0;
  28236. this.originalOffsets = [];
  28237. }
  28238. DecimationVertex.prototype.updatePosition = function (newPosition) {
  28239. this.position.copyFrom(newPosition);
  28240. };
  28241. return DecimationVertex;
  28242. })();
  28243. BABYLON.DecimationVertex = DecimationVertex;
  28244. var QuadraticMatrix = (function () {
  28245. function QuadraticMatrix(data) {
  28246. this.data = new Array(10);
  28247. for (var i = 0; i < 10; ++i) {
  28248. if (data && data[i]) {
  28249. this.data[i] = data[i];
  28250. }
  28251. else {
  28252. this.data[i] = 0;
  28253. }
  28254. }
  28255. }
  28256. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  28257. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  28258. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  28259. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  28260. return det;
  28261. };
  28262. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  28263. for (var i = 0; i < 10; ++i) {
  28264. this.data[i] += matrix.data[i];
  28265. }
  28266. };
  28267. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  28268. for (var i = 0; i < 10; ++i) {
  28269. this.data[i] += data[i];
  28270. }
  28271. };
  28272. QuadraticMatrix.prototype.add = function (matrix) {
  28273. var m = new QuadraticMatrix();
  28274. for (var i = 0; i < 10; ++i) {
  28275. m.data[i] = this.data[i] + matrix.data[i];
  28276. }
  28277. return m;
  28278. };
  28279. QuadraticMatrix.FromData = function (a, b, c, d) {
  28280. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  28281. };
  28282. //returning an array to avoid garbage collection
  28283. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  28284. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  28285. };
  28286. return QuadraticMatrix;
  28287. })();
  28288. BABYLON.QuadraticMatrix = QuadraticMatrix;
  28289. var Reference = (function () {
  28290. function Reference(vertexId, triangleId) {
  28291. this.vertexId = vertexId;
  28292. this.triangleId = triangleId;
  28293. }
  28294. return Reference;
  28295. })();
  28296. BABYLON.Reference = Reference;
  28297. /**
  28298. * An implementation of the Quadratic Error simplification algorithm.
  28299. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  28300. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  28301. * @author RaananW
  28302. */
  28303. var QuadraticErrorSimplification = (function () {
  28304. function QuadraticErrorSimplification(_mesh) {
  28305. this._mesh = _mesh;
  28306. this.initialized = false;
  28307. this.syncIterations = 5000;
  28308. this.aggressiveness = 7;
  28309. this.decimationIterations = 100;
  28310. this.boundingBoxEpsilon = BABYLON.Engine.Epsilon;
  28311. }
  28312. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  28313. var _this = this;
  28314. this.initDecimatedMesh();
  28315. //iterating through the submeshes array, one after the other.
  28316. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  28317. _this.initWithMesh(loop.index, function () {
  28318. _this.runDecimation(settings, loop.index, function () {
  28319. loop.executeNext();
  28320. });
  28321. }, settings.optimizeMesh);
  28322. }, function () {
  28323. setTimeout(function () {
  28324. successCallback(_this._reconstructedMesh);
  28325. }, 0);
  28326. });
  28327. };
  28328. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  28329. var _this = this;
  28330. var gCount = 0;
  28331. triangle.vertices.forEach(function (vertex) {
  28332. var count = 0;
  28333. var vPos = vertex.position;
  28334. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  28335. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  28336. ++count;
  28337. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  28338. ++count;
  28339. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  28340. ++count;
  28341. if (count > 1) {
  28342. ++gCount;
  28343. }
  28344. ;
  28345. });
  28346. if (gCount > 1) {
  28347. console.log(triangle, gCount);
  28348. }
  28349. return gCount > 1;
  28350. };
  28351. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  28352. var _this = this;
  28353. var targetCount = ~~(this.triangles.length * settings.quality);
  28354. var deletedTriangles = 0;
  28355. var triangleCount = this.triangles.length;
  28356. var iterationFunction = function (iteration, callback) {
  28357. setTimeout(function () {
  28358. if (iteration % 5 === 0) {
  28359. _this.updateMesh(iteration === 0);
  28360. }
  28361. for (var i = 0; i < _this.triangles.length; ++i) {
  28362. _this.triangles[i].isDirty = false;
  28363. }
  28364. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  28365. var trianglesIterator = function (i) {
  28366. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  28367. var t = _this.triangles[tIdx];
  28368. if (!t)
  28369. return;
  28370. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  28371. return;
  28372. }
  28373. for (var j = 0; j < 3; ++j) {
  28374. if (t.error[j] < threshold) {
  28375. var deleted0 = [];
  28376. var deleted1 = [];
  28377. var v0 = t.vertices[j];
  28378. var v1 = t.vertices[(j + 1) % 3];
  28379. if (v0.isBorder !== v1.isBorder)
  28380. continue;
  28381. var p = BABYLON.Vector3.Zero();
  28382. var n = BABYLON.Vector3.Zero();
  28383. var uv = BABYLON.Vector2.Zero();
  28384. var color = new BABYLON.Color4(0, 0, 0, 1);
  28385. _this.calculateError(v0, v1, p, n, uv, color);
  28386. var delTr = [];
  28387. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  28388. continue;
  28389. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  28390. continue;
  28391. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  28392. continue;
  28393. var uniqueArray = [];
  28394. delTr.forEach(function (deletedT) {
  28395. if (uniqueArray.indexOf(deletedT) === -1) {
  28396. deletedT.deletePending = true;
  28397. uniqueArray.push(deletedT);
  28398. }
  28399. });
  28400. if (uniqueArray.length % 2 !== 0) {
  28401. continue;
  28402. }
  28403. v0.q = v1.q.add(v0.q);
  28404. v0.updatePosition(p);
  28405. var tStart = _this.references.length;
  28406. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  28407. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  28408. var tCount = _this.references.length - tStart;
  28409. if (tCount <= v0.triangleCount) {
  28410. if (tCount) {
  28411. for (var c = 0; c < tCount; c++) {
  28412. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  28413. }
  28414. }
  28415. }
  28416. else {
  28417. v0.triangleStart = tStart;
  28418. }
  28419. v0.triangleCount = tCount;
  28420. break;
  28421. }
  28422. }
  28423. };
  28424. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  28425. }, 0);
  28426. };
  28427. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  28428. if (triangleCount - deletedTriangles <= targetCount)
  28429. loop.breakLoop();
  28430. else {
  28431. iterationFunction(loop.index, function () {
  28432. loop.executeNext();
  28433. });
  28434. }
  28435. }, function () {
  28436. setTimeout(function () {
  28437. //reconstruct this part of the mesh
  28438. _this.reconstructMesh(submeshIndex);
  28439. successCallback();
  28440. }, 0);
  28441. });
  28442. };
  28443. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  28444. var _this = this;
  28445. this.vertices = [];
  28446. this.triangles = [];
  28447. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28448. var indices = this._mesh.getIndices();
  28449. var submesh = this._mesh.subMeshes[submeshIndex];
  28450. var findInVertices = function (positionToSearch) {
  28451. if (optimizeMesh) {
  28452. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  28453. if (_this.vertices[ii].position.equals(positionToSearch)) {
  28454. return _this.vertices[ii];
  28455. }
  28456. }
  28457. }
  28458. return null;
  28459. };
  28460. var vertexReferences = [];
  28461. var vertexInit = function (i) {
  28462. var offset = i + submesh.verticesStart;
  28463. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  28464. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  28465. vertex.originalOffsets.push(offset);
  28466. if (vertex.id === _this.vertices.length) {
  28467. _this.vertices.push(vertex);
  28468. }
  28469. vertexReferences.push(vertex.id);
  28470. };
  28471. //var totalVertices = mesh.getTotalVertices();
  28472. var totalVertices = submesh.verticesCount;
  28473. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  28474. var indicesInit = function (i) {
  28475. var offset = (submesh.indexStart / 3) + i;
  28476. var pos = (offset * 3);
  28477. var i0 = indices[pos + 0];
  28478. var i1 = indices[pos + 1];
  28479. var i2 = indices[pos + 2];
  28480. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  28481. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  28482. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  28483. var triangle = new DecimationTriangle([v0, v1, v2]);
  28484. triangle.originalOffset = pos;
  28485. _this.triangles.push(triangle);
  28486. };
  28487. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  28488. _this.init(callback);
  28489. });
  28490. });
  28491. };
  28492. QuadraticErrorSimplification.prototype.init = function (callback) {
  28493. var _this = this;
  28494. var triangleInit1 = function (i) {
  28495. var t = _this.triangles[i];
  28496. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  28497. for (var j = 0; j < 3; j++) {
  28498. 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))));
  28499. }
  28500. };
  28501. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  28502. var triangleInit2 = function (i) {
  28503. var t = _this.triangles[i];
  28504. for (var j = 0; j < 3; ++j) {
  28505. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  28506. }
  28507. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  28508. };
  28509. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  28510. _this.initialized = true;
  28511. callback();
  28512. });
  28513. });
  28514. };
  28515. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  28516. var newTriangles = [];
  28517. var i;
  28518. for (i = 0; i < this.vertices.length; ++i) {
  28519. this.vertices[i].triangleCount = 0;
  28520. }
  28521. var t;
  28522. var j;
  28523. for (i = 0; i < this.triangles.length; ++i) {
  28524. if (!this.triangles[i].deleted) {
  28525. t = this.triangles[i];
  28526. for (j = 0; j < 3; ++j) {
  28527. t.vertices[j].triangleCount = 1;
  28528. }
  28529. newTriangles.push(t);
  28530. }
  28531. }
  28532. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  28533. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  28534. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  28535. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  28536. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28537. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  28538. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  28539. var vertexCount = 0;
  28540. for (i = 0; i < this.vertices.length; ++i) {
  28541. var vertex = this.vertices[i];
  28542. vertex.id = vertexCount;
  28543. if (vertex.triangleCount) {
  28544. vertex.originalOffsets.forEach(function (originalOffset) {
  28545. newPositionData.push(vertex.position.x);
  28546. newPositionData.push(vertex.position.y);
  28547. newPositionData.push(vertex.position.z);
  28548. newNormalData.push(normalData[originalOffset * 3]);
  28549. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  28550. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  28551. if (uvs && uvs.length) {
  28552. newUVsData.push(uvs[(originalOffset * 2)]);
  28553. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  28554. }
  28555. else if (colorsData && colorsData.length) {
  28556. newColorsData.push(colorsData[(originalOffset * 4)]);
  28557. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  28558. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  28559. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  28560. }
  28561. ++vertexCount;
  28562. });
  28563. }
  28564. }
  28565. var startingIndex = this._reconstructedMesh.getTotalIndices();
  28566. var startingVertex = this._reconstructedMesh.getTotalVertices();
  28567. var submeshesArray = this._reconstructedMesh.subMeshes;
  28568. this._reconstructedMesh.subMeshes = [];
  28569. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  28570. var originalIndices = this._mesh.getIndices();
  28571. for (i = 0; i < newTriangles.length; ++i) {
  28572. t = newTriangles[i]; //now get the new referencing point for each vertex
  28573. [0, 1, 2].forEach(function (idx) {
  28574. var id = originalIndices[t.originalOffset + idx];
  28575. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  28576. if (offset < 0)
  28577. offset = 0;
  28578. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  28579. });
  28580. }
  28581. //overwriting the old vertex buffers and indices.
  28582. this._reconstructedMesh.setIndices(newIndicesArray);
  28583. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  28584. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  28585. if (newUVsData.length > 0)
  28586. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  28587. if (newColorsData.length > 0)
  28588. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  28589. //create submesh
  28590. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  28591. if (submeshIndex > 0) {
  28592. this._reconstructedMesh.subMeshes = [];
  28593. submeshesArray.forEach(function (submesh) {
  28594. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  28595. });
  28596. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  28597. }
  28598. };
  28599. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  28600. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  28601. this._reconstructedMesh.material = this._mesh.material;
  28602. this._reconstructedMesh.parent = this._mesh.parent;
  28603. this._reconstructedMesh.isVisible = false;
  28604. };
  28605. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  28606. for (var i = 0; i < vertex1.triangleCount; ++i) {
  28607. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  28608. if (t.deleted)
  28609. continue;
  28610. var s = this.references[vertex1.triangleStart + i].vertexId;
  28611. var v1 = t.vertices[(s + 1) % 3];
  28612. var v2 = t.vertices[(s + 2) % 3];
  28613. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  28614. deletedArray[i] = true;
  28615. delTr.push(t);
  28616. continue;
  28617. }
  28618. var d1 = v1.position.subtract(point);
  28619. d1 = d1.normalize();
  28620. var d2 = v2.position.subtract(point);
  28621. d2 = d2.normalize();
  28622. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  28623. return true;
  28624. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  28625. deletedArray[i] = false;
  28626. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  28627. return true;
  28628. }
  28629. return false;
  28630. };
  28631. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  28632. var newDeleted = deletedTriangles;
  28633. for (var i = 0; i < vertex.triangleCount; ++i) {
  28634. var ref = this.references[vertex.triangleStart + i];
  28635. var t = this.triangles[ref.triangleId];
  28636. if (t.deleted)
  28637. continue;
  28638. if (deletedArray[i] && t.deletePending) {
  28639. t.deleted = true;
  28640. newDeleted++;
  28641. continue;
  28642. }
  28643. t.vertices[ref.vertexId] = origVertex;
  28644. t.isDirty = true;
  28645. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  28646. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  28647. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  28648. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  28649. this.references.push(ref);
  28650. }
  28651. return newDeleted;
  28652. };
  28653. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  28654. for (var i = 0; i < this.vertices.length; ++i) {
  28655. var vCount = [];
  28656. var vId = [];
  28657. var v = this.vertices[i];
  28658. var j;
  28659. for (j = 0; j < v.triangleCount; ++j) {
  28660. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  28661. for (var ii = 0; ii < 3; ii++) {
  28662. var ofs = 0;
  28663. var vv = triangle.vertices[ii];
  28664. while (ofs < vCount.length) {
  28665. if (vId[ofs] === vv.id)
  28666. break;
  28667. ++ofs;
  28668. }
  28669. if (ofs === vCount.length) {
  28670. vCount.push(1);
  28671. vId.push(vv.id);
  28672. }
  28673. else {
  28674. vCount[ofs]++;
  28675. }
  28676. }
  28677. }
  28678. for (j = 0; j < vCount.length; ++j) {
  28679. if (vCount[j] === 1) {
  28680. this.vertices[vId[j]].isBorder = true;
  28681. }
  28682. else {
  28683. this.vertices[vId[j]].isBorder = false;
  28684. }
  28685. }
  28686. }
  28687. };
  28688. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  28689. if (identifyBorders === void 0) { identifyBorders = false; }
  28690. var i;
  28691. if (!identifyBorders) {
  28692. var newTrianglesVector = [];
  28693. for (i = 0; i < this.triangles.length; ++i) {
  28694. if (!this.triangles[i].deleted) {
  28695. newTrianglesVector.push(this.triangles[i]);
  28696. }
  28697. }
  28698. this.triangles = newTrianglesVector;
  28699. }
  28700. for (i = 0; i < this.vertices.length; ++i) {
  28701. this.vertices[i].triangleCount = 0;
  28702. this.vertices[i].triangleStart = 0;
  28703. }
  28704. var t;
  28705. var j;
  28706. var v;
  28707. for (i = 0; i < this.triangles.length; ++i) {
  28708. t = this.triangles[i];
  28709. for (j = 0; j < 3; ++j) {
  28710. v = t.vertices[j];
  28711. v.triangleCount++;
  28712. }
  28713. }
  28714. var tStart = 0;
  28715. for (i = 0; i < this.vertices.length; ++i) {
  28716. this.vertices[i].triangleStart = tStart;
  28717. tStart += this.vertices[i].triangleCount;
  28718. this.vertices[i].triangleCount = 0;
  28719. }
  28720. var newReferences = new Array(this.triangles.length * 3);
  28721. for (i = 0; i < this.triangles.length; ++i) {
  28722. t = this.triangles[i];
  28723. for (j = 0; j < 3; ++j) {
  28724. v = t.vertices[j];
  28725. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  28726. v.triangleCount++;
  28727. }
  28728. }
  28729. this.references = newReferences;
  28730. if (identifyBorders) {
  28731. this.identifyBorder();
  28732. }
  28733. };
  28734. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  28735. var x = point.x;
  28736. var y = point.y;
  28737. var z = point.z;
  28738. 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
  28739. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  28740. };
  28741. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  28742. var q = vertex1.q.add(vertex2.q);
  28743. var border = vertex1.isBorder && vertex2.isBorder;
  28744. var error = 0;
  28745. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  28746. if (qDet !== 0 && !border) {
  28747. if (!pointResult) {
  28748. pointResult = BABYLON.Vector3.Zero();
  28749. }
  28750. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  28751. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  28752. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  28753. error = this.vertexError(q, pointResult);
  28754. }
  28755. else {
  28756. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  28757. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  28758. var error1 = this.vertexError(q, vertex1.position);
  28759. var error2 = this.vertexError(q, vertex2.position);
  28760. var error3 = this.vertexError(q, p3);
  28761. error = Math.min(error1, error2, error3);
  28762. if (error === error1) {
  28763. if (pointResult) {
  28764. pointResult.copyFrom(vertex1.position);
  28765. }
  28766. }
  28767. else if (error === error2) {
  28768. if (pointResult) {
  28769. pointResult.copyFrom(vertex2.position);
  28770. }
  28771. }
  28772. else {
  28773. if (pointResult) {
  28774. pointResult.copyFrom(p3);
  28775. }
  28776. }
  28777. }
  28778. return error;
  28779. };
  28780. return QuadraticErrorSimplification;
  28781. })();
  28782. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  28783. })(BABYLON || (BABYLON = {}));
  28784. var BABYLON;
  28785. (function (BABYLON) {
  28786. var serializeLight = function (light) {
  28787. var serializationObject = {};
  28788. serializationObject.name = light.name;
  28789. serializationObject.id = light.id;
  28790. serializationObject.tags = BABYLON.Tags.GetTags(light);
  28791. if (light instanceof BABYLON.PointLight) {
  28792. serializationObject.type = 0;
  28793. serializationObject.position = (light).position.asArray();
  28794. }
  28795. else if (light instanceof BABYLON.DirectionalLight) {
  28796. serializationObject.type = 1;
  28797. var directionalLight = light;
  28798. serializationObject.position = directionalLight.position.asArray();
  28799. serializationObject.direction = directionalLight.direction.asArray();
  28800. }
  28801. else if (light instanceof BABYLON.SpotLight) {
  28802. serializationObject.type = 2;
  28803. var spotLight = light;
  28804. serializationObject.position = spotLight.position.asArray();
  28805. serializationObject.direction = spotLight.position.asArray();
  28806. serializationObject.angle = spotLight.angle;
  28807. serializationObject.exponent = spotLight.exponent;
  28808. }
  28809. else if (light instanceof BABYLON.HemisphericLight) {
  28810. serializationObject.type = 3;
  28811. var hemisphericLight = light;
  28812. serializationObject.direction = hemisphericLight.direction.asArray();
  28813. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  28814. }
  28815. if (light.intensity) {
  28816. serializationObject.intensity = light.intensity;
  28817. }
  28818. serializationObject.range = light.range;
  28819. serializationObject.diffuse = light.diffuse.asArray();
  28820. serializationObject.specular = light.specular.asArray();
  28821. return serializationObject;
  28822. };
  28823. var serializeFresnelParameter = function (fresnelParameter) {
  28824. var serializationObject = {};
  28825. serializationObject.isEnabled = fresnelParameter.isEnabled;
  28826. serializationObject.leftColor = fresnelParameter.leftColor;
  28827. serializationObject.rightColor = fresnelParameter.rightColor;
  28828. serializationObject.bias = fresnelParameter.bias;
  28829. serializationObject.power = fresnelParameter.power;
  28830. return serializationObject;
  28831. };
  28832. var serializeAnimation;
  28833. var appendAnimations = function (source, destination) {
  28834. if (source.animations) {
  28835. destination.animations = [];
  28836. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  28837. var animation = source.animations[animationIndex];
  28838. destination.animations.push(serializeAnimation(animation));
  28839. }
  28840. }
  28841. };
  28842. var serializeCamera = function (camera) {
  28843. var serializationObject = {};
  28844. serializationObject.name = camera.name;
  28845. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  28846. serializationObject.id = camera.id;
  28847. serializationObject.position = camera.position.asArray();
  28848. // Parent
  28849. if (camera.parent) {
  28850. serializationObject.parentId = camera.parent.id;
  28851. }
  28852. serializationObject.fov = camera.fov;
  28853. serializationObject.minZ = camera.minZ;
  28854. serializationObject.maxZ = camera.maxZ;
  28855. serializationObject.inertia = camera.inertia;
  28856. //setting the type
  28857. if (camera instanceof BABYLON.FreeCamera) {
  28858. serializationObject.type = "FreeCamera";
  28859. }
  28860. else if (camera instanceof BABYLON.ArcRotateCamera) {
  28861. serializationObject.type = "ArcRotateCamera";
  28862. }
  28863. else if (camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  28864. serializationObject.type = "AnaglyphArcRotateCamera";
  28865. }
  28866. else if (camera instanceof BABYLON.GamepadCamera) {
  28867. serializationObject.type = "GamepadCamera";
  28868. }
  28869. else if (camera instanceof BABYLON.AnaglyphFreeCamera) {
  28870. serializationObject.type = "AnaglyphFreeCamera";
  28871. }
  28872. else if (camera instanceof BABYLON.DeviceOrientationCamera) {
  28873. serializationObject.type = "DeviceOrientationCamera";
  28874. }
  28875. else if (camera instanceof BABYLON.FollowCamera) {
  28876. serializationObject.type = "FollowCamera";
  28877. }
  28878. else if (camera instanceof BABYLON.TouchCamera) {
  28879. serializationObject.type = "TouchCamera";
  28880. }
  28881. else if (camera instanceof BABYLON.VirtualJoysticksCamera) {
  28882. serializationObject.type = "VirtualJoysticksCamera";
  28883. }
  28884. else if (camera instanceof BABYLON.WebVRFreeCamera) {
  28885. serializationObject.type = "WebVRFreeCamera";
  28886. }
  28887. else if (camera instanceof BABYLON.VRDeviceOrientationFreeCamera) {
  28888. serializationObject.type = "VRDeviceOrientationFreeCamera";
  28889. }
  28890. //special properties of specific cameras
  28891. if (camera instanceof BABYLON.ArcRotateCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  28892. var arcCamera = camera;
  28893. serializationObject.alpha = arcCamera.alpha;
  28894. serializationObject.beta = arcCamera.beta;
  28895. serializationObject.radius = arcCamera.radius;
  28896. if (arcCamera.target && arcCamera.target.id) {
  28897. serializationObject.lockedTargetId = arcCamera.target.id;
  28898. }
  28899. }
  28900. else if (camera instanceof BABYLON.FollowCamera) {
  28901. var followCam = camera;
  28902. serializationObject.radius = followCam.radius;
  28903. serializationObject.heightOffset = followCam.heightOffset;
  28904. serializationObject.rotationOffset = followCam.rotationOffset;
  28905. }
  28906. else if (camera instanceof BABYLON.AnaglyphFreeCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  28907. //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.
  28908. if (camera['_interaxialDistance'] !== undefined) {
  28909. serializationObject.interaxial_distance = BABYLON.Tools.ToDegrees(camera['_interaxialDistance']);
  28910. }
  28911. }
  28912. //general properties that not all cameras have. The [] is due to typescript's type safety
  28913. if (camera['speed'] !== undefined) {
  28914. serializationObject.speed = camera['speed'];
  28915. }
  28916. if (camera['target'] && camera['target'] instanceof BABYLON.Vector3) {
  28917. serializationObject.target = camera['target'].asArray();
  28918. }
  28919. // Target
  28920. if (camera['rotation'] && camera['rotation'] instanceof BABYLON.Vector3) {
  28921. serializationObject.rotation = camera['rotation'].asArray();
  28922. }
  28923. // Locked target
  28924. if (camera['lockedTarget'] && camera['lockedTarget'].id) {
  28925. serializationObject.lockedTargetId = camera['lockedTarget'].id;
  28926. }
  28927. serializationObject.checkCollisions = camera['checkCollisions'] || false;
  28928. serializationObject.applyGravity = camera['applyGravity'] || false;
  28929. if (camera['ellipsoid']) {
  28930. serializationObject.ellipsoid = camera['ellipsoid'].asArray();
  28931. }
  28932. // Animations
  28933. appendAnimations(camera, serializationObject);
  28934. // Layer mask
  28935. serializationObject.layerMask = camera.layerMask;
  28936. return serializationObject;
  28937. };
  28938. serializeAnimation = function (animation) {
  28939. var serializationObject = {};
  28940. serializationObject.name = animation.name;
  28941. serializationObject.property = animation.targetProperty;
  28942. serializationObject.framePerSecond = animation.framePerSecond;
  28943. serializationObject.dataType = animation.dataType;
  28944. serializationObject.loopBehavior = animation.loopMode;
  28945. var dataType = animation.dataType;
  28946. serializationObject.keys = [];
  28947. var keys = animation.getKeys();
  28948. for (var index = 0; index < keys.length; index++) {
  28949. var animationKey = keys[index];
  28950. var key = {};
  28951. key.frame = animationKey.frame;
  28952. switch (dataType) {
  28953. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  28954. key.values = [animationKey.value];
  28955. break;
  28956. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  28957. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  28958. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  28959. key.values = animationKey.value.asArray();
  28960. break;
  28961. }
  28962. serializationObject.keys.push(key);
  28963. }
  28964. return serializationObject;
  28965. };
  28966. var serializeMultiMaterial = function (material) {
  28967. var serializationObject = {};
  28968. serializationObject.name = material.name;
  28969. serializationObject.id = material.id;
  28970. serializationObject.tags = BABYLON.Tags.GetTags(material);
  28971. serializationObject.materials = [];
  28972. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  28973. var subMat = material.subMaterials[matIndex];
  28974. if (subMat) {
  28975. serializationObject.materials.push(subMat.id);
  28976. }
  28977. else {
  28978. serializationObject.materials.push(null);
  28979. }
  28980. }
  28981. return serializationObject;
  28982. };
  28983. var serializeTexture;
  28984. var serializeMaterial = function (material) {
  28985. var serializationObject = {};
  28986. serializationObject.name = material.name;
  28987. serializationObject.ambient = material.ambientColor.asArray();
  28988. serializationObject.diffuse = material.diffuseColor.asArray();
  28989. serializationObject.specular = material.specularColor.asArray();
  28990. serializationObject.specularPower = material.specularPower;
  28991. serializationObject.emissive = material.emissiveColor.asArray();
  28992. serializationObject.useReflectionFresnelFromSpecular = serializationObject.useReflectionFresnelFromSpecular;
  28993. serializationObject.useEmissiveAsIllumination = serializationObject.useEmissiveAsIllumination;
  28994. serializationObject.alpha = material.alpha;
  28995. serializationObject.id = material.id;
  28996. serializationObject.tags = BABYLON.Tags.GetTags(material);
  28997. serializationObject.backFaceCulling = material.backFaceCulling;
  28998. if (material.diffuseTexture) {
  28999. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  29000. }
  29001. if (material.diffuseFresnelParameters) {
  29002. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  29003. }
  29004. if (material.ambientTexture) {
  29005. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  29006. }
  29007. if (material.opacityTexture) {
  29008. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  29009. }
  29010. if (material.opacityFresnelParameters) {
  29011. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  29012. }
  29013. if (material.reflectionTexture) {
  29014. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  29015. }
  29016. if (material.reflectionFresnelParameters) {
  29017. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  29018. }
  29019. if (material.emissiveTexture) {
  29020. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  29021. }
  29022. if (material.lightmapTexture) {
  29023. serializationObject.lightmapTexture = serializeTexture(material.lightmapTexture);
  29024. serializationObject.useLightmapAsShadowmap = material.useLightmapAsShadowmap;
  29025. }
  29026. if (material.emissiveFresnelParameters) {
  29027. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  29028. }
  29029. if (material.specularTexture) {
  29030. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  29031. }
  29032. if (material.bumpTexture) {
  29033. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  29034. }
  29035. return serializationObject;
  29036. };
  29037. serializeTexture = function (texture) {
  29038. var serializationObject = {};
  29039. if (!texture.name) {
  29040. return null;
  29041. }
  29042. if (texture instanceof BABYLON.CubeTexture) {
  29043. serializationObject.name = texture.name;
  29044. serializationObject.hasAlpha = texture.hasAlpha;
  29045. serializationObject.isCube = true;
  29046. serializationObject.level = texture.level;
  29047. serializationObject.coordinatesMode = texture.coordinatesMode;
  29048. return serializationObject;
  29049. }
  29050. var index;
  29051. if (texture instanceof BABYLON.MirrorTexture) {
  29052. var mirrorTexture = texture;
  29053. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  29054. serializationObject.renderList = [];
  29055. for (index = 0; index < mirrorTexture.renderList.length; index++) {
  29056. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  29057. }
  29058. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  29059. }
  29060. else if (texture instanceof BABYLON.RenderTargetTexture) {
  29061. var renderTargetTexture = texture;
  29062. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  29063. serializationObject.renderList = [];
  29064. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  29065. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  29066. }
  29067. }
  29068. var regularTexture = texture;
  29069. serializationObject.name = texture.name;
  29070. serializationObject.hasAlpha = texture.hasAlpha;
  29071. serializationObject.level = texture.level;
  29072. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  29073. serializationObject.coordinatesMode = texture.coordinatesMode;
  29074. serializationObject.uOffset = regularTexture.uOffset;
  29075. serializationObject.vOffset = regularTexture.vOffset;
  29076. serializationObject.uScale = regularTexture.uScale;
  29077. serializationObject.vScale = regularTexture.vScale;
  29078. serializationObject.uAng = regularTexture.uAng;
  29079. serializationObject.vAng = regularTexture.vAng;
  29080. serializationObject.wAng = regularTexture.wAng;
  29081. serializationObject.wrapU = texture.wrapU;
  29082. serializationObject.wrapV = texture.wrapV;
  29083. // Animations
  29084. appendAnimations(texture, serializationObject);
  29085. return serializationObject;
  29086. };
  29087. var serializeSkeleton = function (skeleton) {
  29088. var serializationObject = {};
  29089. serializationObject.name = skeleton.name;
  29090. serializationObject.id = skeleton.id;
  29091. serializationObject.bones = [];
  29092. for (var index = 0; index < skeleton.bones.length; index++) {
  29093. var bone = skeleton.bones[index];
  29094. var serializedBone = {
  29095. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  29096. name: bone.name,
  29097. matrix: bone.getLocalMatrix().toArray()
  29098. };
  29099. serializationObject.bones.push(serializedBone);
  29100. if (bone.animations && bone.animations.length > 0) {
  29101. serializedBone.animation = serializeAnimation(bone.animations[0]);
  29102. }
  29103. }
  29104. return serializationObject;
  29105. };
  29106. var serializeParticleSystem = function (particleSystem) {
  29107. var serializationObject = {};
  29108. serializationObject.emitterId = particleSystem.emitter.id;
  29109. serializationObject.capacity = particleSystem.getCapacity();
  29110. if (particleSystem.particleTexture) {
  29111. serializationObject.textureName = particleSystem.particleTexture.name;
  29112. }
  29113. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  29114. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  29115. serializationObject.minSize = particleSystem.minSize;
  29116. serializationObject.maxSize = particleSystem.maxSize;
  29117. serializationObject.minLifeTime = particleSystem.minLifeTime;
  29118. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  29119. serializationObject.emitRate = particleSystem.emitRate;
  29120. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  29121. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  29122. serializationObject.gravity = particleSystem.gravity.asArray();
  29123. serializationObject.direction1 = particleSystem.direction1.asArray();
  29124. serializationObject.direction2 = particleSystem.direction2.asArray();
  29125. serializationObject.color1 = particleSystem.color1.asArray();
  29126. serializationObject.color2 = particleSystem.color2.asArray();
  29127. serializationObject.colorDead = particleSystem.colorDead.asArray();
  29128. serializationObject.updateSpeed = particleSystem.updateSpeed;
  29129. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  29130. serializationObject.textureMask = particleSystem.textureMask.asArray();
  29131. serializationObject.blendMode = particleSystem.blendMode;
  29132. return serializationObject;
  29133. };
  29134. var serializeLensFlareSystem = function (lensFlareSystem) {
  29135. var serializationObject = {};
  29136. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  29137. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  29138. serializationObject.flares = [];
  29139. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  29140. var flare = lensFlareSystem.lensFlares[index];
  29141. serializationObject.flares.push({
  29142. size: flare.size,
  29143. position: flare.position,
  29144. color: flare.color.asArray(),
  29145. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  29146. });
  29147. }
  29148. return serializationObject;
  29149. };
  29150. var serializeShadowGenerator = function (light) {
  29151. var serializationObject = {};
  29152. var shadowGenerator = light.getShadowGenerator();
  29153. serializationObject.lightId = light.id;
  29154. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  29155. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  29156. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  29157. serializationObject.renderList = [];
  29158. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  29159. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  29160. serializationObject.renderList.push(mesh.id);
  29161. }
  29162. return serializationObject;
  29163. };
  29164. var serializedGeometries = [];
  29165. var serializeVertexData;
  29166. var serializeTorusKnot;
  29167. var serializePlane;
  29168. var serializeGround;
  29169. var serializeTorus;
  29170. var serializeCylinder;
  29171. var serializeSphere;
  29172. var serializeBox;
  29173. var serializeGeometry = function (geometry, serializationGeometries) {
  29174. if (serializedGeometries[geometry.id]) {
  29175. return;
  29176. }
  29177. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  29178. serializationGeometries.boxes.push(serializeBox(geometry));
  29179. }
  29180. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  29181. serializationGeometries.spheres.push(serializeSphere(geometry));
  29182. }
  29183. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  29184. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  29185. }
  29186. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  29187. serializationGeometries.toruses.push(serializeTorus(geometry));
  29188. }
  29189. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  29190. serializationGeometries.grounds.push(serializeGround(geometry));
  29191. }
  29192. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  29193. serializationGeometries.planes.push(serializePlane(geometry));
  29194. }
  29195. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  29196. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  29197. }
  29198. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  29199. throw new Error("Unknown primitive type");
  29200. }
  29201. else {
  29202. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  29203. }
  29204. serializedGeometries[geometry.id] = true;
  29205. };
  29206. var serializeGeometryBase = function (geometry) {
  29207. var serializationObject = {};
  29208. serializationObject.id = geometry.id;
  29209. if (BABYLON.Tags.HasTags(geometry)) {
  29210. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  29211. }
  29212. return serializationObject;
  29213. };
  29214. serializeVertexData = function (vertexData) {
  29215. var serializationObject = serializeGeometryBase(vertexData);
  29216. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29217. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29218. }
  29219. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29220. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29221. }
  29222. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29223. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  29224. }
  29225. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29226. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  29227. }
  29228. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  29229. serializationObject.uvs3 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  29230. }
  29231. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  29232. serializationObject.uvs4 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  29233. }
  29234. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  29235. serializationObject.uvs5 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  29236. }
  29237. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  29238. serializationObject.uvs6 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  29239. }
  29240. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  29241. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  29242. }
  29243. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  29244. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  29245. serializationObject.matricesIndices._isExpanded = true;
  29246. }
  29247. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  29248. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  29249. }
  29250. serializationObject.indices = vertexData.getIndices();
  29251. return serializationObject;
  29252. };
  29253. var serializePrimitive = function (primitive) {
  29254. var serializationObject = serializeGeometryBase(primitive);
  29255. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  29256. return serializationObject;
  29257. };
  29258. serializeBox = function (box) {
  29259. var serializationObject = serializePrimitive(box);
  29260. serializationObject.size = box.size;
  29261. return serializationObject;
  29262. };
  29263. serializeSphere = function (sphere) {
  29264. var serializationObject = serializePrimitive(sphere);
  29265. serializationObject.segments = sphere.segments;
  29266. serializationObject.diameter = sphere.diameter;
  29267. return serializationObject;
  29268. };
  29269. serializeCylinder = function (cylinder) {
  29270. var serializationObject = serializePrimitive(cylinder);
  29271. serializationObject.height = cylinder.height;
  29272. serializationObject.diameterTop = cylinder.diameterTop;
  29273. serializationObject.diameterBottom = cylinder.diameterBottom;
  29274. serializationObject.tessellation = cylinder.tessellation;
  29275. return serializationObject;
  29276. };
  29277. serializeTorus = function (torus) {
  29278. var serializationObject = serializePrimitive(torus);
  29279. serializationObject.diameter = torus.diameter;
  29280. serializationObject.thickness = torus.thickness;
  29281. serializationObject.tessellation = torus.tessellation;
  29282. return serializationObject;
  29283. };
  29284. serializeGround = function (ground) {
  29285. var serializationObject = serializePrimitive(ground);
  29286. serializationObject.width = ground.width;
  29287. serializationObject.height = ground.height;
  29288. serializationObject.subdivisions = ground.subdivisions;
  29289. return serializationObject;
  29290. };
  29291. serializePlane = function (plane) {
  29292. var serializationObject = serializePrimitive(plane);
  29293. serializationObject.size = plane.size;
  29294. return serializationObject;
  29295. };
  29296. serializeTorusKnot = function (torusKnot) {
  29297. var serializationObject = serializePrimitive(torusKnot);
  29298. serializationObject.radius = torusKnot.radius;
  29299. serializationObject.tube = torusKnot.tube;
  29300. serializationObject.radialSegments = torusKnot.radialSegments;
  29301. serializationObject.tubularSegments = torusKnot.tubularSegments;
  29302. serializationObject.p = torusKnot.p;
  29303. serializationObject.q = torusKnot.q;
  29304. return serializationObject;
  29305. };
  29306. var serializeMesh = function (mesh, serializationScene) {
  29307. var serializationObject = {};
  29308. serializationObject.name = mesh.name;
  29309. serializationObject.id = mesh.id;
  29310. if (BABYLON.Tags.HasTags(mesh)) {
  29311. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  29312. }
  29313. serializationObject.position = mesh.position.asArray();
  29314. if (mesh.rotationQuaternion) {
  29315. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  29316. }
  29317. else if (mesh.rotation) {
  29318. serializationObject.rotation = mesh.rotation.asArray();
  29319. }
  29320. serializationObject.scaling = mesh.scaling.asArray();
  29321. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  29322. serializationObject.isEnabled = mesh.isEnabled();
  29323. serializationObject.isVisible = mesh.isVisible;
  29324. serializationObject.infiniteDistance = mesh.infiniteDistance;
  29325. serializationObject.pickable = mesh.isPickable;
  29326. serializationObject.receiveShadows = mesh.receiveShadows;
  29327. serializationObject.billboardMode = mesh.billboardMode;
  29328. serializationObject.visibility = mesh.visibility;
  29329. serializationObject.checkCollisions = mesh.checkCollisions;
  29330. // Parent
  29331. if (mesh.parent) {
  29332. serializationObject.parentId = mesh.parent.id;
  29333. }
  29334. // Geometry
  29335. var geometry = mesh._geometry;
  29336. if (geometry) {
  29337. var geometryId = geometry.id;
  29338. serializationObject.geometryId = geometryId;
  29339. if (!mesh.getScene().getGeometryByID(geometryId)) {
  29340. // 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
  29341. serializeGeometry(geometry, serializationScene.geometries);
  29342. }
  29343. // SubMeshes
  29344. serializationObject.subMeshes = [];
  29345. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  29346. var subMesh = mesh.subMeshes[subIndex];
  29347. serializationObject.subMeshes.push({
  29348. materialIndex: subMesh.materialIndex,
  29349. verticesStart: subMesh.verticesStart,
  29350. verticesCount: subMesh.verticesCount,
  29351. indexStart: subMesh.indexStart,
  29352. indexCount: subMesh.indexCount
  29353. });
  29354. }
  29355. }
  29356. // Material
  29357. if (mesh.material) {
  29358. serializationObject.materialId = mesh.material.id;
  29359. }
  29360. else {
  29361. mesh.material = null;
  29362. }
  29363. // Skeleton
  29364. if (mesh.skeleton) {
  29365. serializationObject.skeletonId = mesh.skeleton.id;
  29366. }
  29367. // Physics
  29368. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  29369. serializationObject.physicsMass = mesh.getPhysicsMass();
  29370. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  29371. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  29372. switch (mesh.getPhysicsImpostor()) {
  29373. case BABYLON.PhysicsEngine.BoxImpostor:
  29374. serializationObject.physicsImpostor = 1;
  29375. break;
  29376. case BABYLON.PhysicsEngine.SphereImpostor:
  29377. serializationObject.physicsImpostor = 2;
  29378. break;
  29379. }
  29380. }
  29381. // Instances
  29382. serializationObject.instances = [];
  29383. for (var index = 0; index < mesh.instances.length; index++) {
  29384. var instance = mesh.instances[index];
  29385. var serializationInstance = {
  29386. name: instance.name,
  29387. position: instance.position.asArray(),
  29388. rotation: instance.rotation.asArray(),
  29389. rotationQuaternion: instance.rotationQuaternion.asArray(),
  29390. scaling: instance.scaling.asArray()
  29391. };
  29392. serializationObject.instances.push(serializationInstance);
  29393. // Animations
  29394. appendAnimations(instance, serializationInstance);
  29395. }
  29396. // Animations
  29397. appendAnimations(mesh, serializationObject);
  29398. // Layer mask
  29399. serializationObject.layerMask = mesh.layerMask;
  29400. return serializationObject;
  29401. };
  29402. var finalizeSingleMesh = function (mesh, serializationObject) {
  29403. //only works if the mesh is already loaded
  29404. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  29405. //serialize material
  29406. if (mesh.material) {
  29407. if (mesh.material instanceof BABYLON.StandardMaterial) {
  29408. serializationObject.materials = serializationObject.materials || [];
  29409. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  29410. serializationObject.materials.push(serializeMaterial(mesh.material));
  29411. }
  29412. }
  29413. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  29414. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  29415. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  29416. serializationObject.multiMaterials.push(serializeMultiMaterial(mesh.material));
  29417. }
  29418. }
  29419. }
  29420. //serialize geometry
  29421. var geometry = mesh._geometry;
  29422. if (geometry) {
  29423. if (!serializationObject.geometries) {
  29424. serializationObject.geometries = {};
  29425. serializationObject.geometries.boxes = [];
  29426. serializationObject.geometries.spheres = [];
  29427. serializationObject.geometries.cylinders = [];
  29428. serializationObject.geometries.toruses = [];
  29429. serializationObject.geometries.grounds = [];
  29430. serializationObject.geometries.planes = [];
  29431. serializationObject.geometries.torusKnots = [];
  29432. serializationObject.geometries.vertexData = [];
  29433. }
  29434. serializeGeometry(geometry, serializationObject.geometries);
  29435. }
  29436. // Skeletons
  29437. if (mesh.skeleton) {
  29438. serializationObject.skeletons = serializationObject.skeletons || [];
  29439. serializationObject.skeletons.push(serializeSkeleton(mesh.skeleton));
  29440. }
  29441. //serialize the actual mesh
  29442. serializationObject.meshes = serializationObject.meshes || [];
  29443. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  29444. }
  29445. };
  29446. var SceneSerializer = (function () {
  29447. function SceneSerializer() {
  29448. }
  29449. SceneSerializer.Serialize = function (scene) {
  29450. var serializationObject = {};
  29451. // Scene
  29452. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  29453. serializationObject.autoClear = scene.autoClear;
  29454. serializationObject.clearColor = scene.clearColor.asArray();
  29455. serializationObject.ambientColor = scene.ambientColor.asArray();
  29456. serializationObject.gravity = scene.gravity.asArray();
  29457. // Fog
  29458. if (scene.fogMode && scene.fogMode !== 0) {
  29459. serializationObject.fogMode = scene.fogMode;
  29460. serializationObject.fogColor = scene.fogColor.asArray();
  29461. serializationObject.fogStart = scene.fogStart;
  29462. serializationObject.fogEnd = scene.fogEnd;
  29463. serializationObject.fogDensity = scene.fogDensity;
  29464. }
  29465. // Lights
  29466. serializationObject.lights = [];
  29467. var index;
  29468. var light;
  29469. for (index = 0; index < scene.lights.length; index++) {
  29470. light = scene.lights[index];
  29471. serializationObject.lights.push(serializeLight(light));
  29472. }
  29473. // Cameras
  29474. serializationObject.cameras = [];
  29475. for (index = 0; index < scene.cameras.length; index++) {
  29476. var camera = scene.cameras[index];
  29477. serializationObject.cameras.push(serializeCamera(camera));
  29478. }
  29479. if (scene.activeCamera) {
  29480. serializationObject.activeCameraID = scene.activeCamera.id;
  29481. }
  29482. // Materials
  29483. serializationObject.materials = [];
  29484. serializationObject.multiMaterials = [];
  29485. var material;
  29486. for (index = 0; index < scene.materials.length; index++) {
  29487. material = scene.materials[index];
  29488. serializationObject.materials.push(serializeMaterial(material));
  29489. }
  29490. // MultiMaterials
  29491. serializationObject.multiMaterials = [];
  29492. for (index = 0; index < scene.multiMaterials.length; index++) {
  29493. var multiMaterial = scene.multiMaterials[index];
  29494. serializationObject.multiMaterials.push(serializeMultiMaterial(multiMaterial));
  29495. }
  29496. for (index = 0; index < scene.materials.length; index++) {
  29497. material = scene.materials[index];
  29498. if (material instanceof BABYLON.StandardMaterial) {
  29499. serializationObject.materials.push(serializeMaterial(material));
  29500. }
  29501. else if (material instanceof BABYLON.MultiMaterial) {
  29502. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  29503. }
  29504. }
  29505. // Skeletons
  29506. serializationObject.skeletons = [];
  29507. for (index = 0; index < scene.skeletons.length; index++) {
  29508. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  29509. }
  29510. // Geometries
  29511. serializationObject.geometries = {};
  29512. serializationObject.geometries.boxes = [];
  29513. serializationObject.geometries.spheres = [];
  29514. serializationObject.geometries.cylinders = [];
  29515. serializationObject.geometries.toruses = [];
  29516. serializationObject.geometries.grounds = [];
  29517. serializationObject.geometries.planes = [];
  29518. serializationObject.geometries.torusKnots = [];
  29519. serializationObject.geometries.vertexData = [];
  29520. serializedGeometries = [];
  29521. var geometries = scene.getGeometries();
  29522. for (index = 0; index < geometries.length; index++) {
  29523. var geometry = geometries[index];
  29524. if (geometry.isReady()) {
  29525. serializeGeometry(geometry, serializationObject.geometries);
  29526. }
  29527. }
  29528. // Meshes
  29529. serializationObject.meshes = [];
  29530. for (index = 0; index < scene.meshes.length; index++) {
  29531. var abstractMesh = scene.meshes[index];
  29532. if (abstractMesh instanceof BABYLON.Mesh) {
  29533. var mesh = abstractMesh;
  29534. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  29535. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  29536. }
  29537. }
  29538. }
  29539. // Particles Systems
  29540. serializationObject.particleSystems = [];
  29541. for (index = 0; index < scene.particleSystems.length; index++) {
  29542. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  29543. }
  29544. // Lens flares
  29545. serializationObject.lensFlareSystems = [];
  29546. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  29547. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  29548. }
  29549. // Shadows
  29550. serializationObject.shadowGenerators = [];
  29551. for (index = 0; index < scene.lights.length; index++) {
  29552. light = scene.lights[index];
  29553. if (light.getShadowGenerator()) {
  29554. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  29555. }
  29556. }
  29557. return serializationObject;
  29558. };
  29559. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  29560. if (withParents === void 0) { withParents = false; }
  29561. if (withChildren === void 0) { withChildren = false; }
  29562. var serializationObject = {};
  29563. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  29564. if (withParents || withChildren) {
  29565. //deliberate for loop! not for each, appended should be processed as well.
  29566. for (var i = 0; i < toSerialize.length; ++i) {
  29567. if (withChildren) {
  29568. toSerialize[i].getDescendants().forEach(function (node) {
  29569. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  29570. toSerialize.push(node);
  29571. }
  29572. });
  29573. }
  29574. //make sure the array doesn't contain the object already
  29575. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  29576. toSerialize.push(toSerialize[i].parent);
  29577. }
  29578. }
  29579. }
  29580. toSerialize.forEach(function (mesh) {
  29581. finalizeSingleMesh(mesh, serializationObject);
  29582. });
  29583. return serializationObject;
  29584. };
  29585. return SceneSerializer;
  29586. })();
  29587. BABYLON.SceneSerializer = SceneSerializer;
  29588. })(BABYLON || (BABYLON = {}));
  29589. var BABYLON;
  29590. (function (BABYLON) {
  29591. // Unique ID when we import meshes from Babylon to CSG
  29592. var currentCSGMeshId = 0;
  29593. // # class Vertex
  29594. // Represents a vertex of a polygon. Use your own vertex class instead of this
  29595. // one to provide additional features like texture coordinates and vertex
  29596. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  29597. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  29598. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  29599. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  29600. // is not used anywhere else.
  29601. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  29602. var Vertex = (function () {
  29603. function Vertex(pos, normal, uv) {
  29604. this.pos = pos;
  29605. this.normal = normal;
  29606. this.uv = uv;
  29607. }
  29608. Vertex.prototype.clone = function () {
  29609. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  29610. };
  29611. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  29612. // orientation of a polygon is flipped.
  29613. Vertex.prototype.flip = function () {
  29614. this.normal = this.normal.scale(-1);
  29615. };
  29616. // Create a new vertex between this vertex and `other` by linearly
  29617. // interpolating all properties using a parameter of `t`. Subclasses should
  29618. // override this to interpolate additional properties.
  29619. Vertex.prototype.interpolate = function (other, t) {
  29620. 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));
  29621. };
  29622. return Vertex;
  29623. })();
  29624. // # class Plane
  29625. // Represents a plane in 3D space.
  29626. var Plane = (function () {
  29627. function Plane(normal, w) {
  29628. this.normal = normal;
  29629. this.w = w;
  29630. }
  29631. Plane.FromPoints = function (a, b, c) {
  29632. var v0 = c.subtract(a);
  29633. var v1 = b.subtract(a);
  29634. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  29635. return null;
  29636. }
  29637. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  29638. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  29639. };
  29640. Plane.prototype.clone = function () {
  29641. return new Plane(this.normal.clone(), this.w);
  29642. };
  29643. Plane.prototype.flip = function () {
  29644. this.normal.scaleInPlace(-1);
  29645. this.w = -this.w;
  29646. };
  29647. // Split `polygon` by this plane if needed, then put the polygon or polygon
  29648. // fragments in the appropriate lists. Coplanar polygons go into either
  29649. // `coplanarFront` or `coplanarBack` depending on their orientation with
  29650. // respect to this plane. Polygons in front or in back of this plane go into
  29651. // either `front` or `back`.
  29652. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  29653. var COPLANAR = 0;
  29654. var FRONT = 1;
  29655. var BACK = 2;
  29656. var SPANNING = 3;
  29657. // Classify each point as well as the entire polygon into one of the above
  29658. // four classes.
  29659. var polygonType = 0;
  29660. var types = [];
  29661. var i;
  29662. var t;
  29663. for (i = 0; i < polygon.vertices.length; i++) {
  29664. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  29665. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  29666. polygonType |= type;
  29667. types.push(type);
  29668. }
  29669. // Put the polygon in the correct list, splitting it when necessary.
  29670. switch (polygonType) {
  29671. case COPLANAR:
  29672. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  29673. break;
  29674. case FRONT:
  29675. front.push(polygon);
  29676. break;
  29677. case BACK:
  29678. back.push(polygon);
  29679. break;
  29680. case SPANNING:
  29681. var f = [], b = [];
  29682. for (i = 0; i < polygon.vertices.length; i++) {
  29683. var j = (i + 1) % polygon.vertices.length;
  29684. var ti = types[i], tj = types[j];
  29685. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  29686. if (ti !== BACK)
  29687. f.push(vi);
  29688. if (ti !== FRONT)
  29689. b.push(ti !== BACK ? vi.clone() : vi);
  29690. if ((ti | tj) === SPANNING) {
  29691. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  29692. var v = vi.interpolate(vj, t);
  29693. f.push(v);
  29694. b.push(v.clone());
  29695. }
  29696. }
  29697. var poly;
  29698. if (f.length >= 3) {
  29699. poly = new Polygon(f, polygon.shared);
  29700. if (poly.plane)
  29701. front.push(poly);
  29702. }
  29703. if (b.length >= 3) {
  29704. poly = new Polygon(b, polygon.shared);
  29705. if (poly.plane)
  29706. back.push(poly);
  29707. }
  29708. break;
  29709. }
  29710. };
  29711. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  29712. // point is on the plane.
  29713. Plane.EPSILON = 1e-5;
  29714. return Plane;
  29715. })();
  29716. // # class Polygon
  29717. // Represents a convex polygon. The vertices used to initialize a polygon must
  29718. // be coplanar and form a convex loop.
  29719. //
  29720. // Each convex polygon has a `shared` property, which is shared between all
  29721. // polygons that are clones of each other or were split from the same polygon.
  29722. // This can be used to define per-polygon properties (such as surface color).
  29723. var Polygon = (function () {
  29724. function Polygon(vertices, shared) {
  29725. this.vertices = vertices;
  29726. this.shared = shared;
  29727. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  29728. }
  29729. Polygon.prototype.clone = function () {
  29730. var vertices = this.vertices.map(function (v) { return v.clone(); });
  29731. return new Polygon(vertices, this.shared);
  29732. };
  29733. Polygon.prototype.flip = function () {
  29734. this.vertices.reverse().map(function (v) { v.flip(); });
  29735. this.plane.flip();
  29736. };
  29737. return Polygon;
  29738. })();
  29739. // # class Node
  29740. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  29741. // by picking a polygon to split along. That polygon (and all other coplanar
  29742. // polygons) are added directly to that node and the other polygons are added to
  29743. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  29744. // no distinction between internal and leaf nodes.
  29745. var Node = (function () {
  29746. function Node(polygons) {
  29747. this.plane = null;
  29748. this.front = null;
  29749. this.back = null;
  29750. this.polygons = [];
  29751. if (polygons) {
  29752. this.build(polygons);
  29753. }
  29754. }
  29755. Node.prototype.clone = function () {
  29756. var node = new Node();
  29757. node.plane = this.plane && this.plane.clone();
  29758. node.front = this.front && this.front.clone();
  29759. node.back = this.back && this.back.clone();
  29760. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  29761. return node;
  29762. };
  29763. // Convert solid space to empty space and empty space to solid space.
  29764. Node.prototype.invert = function () {
  29765. for (var i = 0; i < this.polygons.length; i++) {
  29766. this.polygons[i].flip();
  29767. }
  29768. if (this.plane) {
  29769. this.plane.flip();
  29770. }
  29771. if (this.front) {
  29772. this.front.invert();
  29773. }
  29774. if (this.back) {
  29775. this.back.invert();
  29776. }
  29777. var temp = this.front;
  29778. this.front = this.back;
  29779. this.back = temp;
  29780. };
  29781. // Recursively remove all polygons in `polygons` that are inside this BSP
  29782. // tree.
  29783. Node.prototype.clipPolygons = function (polygons) {
  29784. if (!this.plane)
  29785. return polygons.slice();
  29786. var front = [], back = [];
  29787. for (var i = 0; i < polygons.length; i++) {
  29788. this.plane.splitPolygon(polygons[i], front, back, front, back);
  29789. }
  29790. if (this.front) {
  29791. front = this.front.clipPolygons(front);
  29792. }
  29793. if (this.back) {
  29794. back = this.back.clipPolygons(back);
  29795. }
  29796. else {
  29797. back = [];
  29798. }
  29799. return front.concat(back);
  29800. };
  29801. // Remove all polygons in this BSP tree that are inside the other BSP tree
  29802. // `bsp`.
  29803. Node.prototype.clipTo = function (bsp) {
  29804. this.polygons = bsp.clipPolygons(this.polygons);
  29805. if (this.front)
  29806. this.front.clipTo(bsp);
  29807. if (this.back)
  29808. this.back.clipTo(bsp);
  29809. };
  29810. // Return a list of all polygons in this BSP tree.
  29811. Node.prototype.allPolygons = function () {
  29812. var polygons = this.polygons.slice();
  29813. if (this.front)
  29814. polygons = polygons.concat(this.front.allPolygons());
  29815. if (this.back)
  29816. polygons = polygons.concat(this.back.allPolygons());
  29817. return polygons;
  29818. };
  29819. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  29820. // new polygons are filtered down to the bottom of the tree and become new
  29821. // nodes there. Each set of polygons is partitioned using the first polygon
  29822. // (no heuristic is used to pick a good split).
  29823. Node.prototype.build = function (polygons) {
  29824. if (!polygons.length)
  29825. return;
  29826. if (!this.plane)
  29827. this.plane = polygons[0].plane.clone();
  29828. var front = [], back = [];
  29829. for (var i = 0; i < polygons.length; i++) {
  29830. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  29831. }
  29832. if (front.length) {
  29833. if (!this.front)
  29834. this.front = new Node();
  29835. this.front.build(front);
  29836. }
  29837. if (back.length) {
  29838. if (!this.back)
  29839. this.back = new Node();
  29840. this.back.build(back);
  29841. }
  29842. };
  29843. return Node;
  29844. })();
  29845. var CSG = (function () {
  29846. function CSG() {
  29847. this.polygons = new Array();
  29848. }
  29849. // Convert BABYLON.Mesh to BABYLON.CSG
  29850. CSG.FromMesh = function (mesh) {
  29851. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  29852. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  29853. if (mesh instanceof BABYLON.Mesh) {
  29854. mesh.computeWorldMatrix(true);
  29855. matrix = mesh.getWorldMatrix();
  29856. meshPosition = mesh.position.clone();
  29857. meshRotation = mesh.rotation.clone();
  29858. if (mesh.rotationQuaternion) {
  29859. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  29860. }
  29861. meshScaling = mesh.scaling.clone();
  29862. }
  29863. else {
  29864. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  29865. }
  29866. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  29867. var subMeshes = mesh.subMeshes;
  29868. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  29869. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  29870. vertices = [];
  29871. for (var j = 0; j < 3; j++) {
  29872. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  29873. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  29874. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  29875. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  29876. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  29877. vertex = new Vertex(position, normal, uv);
  29878. vertices.push(vertex);
  29879. }
  29880. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  29881. // To handle the case of degenerated triangle
  29882. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  29883. if (polygon.plane)
  29884. polygons.push(polygon);
  29885. }
  29886. }
  29887. var csg = CSG.FromPolygons(polygons);
  29888. csg.matrix = matrix;
  29889. csg.position = meshPosition;
  29890. csg.rotation = meshRotation;
  29891. csg.scaling = meshScaling;
  29892. csg.rotationQuaternion = meshRotationQuaternion;
  29893. currentCSGMeshId++;
  29894. return csg;
  29895. };
  29896. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  29897. CSG.FromPolygons = function (polygons) {
  29898. var csg = new CSG();
  29899. csg.polygons = polygons;
  29900. return csg;
  29901. };
  29902. CSG.prototype.clone = function () {
  29903. var csg = new CSG();
  29904. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  29905. csg.copyTransformAttributes(this);
  29906. return csg;
  29907. };
  29908. CSG.prototype.toPolygons = function () {
  29909. return this.polygons;
  29910. };
  29911. CSG.prototype.union = function (csg) {
  29912. var a = new Node(this.clone().polygons);
  29913. var b = new Node(csg.clone().polygons);
  29914. a.clipTo(b);
  29915. b.clipTo(a);
  29916. b.invert();
  29917. b.clipTo(a);
  29918. b.invert();
  29919. a.build(b.allPolygons());
  29920. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  29921. };
  29922. CSG.prototype.unionInPlace = function (csg) {
  29923. var a = new Node(this.polygons);
  29924. var b = new Node(csg.polygons);
  29925. a.clipTo(b);
  29926. b.clipTo(a);
  29927. b.invert();
  29928. b.clipTo(a);
  29929. b.invert();
  29930. a.build(b.allPolygons());
  29931. this.polygons = a.allPolygons();
  29932. };
  29933. CSG.prototype.subtract = function (csg) {
  29934. var a = new Node(this.clone().polygons);
  29935. var b = new Node(csg.clone().polygons);
  29936. a.invert();
  29937. a.clipTo(b);
  29938. b.clipTo(a);
  29939. b.invert();
  29940. b.clipTo(a);
  29941. b.invert();
  29942. a.build(b.allPolygons());
  29943. a.invert();
  29944. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  29945. };
  29946. CSG.prototype.subtractInPlace = function (csg) {
  29947. var a = new Node(this.polygons);
  29948. var b = new Node(csg.polygons);
  29949. a.invert();
  29950. a.clipTo(b);
  29951. b.clipTo(a);
  29952. b.invert();
  29953. b.clipTo(a);
  29954. b.invert();
  29955. a.build(b.allPolygons());
  29956. a.invert();
  29957. this.polygons = a.allPolygons();
  29958. };
  29959. CSG.prototype.intersect = function (csg) {
  29960. var a = new Node(this.clone().polygons);
  29961. var b = new Node(csg.clone().polygons);
  29962. a.invert();
  29963. b.clipTo(a);
  29964. b.invert();
  29965. a.clipTo(b);
  29966. b.clipTo(a);
  29967. a.build(b.allPolygons());
  29968. a.invert();
  29969. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  29970. };
  29971. CSG.prototype.intersectInPlace = function (csg) {
  29972. var a = new Node(this.polygons);
  29973. var b = new Node(csg.polygons);
  29974. a.invert();
  29975. b.clipTo(a);
  29976. b.invert();
  29977. a.clipTo(b);
  29978. b.clipTo(a);
  29979. a.build(b.allPolygons());
  29980. a.invert();
  29981. this.polygons = a.allPolygons();
  29982. };
  29983. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  29984. // not modified.
  29985. CSG.prototype.inverse = function () {
  29986. var csg = this.clone();
  29987. csg.inverseInPlace();
  29988. return csg;
  29989. };
  29990. CSG.prototype.inverseInPlace = function () {
  29991. this.polygons.map(function (p) { p.flip(); });
  29992. };
  29993. // This is used to keep meshes transformations so they can be restored
  29994. // when we build back a Babylon Mesh
  29995. // NB : All CSG operations are performed in world coordinates
  29996. CSG.prototype.copyTransformAttributes = function (csg) {
  29997. this.matrix = csg.matrix;
  29998. this.position = csg.position;
  29999. this.rotation = csg.rotation;
  30000. this.scaling = csg.scaling;
  30001. this.rotationQuaternion = csg.rotationQuaternion;
  30002. return this;
  30003. };
  30004. // Build Raw mesh from CSG
  30005. // Coordinates here are in world space
  30006. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  30007. var matrix = this.matrix.clone();
  30008. matrix.invert();
  30009. 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;
  30010. if (keepSubMeshes) {
  30011. // Sort Polygons, since subMeshes are indices range
  30012. polygons.sort(function (a, b) {
  30013. if (a.shared.meshId === b.shared.meshId) {
  30014. return a.shared.subMeshId - b.shared.subMeshId;
  30015. }
  30016. else {
  30017. return a.shared.meshId - b.shared.meshId;
  30018. }
  30019. });
  30020. }
  30021. for (var i = 0, il = polygons.length; i < il; i++) {
  30022. polygon = polygons[i];
  30023. // Building SubMeshes
  30024. if (!subMesh_dict[polygon.shared.meshId]) {
  30025. subMesh_dict[polygon.shared.meshId] = {};
  30026. }
  30027. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  30028. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  30029. indexStart: +Infinity,
  30030. indexEnd: -Infinity,
  30031. materialIndex: polygon.shared.materialIndex
  30032. };
  30033. }
  30034. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  30035. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  30036. polygonIndices[0] = 0;
  30037. polygonIndices[1] = j - 1;
  30038. polygonIndices[2] = j;
  30039. for (var k = 0; k < 3; k++) {
  30040. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  30041. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  30042. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  30043. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  30044. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  30045. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  30046. // Check if 2 points can be merged
  30047. if (!(typeof vertex_idx !== 'undefined' &&
  30048. normals[vertex_idx * 3] === localNormal.x &&
  30049. normals[vertex_idx * 3 + 1] === localNormal.y &&
  30050. normals[vertex_idx * 3 + 2] === localNormal.z &&
  30051. uvs[vertex_idx * 2] === uv.x &&
  30052. uvs[vertex_idx * 2 + 1] === uv.y)) {
  30053. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  30054. uvs.push(uv.x, uv.y);
  30055. normals.push(normal.x, normal.y, normal.z);
  30056. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  30057. }
  30058. indices.push(vertex_idx);
  30059. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  30060. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  30061. currentIndex++;
  30062. }
  30063. }
  30064. }
  30065. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  30066. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  30067. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  30068. mesh.setIndices(indices);
  30069. if (keepSubMeshes) {
  30070. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  30071. var materialIndexOffset = 0, materialMaxIndex;
  30072. mesh.subMeshes = new Array();
  30073. for (var m in subMesh_dict) {
  30074. materialMaxIndex = -1;
  30075. for (var sm in subMesh_dict[m]) {
  30076. subMesh_obj = subMesh_dict[m][sm];
  30077. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  30078. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  30079. }
  30080. materialIndexOffset += ++materialMaxIndex;
  30081. }
  30082. }
  30083. return mesh;
  30084. };
  30085. // Build Mesh from CSG taking material and transforms into account
  30086. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  30087. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  30088. mesh.material = material;
  30089. mesh.position.copyFrom(this.position);
  30090. mesh.rotation.copyFrom(this.rotation);
  30091. if (this.rotationQuaternion) {
  30092. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  30093. }
  30094. mesh.scaling.copyFrom(this.scaling);
  30095. mesh.computeWorldMatrix(true);
  30096. return mesh;
  30097. };
  30098. return CSG;
  30099. })();
  30100. BABYLON.CSG = CSG;
  30101. })(BABYLON || (BABYLON = {}));
  30102. var BABYLON;
  30103. (function (BABYLON) {
  30104. var VRDistortionCorrectionPostProcess = (function (_super) {
  30105. __extends(VRDistortionCorrectionPostProcess, _super);
  30106. //ANY
  30107. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  30108. var _this = this;
  30109. _super.call(this, name, "vrDistortionCorrection", [
  30110. 'LensCenter',
  30111. 'Scale',
  30112. 'ScaleIn',
  30113. 'HmdWarpParam'
  30114. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  30115. this._isRightEye = isRightEye;
  30116. this._distortionFactors = vrMetrics.distortionK;
  30117. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  30118. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  30119. this.onSizeChanged = function () {
  30120. _this.aspectRatio = _this.width * .5 / _this.height;
  30121. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  30122. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  30123. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  30124. };
  30125. this.onApply = function (effect) {
  30126. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  30127. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  30128. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  30129. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  30130. };
  30131. }
  30132. return VRDistortionCorrectionPostProcess;
  30133. })(BABYLON.PostProcess);
  30134. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  30135. })(BABYLON || (BABYLON = {}));
  30136. // Mainly based on these 2 articles :
  30137. // 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
  30138. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  30139. var BABYLON;
  30140. (function (BABYLON) {
  30141. (function (JoystickAxis) {
  30142. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  30143. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  30144. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  30145. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  30146. var JoystickAxis = BABYLON.JoystickAxis;
  30147. var VirtualJoystick = (function () {
  30148. function VirtualJoystick(leftJoystick) {
  30149. var _this = this;
  30150. if (leftJoystick) {
  30151. this._leftJoystick = true;
  30152. }
  30153. else {
  30154. this._leftJoystick = false;
  30155. }
  30156. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  30157. VirtualJoystick._globalJoystickIndex++;
  30158. // By default left & right arrow keys are moving the X
  30159. // and up & down keys are moving the Y
  30160. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  30161. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  30162. this.reverseLeftRight = false;
  30163. this.reverseUpDown = false;
  30164. // collections of pointers
  30165. this._touches = new BABYLON.SmartCollection();
  30166. this.deltaPosition = BABYLON.Vector3.Zero();
  30167. this._joystickSensibility = 25;
  30168. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  30169. this._rotationSpeed = 25;
  30170. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  30171. this._rotateOnAxisRelativeToMesh = false;
  30172. this._onResize = function (evt) {
  30173. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  30174. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  30175. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  30176. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  30177. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  30178. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  30179. };
  30180. // injecting a canvas element on top of the canvas 3D game
  30181. if (!VirtualJoystick.vjCanvas) {
  30182. window.addEventListener("resize", this._onResize, false);
  30183. VirtualJoystick.vjCanvas = document.createElement("canvas");
  30184. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  30185. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  30186. VirtualJoystick.vjCanvas.width = window.innerWidth;
  30187. VirtualJoystick.vjCanvas.height = window.innerHeight;
  30188. VirtualJoystick.vjCanvas.style.width = "100%";
  30189. VirtualJoystick.vjCanvas.style.height = "100%";
  30190. VirtualJoystick.vjCanvas.style.position = "absolute";
  30191. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  30192. VirtualJoystick.vjCanvas.style.top = "0px";
  30193. VirtualJoystick.vjCanvas.style.left = "0px";
  30194. VirtualJoystick.vjCanvas.style.zIndex = "5";
  30195. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  30196. // Support for jQuery PEP polyfill
  30197. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  30198. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  30199. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  30200. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  30201. document.body.appendChild(VirtualJoystick.vjCanvas);
  30202. }
  30203. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  30204. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  30205. this.pressed = false;
  30206. // default joystick color
  30207. this._joystickColor = "cyan";
  30208. this._joystickPointerID = -1;
  30209. // current joystick position
  30210. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  30211. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  30212. // origin joystick position
  30213. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  30214. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  30215. this._onPointerDownHandlerRef = function (evt) {
  30216. _this._onPointerDown(evt);
  30217. };
  30218. this._onPointerMoveHandlerRef = function (evt) {
  30219. _this._onPointerMove(evt);
  30220. };
  30221. this._onPointerOutHandlerRef = function (evt) {
  30222. _this._onPointerUp(evt);
  30223. };
  30224. this._onPointerUpHandlerRef = function (evt) {
  30225. _this._onPointerUp(evt);
  30226. };
  30227. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  30228. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  30229. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  30230. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  30231. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  30232. evt.preventDefault(); // Disables system menu
  30233. }, false);
  30234. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  30235. }
  30236. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  30237. this._joystickSensibility = newJoystickSensibility;
  30238. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  30239. };
  30240. VirtualJoystick.prototype._onPointerDown = function (e) {
  30241. var positionOnScreenCondition;
  30242. e.preventDefault();
  30243. if (this._leftJoystick === true) {
  30244. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  30245. }
  30246. else {
  30247. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  30248. }
  30249. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  30250. // First contact will be dedicated to the virtual joystick
  30251. this._joystickPointerID = e.pointerId;
  30252. this._joystickPointerStartPos.x = e.clientX;
  30253. this._joystickPointerStartPos.y = e.clientY;
  30254. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  30255. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  30256. this._deltaJoystickVector.x = 0;
  30257. this._deltaJoystickVector.y = 0;
  30258. this.pressed = true;
  30259. this._touches.add(e.pointerId.toString(), e);
  30260. }
  30261. else {
  30262. // You can only trigger the action buttons with a joystick declared
  30263. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  30264. this._action();
  30265. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  30266. }
  30267. }
  30268. };
  30269. VirtualJoystick.prototype._onPointerMove = function (e) {
  30270. // If the current pointer is the one associated to the joystick (first touch contact)
  30271. if (this._joystickPointerID == e.pointerId) {
  30272. this._joystickPointerPos.x = e.clientX;
  30273. this._joystickPointerPos.y = e.clientY;
  30274. this._deltaJoystickVector = this._joystickPointerPos.clone();
  30275. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  30276. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  30277. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  30278. switch (this._axisTargetedByLeftAndRight) {
  30279. case JoystickAxis.X:
  30280. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  30281. break;
  30282. case JoystickAxis.Y:
  30283. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  30284. break;
  30285. case JoystickAxis.Z:
  30286. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  30287. break;
  30288. }
  30289. var directionUpDown = this.reverseUpDown ? 1 : -1;
  30290. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  30291. switch (this._axisTargetedByUpAndDown) {
  30292. case JoystickAxis.X:
  30293. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  30294. break;
  30295. case JoystickAxis.Y:
  30296. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  30297. break;
  30298. case JoystickAxis.Z:
  30299. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  30300. break;
  30301. }
  30302. }
  30303. else {
  30304. if (this._touches.item(e.pointerId.toString())) {
  30305. this._touches.item(e.pointerId.toString()).x = e.clientX;
  30306. this._touches.item(e.pointerId.toString()).y = e.clientY;
  30307. }
  30308. }
  30309. };
  30310. VirtualJoystick.prototype._onPointerUp = function (e) {
  30311. if (this._joystickPointerID == e.pointerId) {
  30312. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  30313. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  30314. this._joystickPointerID = -1;
  30315. this.pressed = false;
  30316. }
  30317. else {
  30318. var touch = this._touches.item(e.pointerId.toString());
  30319. if (touch) {
  30320. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  30321. }
  30322. }
  30323. this._deltaJoystickVector.x = 0;
  30324. this._deltaJoystickVector.y = 0;
  30325. this._touches.remove(e.pointerId.toString());
  30326. };
  30327. /**
  30328. * Change the color of the virtual joystick
  30329. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  30330. */
  30331. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  30332. this._joystickColor = newColor;
  30333. };
  30334. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  30335. this._action = action;
  30336. };
  30337. // Define which axis you'd like to control for left & right
  30338. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  30339. switch (axis) {
  30340. case JoystickAxis.X:
  30341. case JoystickAxis.Y:
  30342. case JoystickAxis.Z:
  30343. this._axisTargetedByLeftAndRight = axis;
  30344. break;
  30345. default:
  30346. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  30347. break;
  30348. }
  30349. };
  30350. // Define which axis you'd like to control for up & down
  30351. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  30352. switch (axis) {
  30353. case JoystickAxis.X:
  30354. case JoystickAxis.Y:
  30355. case JoystickAxis.Z:
  30356. this._axisTargetedByUpAndDown = axis;
  30357. break;
  30358. default:
  30359. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  30360. break;
  30361. }
  30362. };
  30363. VirtualJoystick.prototype._clearCanvas = function () {
  30364. if (this._leftJoystick) {
  30365. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  30366. }
  30367. else {
  30368. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  30369. }
  30370. };
  30371. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  30372. var _this = this;
  30373. if (this.pressed) {
  30374. this._touches.forEach(function (touch) {
  30375. if (touch.pointerId === _this._joystickPointerID) {
  30376. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  30377. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  30378. VirtualJoystick.vjCanvasContext.beginPath();
  30379. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  30380. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  30381. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  30382. VirtualJoystick.vjCanvasContext.stroke();
  30383. VirtualJoystick.vjCanvasContext.closePath();
  30384. VirtualJoystick.vjCanvasContext.beginPath();
  30385. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  30386. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  30387. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  30388. VirtualJoystick.vjCanvasContext.stroke();
  30389. VirtualJoystick.vjCanvasContext.closePath();
  30390. VirtualJoystick.vjCanvasContext.beginPath();
  30391. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  30392. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  30393. VirtualJoystick.vjCanvasContext.stroke();
  30394. VirtualJoystick.vjCanvasContext.closePath();
  30395. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  30396. }
  30397. else {
  30398. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  30399. VirtualJoystick.vjCanvasContext.beginPath();
  30400. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  30401. VirtualJoystick.vjCanvasContext.beginPath();
  30402. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  30403. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  30404. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  30405. VirtualJoystick.vjCanvasContext.stroke();
  30406. VirtualJoystick.vjCanvasContext.closePath();
  30407. touch.prevX = touch.x;
  30408. touch.prevY = touch.y;
  30409. }
  30410. ;
  30411. });
  30412. }
  30413. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  30414. };
  30415. VirtualJoystick.prototype.releaseCanvas = function () {
  30416. if (VirtualJoystick.vjCanvas) {
  30417. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  30418. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  30419. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  30420. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  30421. window.removeEventListener("resize", this._onResize);
  30422. document.body.removeChild(VirtualJoystick.vjCanvas);
  30423. VirtualJoystick.vjCanvas = null;
  30424. }
  30425. };
  30426. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  30427. VirtualJoystick._globalJoystickIndex = 0;
  30428. return VirtualJoystick;
  30429. })();
  30430. BABYLON.VirtualJoystick = VirtualJoystick;
  30431. })(BABYLON || (BABYLON = {}));
  30432. var BABYLON;
  30433. (function (BABYLON) {
  30434. // We're mainly based on the logic defined into the FreeCamera code
  30435. var VirtualJoysticksCamera = (function (_super) {
  30436. __extends(VirtualJoysticksCamera, _super);
  30437. function VirtualJoysticksCamera(name, position, scene) {
  30438. _super.call(this, name, position, scene);
  30439. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  30440. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  30441. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  30442. this._leftjoystick.setJoystickSensibility(0.15);
  30443. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  30444. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  30445. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  30446. this._rightjoystick.reverseUpDown = true;
  30447. this._rightjoystick.setJoystickSensibility(0.05);
  30448. this._rightjoystick.setJoystickColor("yellow");
  30449. }
  30450. VirtualJoysticksCamera.prototype.getLeftJoystick = function () {
  30451. return this._leftjoystick;
  30452. };
  30453. VirtualJoysticksCamera.prototype.getRightJoystick = function () {
  30454. return this._rightjoystick;
  30455. };
  30456. VirtualJoysticksCamera.prototype._checkInputs = function () {
  30457. var speed = this._computeLocalCameraSpeed() * 50;
  30458. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  30459. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  30460. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  30461. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  30462. if (!this._leftjoystick.pressed) {
  30463. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  30464. }
  30465. if (!this._rightjoystick.pressed) {
  30466. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  30467. }
  30468. _super.prototype._checkInputs.call(this);
  30469. };
  30470. VirtualJoysticksCamera.prototype.dispose = function () {
  30471. this._leftjoystick.releaseCanvas();
  30472. _super.prototype.dispose.call(this);
  30473. };
  30474. return VirtualJoysticksCamera;
  30475. })(BABYLON.FreeCamera);
  30476. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  30477. })(BABYLON || (BABYLON = {}));
  30478. var BABYLON;
  30479. (function (BABYLON) {
  30480. var AnaglyphPostProcess = (function (_super) {
  30481. __extends(AnaglyphPostProcess, _super);
  30482. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  30483. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  30484. }
  30485. return AnaglyphPostProcess;
  30486. })(BABYLON.PostProcess);
  30487. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  30488. })(BABYLON || (BABYLON = {}));
  30489. var BABYLON;
  30490. (function (BABYLON) {
  30491. var OutlineRenderer = (function () {
  30492. function OutlineRenderer(scene) {
  30493. this._scene = scene;
  30494. }
  30495. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  30496. var _this = this;
  30497. if (useOverlay === void 0) { useOverlay = false; }
  30498. var scene = this._scene;
  30499. var engine = this._scene.getEngine();
  30500. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  30501. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  30502. return;
  30503. }
  30504. var mesh = subMesh.getRenderingMesh();
  30505. var material = subMesh.getMaterial();
  30506. engine.enableEffect(this._effect);
  30507. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  30508. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  30509. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  30510. // Bones
  30511. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  30512. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  30513. }
  30514. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  30515. // Alpha test
  30516. if (material && material.needAlphaTesting()) {
  30517. var alphaTexture = material.getAlphaTestTexture();
  30518. this._effect.setTexture("diffuseSampler", alphaTexture);
  30519. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  30520. }
  30521. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  30522. };
  30523. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  30524. var defines = [];
  30525. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  30526. var mesh = subMesh.getMesh();
  30527. var material = subMesh.getMaterial();
  30528. // Alpha test
  30529. if (material && material.needAlphaTesting()) {
  30530. defines.push("#define ALPHATEST");
  30531. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  30532. attribs.push(BABYLON.VertexBuffer.UVKind);
  30533. defines.push("#define UV1");
  30534. }
  30535. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  30536. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  30537. defines.push("#define UV2");
  30538. }
  30539. }
  30540. // Bones
  30541. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  30542. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  30543. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  30544. defines.push("#define BONES");
  30545. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  30546. }
  30547. // Instances
  30548. if (useInstances) {
  30549. defines.push("#define INSTANCES");
  30550. attribs.push("world0");
  30551. attribs.push("world1");
  30552. attribs.push("world2");
  30553. attribs.push("world3");
  30554. }
  30555. // Get correct effect
  30556. var join = defines.join("\n");
  30557. if (this._cachedDefines !== join) {
  30558. this._cachedDefines = join;
  30559. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  30560. }
  30561. return this._effect.isReady();
  30562. };
  30563. return OutlineRenderer;
  30564. })();
  30565. BABYLON.OutlineRenderer = OutlineRenderer;
  30566. })(BABYLON || (BABYLON = {}));
  30567. var BABYLON;
  30568. (function (BABYLON) {
  30569. var MeshAssetTask = (function () {
  30570. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  30571. this.name = name;
  30572. this.meshesNames = meshesNames;
  30573. this.rootUrl = rootUrl;
  30574. this.sceneFilename = sceneFilename;
  30575. this.isCompleted = false;
  30576. }
  30577. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  30578. var _this = this;
  30579. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  30580. _this.loadedMeshes = meshes;
  30581. _this.loadedParticleSystems = particleSystems;
  30582. _this.loadedSkeletons = skeletons;
  30583. _this.isCompleted = true;
  30584. if (_this.onSuccess) {
  30585. _this.onSuccess(_this);
  30586. }
  30587. onSuccess();
  30588. }, null, function () {
  30589. if (_this.onError) {
  30590. _this.onError(_this);
  30591. }
  30592. onError();
  30593. });
  30594. };
  30595. return MeshAssetTask;
  30596. })();
  30597. BABYLON.MeshAssetTask = MeshAssetTask;
  30598. var TextFileAssetTask = (function () {
  30599. function TextFileAssetTask(name, url) {
  30600. this.name = name;
  30601. this.url = url;
  30602. this.isCompleted = false;
  30603. }
  30604. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  30605. var _this = this;
  30606. BABYLON.Tools.LoadFile(this.url, function (data) {
  30607. _this.text = data;
  30608. _this.isCompleted = true;
  30609. if (_this.onSuccess) {
  30610. _this.onSuccess(_this);
  30611. }
  30612. onSuccess();
  30613. }, null, scene.database, false, function () {
  30614. if (_this.onError) {
  30615. _this.onError(_this);
  30616. }
  30617. onError();
  30618. });
  30619. };
  30620. return TextFileAssetTask;
  30621. })();
  30622. BABYLON.TextFileAssetTask = TextFileAssetTask;
  30623. var BinaryFileAssetTask = (function () {
  30624. function BinaryFileAssetTask(name, url) {
  30625. this.name = name;
  30626. this.url = url;
  30627. this.isCompleted = false;
  30628. }
  30629. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  30630. var _this = this;
  30631. BABYLON.Tools.LoadFile(this.url, function (data) {
  30632. _this.data = data;
  30633. _this.isCompleted = true;
  30634. if (_this.onSuccess) {
  30635. _this.onSuccess(_this);
  30636. }
  30637. onSuccess();
  30638. }, null, scene.database, true, function () {
  30639. if (_this.onError) {
  30640. _this.onError(_this);
  30641. }
  30642. onError();
  30643. });
  30644. };
  30645. return BinaryFileAssetTask;
  30646. })();
  30647. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  30648. var ImageAssetTask = (function () {
  30649. function ImageAssetTask(name, url) {
  30650. this.name = name;
  30651. this.url = url;
  30652. this.isCompleted = false;
  30653. }
  30654. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  30655. var _this = this;
  30656. var img = new Image();
  30657. img.onload = function () {
  30658. _this.image = img;
  30659. _this.isCompleted = true;
  30660. if (_this.onSuccess) {
  30661. _this.onSuccess(_this);
  30662. }
  30663. onSuccess();
  30664. };
  30665. img.onerror = function () {
  30666. if (_this.onError) {
  30667. _this.onError(_this);
  30668. }
  30669. onError();
  30670. };
  30671. img.src = this.url;
  30672. };
  30673. return ImageAssetTask;
  30674. })();
  30675. BABYLON.ImageAssetTask = ImageAssetTask;
  30676. var TextureAssetTask = (function () {
  30677. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  30678. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  30679. this.name = name;
  30680. this.url = url;
  30681. this.noMipmap = noMipmap;
  30682. this.invertY = invertY;
  30683. this.samplingMode = samplingMode;
  30684. this.isCompleted = false;
  30685. }
  30686. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  30687. var _this = this;
  30688. var onload = function () {
  30689. _this.isCompleted = true;
  30690. if (_this.onSuccess) {
  30691. _this.onSuccess(_this);
  30692. }
  30693. onSuccess();
  30694. };
  30695. var onerror = function () {
  30696. if (_this.onError) {
  30697. _this.onError(_this);
  30698. }
  30699. onError();
  30700. };
  30701. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  30702. };
  30703. return TextureAssetTask;
  30704. })();
  30705. BABYLON.TextureAssetTask = TextureAssetTask;
  30706. var AssetsManager = (function () {
  30707. function AssetsManager(scene) {
  30708. this._tasks = new Array();
  30709. this._waitingTasksCount = 0;
  30710. this.useDefaultLoadingScreen = true;
  30711. this._scene = scene;
  30712. }
  30713. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  30714. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  30715. this._tasks.push(task);
  30716. return task;
  30717. };
  30718. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  30719. var task = new TextFileAssetTask(taskName, url);
  30720. this._tasks.push(task);
  30721. return task;
  30722. };
  30723. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  30724. var task = new BinaryFileAssetTask(taskName, url);
  30725. this._tasks.push(task);
  30726. return task;
  30727. };
  30728. AssetsManager.prototype.addImageTask = function (taskName, url) {
  30729. var task = new ImageAssetTask(taskName, url);
  30730. this._tasks.push(task);
  30731. return task;
  30732. };
  30733. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  30734. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  30735. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  30736. this._tasks.push(task);
  30737. return task;
  30738. };
  30739. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  30740. this._waitingTasksCount--;
  30741. if (this._waitingTasksCount === 0) {
  30742. if (this.onFinish) {
  30743. this.onFinish(this._tasks);
  30744. }
  30745. this._scene.getEngine().hideLoadingUI();
  30746. }
  30747. };
  30748. AssetsManager.prototype._runTask = function (task) {
  30749. var _this = this;
  30750. task.run(this._scene, function () {
  30751. if (_this.onTaskSuccess) {
  30752. _this.onTaskSuccess(task);
  30753. }
  30754. _this._decreaseWaitingTasksCount();
  30755. }, function () {
  30756. if (_this.onTaskError) {
  30757. _this.onTaskError(task);
  30758. }
  30759. _this._decreaseWaitingTasksCount();
  30760. });
  30761. };
  30762. AssetsManager.prototype.reset = function () {
  30763. this._tasks = new Array();
  30764. return this;
  30765. };
  30766. AssetsManager.prototype.load = function () {
  30767. this._waitingTasksCount = this._tasks.length;
  30768. if (this._waitingTasksCount === 0) {
  30769. if (this.onFinish) {
  30770. this.onFinish(this._tasks);
  30771. }
  30772. return this;
  30773. }
  30774. if (this.useDefaultLoadingScreen) {
  30775. this._scene.getEngine().displayLoadingUI();
  30776. }
  30777. for (var index = 0; index < this._tasks.length; index++) {
  30778. var task = this._tasks[index];
  30779. this._runTask(task);
  30780. }
  30781. return this;
  30782. };
  30783. return AssetsManager;
  30784. })();
  30785. BABYLON.AssetsManager = AssetsManager;
  30786. })(BABYLON || (BABYLON = {}));
  30787. var BABYLON;
  30788. (function (BABYLON) {
  30789. var VRDeviceOrientationFreeCamera = (function (_super) {
  30790. __extends(VRDeviceOrientationFreeCamera, _super);
  30791. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion) {
  30792. if (compensateDistortion === void 0) { compensateDistortion = true; }
  30793. _super.call(this, name, position, scene);
  30794. this._alpha = 0;
  30795. this._beta = 0;
  30796. this._gamma = 0;
  30797. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  30798. metrics.compensateDistortion = compensateDistortion;
  30799. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  30800. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  30801. }
  30802. VRDeviceOrientationFreeCamera.prototype._onOrientationEvent = function (evt) {
  30803. this._alpha = +evt.alpha | 0;
  30804. this._beta = +evt.beta | 0;
  30805. this._gamma = +evt.gamma | 0;
  30806. if (this._gamma < 0) {
  30807. this._gamma = 90 + this._gamma;
  30808. }
  30809. else {
  30810. // Incline it in the correct angle.
  30811. this._gamma = 270 - this._gamma;
  30812. }
  30813. this.rotation.x = this._gamma / 180.0 * Math.PI;
  30814. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  30815. this.rotation.z = this._beta / 180.0 * Math.PI;
  30816. };
  30817. VRDeviceOrientationFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  30818. _super.prototype.attachControl.call(this, element, noPreventDefault);
  30819. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  30820. };
  30821. VRDeviceOrientationFreeCamera.prototype.detachControl = function (element) {
  30822. _super.prototype.detachControl.call(this, element);
  30823. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  30824. };
  30825. return VRDeviceOrientationFreeCamera;
  30826. })(BABYLON.FreeCamera);
  30827. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  30828. })(BABYLON || (BABYLON = {}));
  30829. var BABYLON;
  30830. (function (BABYLON) {
  30831. var WebVRFreeCamera = (function (_super) {
  30832. __extends(WebVRFreeCamera, _super);
  30833. function WebVRFreeCamera(name, position, scene, compensateDistortion) {
  30834. if (compensateDistortion === void 0) { compensateDistortion = true; }
  30835. _super.call(this, name, position, scene);
  30836. this._hmdDevice = null;
  30837. this._sensorDevice = null;
  30838. this._cacheState = null;
  30839. this._cacheQuaternion = new BABYLON.Quaternion();
  30840. this._cacheRotation = BABYLON.Vector3.Zero();
  30841. this._vrEnabled = false;
  30842. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  30843. metrics.compensateDistortion = compensateDistortion;
  30844. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  30845. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  30846. }
  30847. WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
  30848. var size = devices.length;
  30849. var i = 0;
  30850. // Reset devices.
  30851. this._sensorDevice = null;
  30852. this._hmdDevice = null;
  30853. // Search for a HmdDevice.
  30854. while (i < size && this._hmdDevice === null) {
  30855. if (devices[i] instanceof HMDVRDevice) {
  30856. this._hmdDevice = devices[i];
  30857. }
  30858. i++;
  30859. }
  30860. i = 0;
  30861. while (i < size && this._sensorDevice === null) {
  30862. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  30863. this._sensorDevice = devices[i];
  30864. }
  30865. i++;
  30866. }
  30867. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  30868. };
  30869. WebVRFreeCamera.prototype._checkInputs = function () {
  30870. if (this._vrEnabled) {
  30871. this._cacheState = this._sensorDevice.getState();
  30872. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  30873. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  30874. this.rotation.x = -this._cacheRotation.z;
  30875. this.rotation.y = -this._cacheRotation.y;
  30876. this.rotation.z = this._cacheRotation.x;
  30877. }
  30878. _super.prototype._checkInputs.call(this);
  30879. };
  30880. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  30881. _super.prototype.attachControl.call(this, element, noPreventDefault);
  30882. if (navigator.getVRDevices) {
  30883. navigator.getVRDevices().then(this._getWebVRDevices);
  30884. }
  30885. else if (navigator.mozGetVRDevices) {
  30886. navigator.mozGetVRDevices(this._getWebVRDevices);
  30887. }
  30888. };
  30889. WebVRFreeCamera.prototype.detachControl = function (element) {
  30890. _super.prototype.detachControl.call(this, element);
  30891. this._vrEnabled = false;
  30892. };
  30893. return WebVRFreeCamera;
  30894. })(BABYLON.FreeCamera);
  30895. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  30896. })(BABYLON || (BABYLON = {}));
  30897. var BABYLON;
  30898. (function (BABYLON) {
  30899. // Standard optimizations
  30900. var SceneOptimization = (function () {
  30901. function SceneOptimization(priority) {
  30902. if (priority === void 0) { priority = 0; }
  30903. this.priority = priority;
  30904. this.apply = function (scene) {
  30905. return true; // Return true if everything that can be done was applied
  30906. };
  30907. }
  30908. return SceneOptimization;
  30909. })();
  30910. BABYLON.SceneOptimization = SceneOptimization;
  30911. var TextureOptimization = (function (_super) {
  30912. __extends(TextureOptimization, _super);
  30913. function TextureOptimization(priority, maximumSize) {
  30914. var _this = this;
  30915. if (priority === void 0) { priority = 0; }
  30916. if (maximumSize === void 0) { maximumSize = 1024; }
  30917. _super.call(this, priority);
  30918. this.priority = priority;
  30919. this.maximumSize = maximumSize;
  30920. this.apply = function (scene) {
  30921. var allDone = true;
  30922. for (var index = 0; index < scene.textures.length; index++) {
  30923. var texture = scene.textures[index];
  30924. if (!texture.canRescale) {
  30925. continue;
  30926. }
  30927. var currentSize = texture.getSize();
  30928. var maxDimension = Math.max(currentSize.width, currentSize.height);
  30929. if (maxDimension > _this.maximumSize) {
  30930. texture.scale(0.5);
  30931. allDone = false;
  30932. }
  30933. }
  30934. return allDone;
  30935. };
  30936. }
  30937. return TextureOptimization;
  30938. })(SceneOptimization);
  30939. BABYLON.TextureOptimization = TextureOptimization;
  30940. var HardwareScalingOptimization = (function (_super) {
  30941. __extends(HardwareScalingOptimization, _super);
  30942. function HardwareScalingOptimization(priority, maximumScale) {
  30943. var _this = this;
  30944. if (priority === void 0) { priority = 0; }
  30945. if (maximumScale === void 0) { maximumScale = 2; }
  30946. _super.call(this, priority);
  30947. this.priority = priority;
  30948. this.maximumScale = maximumScale;
  30949. this._currentScale = 1;
  30950. this.apply = function (scene) {
  30951. _this._currentScale++;
  30952. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  30953. return _this._currentScale >= _this.maximumScale;
  30954. };
  30955. }
  30956. return HardwareScalingOptimization;
  30957. })(SceneOptimization);
  30958. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  30959. var ShadowsOptimization = (function (_super) {
  30960. __extends(ShadowsOptimization, _super);
  30961. function ShadowsOptimization() {
  30962. _super.apply(this, arguments);
  30963. this.apply = function (scene) {
  30964. scene.shadowsEnabled = false;
  30965. return true;
  30966. };
  30967. }
  30968. return ShadowsOptimization;
  30969. })(SceneOptimization);
  30970. BABYLON.ShadowsOptimization = ShadowsOptimization;
  30971. var PostProcessesOptimization = (function (_super) {
  30972. __extends(PostProcessesOptimization, _super);
  30973. function PostProcessesOptimization() {
  30974. _super.apply(this, arguments);
  30975. this.apply = function (scene) {
  30976. scene.postProcessesEnabled = false;
  30977. return true;
  30978. };
  30979. }
  30980. return PostProcessesOptimization;
  30981. })(SceneOptimization);
  30982. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  30983. var LensFlaresOptimization = (function (_super) {
  30984. __extends(LensFlaresOptimization, _super);
  30985. function LensFlaresOptimization() {
  30986. _super.apply(this, arguments);
  30987. this.apply = function (scene) {
  30988. scene.lensFlaresEnabled = false;
  30989. return true;
  30990. };
  30991. }
  30992. return LensFlaresOptimization;
  30993. })(SceneOptimization);
  30994. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  30995. var ParticlesOptimization = (function (_super) {
  30996. __extends(ParticlesOptimization, _super);
  30997. function ParticlesOptimization() {
  30998. _super.apply(this, arguments);
  30999. this.apply = function (scene) {
  31000. scene.particlesEnabled = false;
  31001. return true;
  31002. };
  31003. }
  31004. return ParticlesOptimization;
  31005. })(SceneOptimization);
  31006. BABYLON.ParticlesOptimization = ParticlesOptimization;
  31007. var RenderTargetsOptimization = (function (_super) {
  31008. __extends(RenderTargetsOptimization, _super);
  31009. function RenderTargetsOptimization() {
  31010. _super.apply(this, arguments);
  31011. this.apply = function (scene) {
  31012. scene.renderTargetsEnabled = false;
  31013. return true;
  31014. };
  31015. }
  31016. return RenderTargetsOptimization;
  31017. })(SceneOptimization);
  31018. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  31019. var MergeMeshesOptimization = (function (_super) {
  31020. __extends(MergeMeshesOptimization, _super);
  31021. function MergeMeshesOptimization() {
  31022. var _this = this;
  31023. _super.apply(this, arguments);
  31024. this._canBeMerged = function (abstractMesh) {
  31025. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  31026. return false;
  31027. }
  31028. var mesh = abstractMesh;
  31029. if (!mesh.isVisible || !mesh.isEnabled()) {
  31030. return false;
  31031. }
  31032. if (mesh.instances.length > 0) {
  31033. return false;
  31034. }
  31035. if (mesh.skeleton || mesh.hasLODLevels) {
  31036. return false;
  31037. }
  31038. return true;
  31039. };
  31040. this.apply = function (scene, updateSelectionTree) {
  31041. var globalPool = scene.meshes.slice(0);
  31042. var globalLength = globalPool.length;
  31043. for (var index = 0; index < globalLength; index++) {
  31044. var currentPool = new Array();
  31045. var current = globalPool[index];
  31046. // Checks
  31047. if (!_this._canBeMerged(current)) {
  31048. continue;
  31049. }
  31050. currentPool.push(current);
  31051. // Find compatible meshes
  31052. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  31053. var otherMesh = globalPool[subIndex];
  31054. if (!_this._canBeMerged(otherMesh)) {
  31055. continue;
  31056. }
  31057. if (otherMesh.material !== current.material) {
  31058. continue;
  31059. }
  31060. if (otherMesh.checkCollisions !== current.checkCollisions) {
  31061. continue;
  31062. }
  31063. currentPool.push(otherMesh);
  31064. globalLength--;
  31065. globalPool.splice(subIndex, 1);
  31066. subIndex--;
  31067. }
  31068. if (currentPool.length < 2) {
  31069. continue;
  31070. }
  31071. // Merge meshes
  31072. BABYLON.Mesh.MergeMeshes(currentPool);
  31073. }
  31074. if (updateSelectionTree != undefined) {
  31075. if (updateSelectionTree) {
  31076. scene.createOrUpdateSelectionOctree();
  31077. }
  31078. }
  31079. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  31080. scene.createOrUpdateSelectionOctree();
  31081. }
  31082. return true;
  31083. };
  31084. }
  31085. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  31086. get: function () {
  31087. return MergeMeshesOptimization._UpdateSelectionTree;
  31088. },
  31089. set: function (value) {
  31090. MergeMeshesOptimization._UpdateSelectionTree = value;
  31091. },
  31092. enumerable: true,
  31093. configurable: true
  31094. });
  31095. MergeMeshesOptimization._UpdateSelectionTree = false;
  31096. return MergeMeshesOptimization;
  31097. })(SceneOptimization);
  31098. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  31099. // Options
  31100. var SceneOptimizerOptions = (function () {
  31101. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  31102. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  31103. if (trackerDuration === void 0) { trackerDuration = 2000; }
  31104. this.targetFrameRate = targetFrameRate;
  31105. this.trackerDuration = trackerDuration;
  31106. this.optimizations = new Array();
  31107. }
  31108. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  31109. var result = new SceneOptimizerOptions(targetFrameRate);
  31110. var priority = 0;
  31111. result.optimizations.push(new MergeMeshesOptimization(priority));
  31112. result.optimizations.push(new ShadowsOptimization(priority));
  31113. result.optimizations.push(new LensFlaresOptimization(priority));
  31114. // Next priority
  31115. priority++;
  31116. result.optimizations.push(new PostProcessesOptimization(priority));
  31117. result.optimizations.push(new ParticlesOptimization(priority));
  31118. // Next priority
  31119. priority++;
  31120. result.optimizations.push(new TextureOptimization(priority, 1024));
  31121. return result;
  31122. };
  31123. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  31124. var result = new SceneOptimizerOptions(targetFrameRate);
  31125. var priority = 0;
  31126. result.optimizations.push(new MergeMeshesOptimization(priority));
  31127. result.optimizations.push(new ShadowsOptimization(priority));
  31128. result.optimizations.push(new LensFlaresOptimization(priority));
  31129. // Next priority
  31130. priority++;
  31131. result.optimizations.push(new PostProcessesOptimization(priority));
  31132. result.optimizations.push(new ParticlesOptimization(priority));
  31133. // Next priority
  31134. priority++;
  31135. result.optimizations.push(new TextureOptimization(priority, 512));
  31136. // Next priority
  31137. priority++;
  31138. result.optimizations.push(new RenderTargetsOptimization(priority));
  31139. // Next priority
  31140. priority++;
  31141. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  31142. return result;
  31143. };
  31144. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  31145. var result = new SceneOptimizerOptions(targetFrameRate);
  31146. var priority = 0;
  31147. result.optimizations.push(new MergeMeshesOptimization(priority));
  31148. result.optimizations.push(new ShadowsOptimization(priority));
  31149. result.optimizations.push(new LensFlaresOptimization(priority));
  31150. // Next priority
  31151. priority++;
  31152. result.optimizations.push(new PostProcessesOptimization(priority));
  31153. result.optimizations.push(new ParticlesOptimization(priority));
  31154. // Next priority
  31155. priority++;
  31156. result.optimizations.push(new TextureOptimization(priority, 256));
  31157. // Next priority
  31158. priority++;
  31159. result.optimizations.push(new RenderTargetsOptimization(priority));
  31160. // Next priority
  31161. priority++;
  31162. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  31163. return result;
  31164. };
  31165. return SceneOptimizerOptions;
  31166. })();
  31167. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  31168. // Scene optimizer tool
  31169. var SceneOptimizer = (function () {
  31170. function SceneOptimizer() {
  31171. }
  31172. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  31173. // TODO: add an epsilon
  31174. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  31175. if (onSuccess) {
  31176. onSuccess();
  31177. }
  31178. return;
  31179. }
  31180. // Apply current level of optimizations
  31181. var allDone = true;
  31182. var noOptimizationApplied = true;
  31183. for (var index = 0; index < options.optimizations.length; index++) {
  31184. var optimization = options.optimizations[index];
  31185. if (optimization.priority === currentPriorityLevel) {
  31186. noOptimizationApplied = false;
  31187. allDone = allDone && optimization.apply(scene);
  31188. }
  31189. }
  31190. // If no optimization was applied, this is a failure :(
  31191. if (noOptimizationApplied) {
  31192. if (onFailure) {
  31193. onFailure();
  31194. }
  31195. return;
  31196. }
  31197. // If all optimizations were done, move to next level
  31198. if (allDone) {
  31199. currentPriorityLevel++;
  31200. }
  31201. // Let's the system running for a specific amount of time before checking FPS
  31202. scene.executeWhenReady(function () {
  31203. setTimeout(function () {
  31204. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  31205. }, options.trackerDuration);
  31206. });
  31207. };
  31208. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  31209. if (!options) {
  31210. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  31211. }
  31212. // Let's the system running for a specific amount of time before checking FPS
  31213. scene.executeWhenReady(function () {
  31214. setTimeout(function () {
  31215. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  31216. }, options.trackerDuration);
  31217. });
  31218. };
  31219. return SceneOptimizer;
  31220. })();
  31221. BABYLON.SceneOptimizer = SceneOptimizer;
  31222. })(BABYLON || (BABYLON = {}));
  31223. var BABYLON;
  31224. (function (BABYLON) {
  31225. var Internals;
  31226. (function (Internals) {
  31227. var MeshLODLevel = (function () {
  31228. function MeshLODLevel(distance, mesh) {
  31229. this.distance = distance;
  31230. this.mesh = mesh;
  31231. }
  31232. return MeshLODLevel;
  31233. })();
  31234. Internals.MeshLODLevel = MeshLODLevel;
  31235. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  31236. })(BABYLON || (BABYLON = {}));
  31237. var BABYLON;
  31238. (function (BABYLON) {
  31239. var RawTexture = (function (_super) {
  31240. __extends(RawTexture, _super);
  31241. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  31242. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31243. if (invertY === void 0) { invertY = false; }
  31244. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31245. _super.call(this, null, scene, !generateMipMaps, invertY);
  31246. this.format = format;
  31247. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  31248. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31249. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31250. }
  31251. RawTexture.prototype.update = function (data) {
  31252. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  31253. };
  31254. // Statics
  31255. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31256. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31257. if (invertY === void 0) { invertY = false; }
  31258. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31259. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  31260. };
  31261. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31262. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31263. if (invertY === void 0) { invertY = false; }
  31264. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31265. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  31266. };
  31267. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31268. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31269. if (invertY === void 0) { invertY = false; }
  31270. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31271. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  31272. };
  31273. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31274. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31275. if (invertY === void 0) { invertY = false; }
  31276. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31277. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  31278. };
  31279. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31280. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31281. if (invertY === void 0) { invertY = false; }
  31282. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31283. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  31284. };
  31285. return RawTexture;
  31286. })(BABYLON.Texture);
  31287. BABYLON.RawTexture = RawTexture;
  31288. })(BABYLON || (BABYLON = {}));
  31289. var BABYLON;
  31290. (function (BABYLON) {
  31291. var IndexedVector2 = (function (_super) {
  31292. __extends(IndexedVector2, _super);
  31293. function IndexedVector2(original, index) {
  31294. _super.call(this, original.x, original.y);
  31295. this.index = index;
  31296. }
  31297. return IndexedVector2;
  31298. })(BABYLON.Vector2);
  31299. var PolygonPoints = (function () {
  31300. function PolygonPoints() {
  31301. this.elements = new Array();
  31302. }
  31303. PolygonPoints.prototype.add = function (originalPoints) {
  31304. var _this = this;
  31305. var result = new Array();
  31306. originalPoints.forEach(function (point) {
  31307. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  31308. var newPoint = new IndexedVector2(point, _this.elements.length);
  31309. result.push(newPoint);
  31310. _this.elements.push(newPoint);
  31311. }
  31312. });
  31313. return result;
  31314. };
  31315. PolygonPoints.prototype.computeBounds = function () {
  31316. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  31317. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  31318. this.elements.forEach(function (point) {
  31319. // x
  31320. if (point.x < lmin.x) {
  31321. lmin.x = point.x;
  31322. }
  31323. else if (point.x > lmax.x) {
  31324. lmax.x = point.x;
  31325. }
  31326. // y
  31327. if (point.y < lmin.y) {
  31328. lmin.y = point.y;
  31329. }
  31330. else if (point.y > lmax.y) {
  31331. lmax.y = point.y;
  31332. }
  31333. });
  31334. return {
  31335. min: lmin,
  31336. max: lmax,
  31337. width: lmax.x - lmin.x,
  31338. height: lmax.y - lmin.y
  31339. };
  31340. };
  31341. return PolygonPoints;
  31342. })();
  31343. var Polygon = (function () {
  31344. function Polygon() {
  31345. }
  31346. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  31347. return [
  31348. new BABYLON.Vector2(xmin, ymin),
  31349. new BABYLON.Vector2(xmax, ymin),
  31350. new BABYLON.Vector2(xmax, ymax),
  31351. new BABYLON.Vector2(xmin, ymax)
  31352. ];
  31353. };
  31354. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  31355. if (cx === void 0) { cx = 0; }
  31356. if (cy === void 0) { cy = 0; }
  31357. if (numberOfSides === void 0) { numberOfSides = 32; }
  31358. var result = new Array();
  31359. var angle = 0;
  31360. var increment = (Math.PI * 2) / numberOfSides;
  31361. for (var i = 0; i < numberOfSides; i++) {
  31362. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  31363. angle -= increment;
  31364. }
  31365. return result;
  31366. };
  31367. Polygon.Parse = function (input) {
  31368. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  31369. var i, result = [];
  31370. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  31371. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  31372. }
  31373. return result;
  31374. };
  31375. Polygon.StartingAt = function (x, y) {
  31376. return BABYLON.Path2.StartingAt(x, y);
  31377. };
  31378. return Polygon;
  31379. })();
  31380. BABYLON.Polygon = Polygon;
  31381. var PolygonMeshBuilder = (function () {
  31382. function PolygonMeshBuilder(name, contours, scene) {
  31383. this._points = new PolygonPoints();
  31384. this._outlinepoints = new PolygonPoints();
  31385. this._holes = [];
  31386. if (!("poly2tri" in window)) {
  31387. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  31388. }
  31389. this._name = name;
  31390. this._scene = scene;
  31391. var points;
  31392. if (contours instanceof BABYLON.Path2) {
  31393. points = contours.getPoints();
  31394. }
  31395. else {
  31396. points = contours;
  31397. }
  31398. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  31399. this._outlinepoints.add(points);
  31400. }
  31401. PolygonMeshBuilder.prototype.addHole = function (hole) {
  31402. this._swctx.addHole(this._points.add(hole));
  31403. var holepoints = new PolygonPoints();
  31404. holepoints.add(hole);
  31405. this._holes.push(holepoints);
  31406. return this;
  31407. };
  31408. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  31409. var _this = this;
  31410. if (updatable === void 0) { updatable = false; }
  31411. var result = new BABYLON.Mesh(this._name, this._scene);
  31412. var normals = [];
  31413. var positions = [];
  31414. var uvs = [];
  31415. var bounds = this._points.computeBounds();
  31416. this._points.elements.forEach(function (p) {
  31417. normals.push(0, 1.0, 0);
  31418. positions.push(p.x, 0, p.y);
  31419. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  31420. });
  31421. var indices = [];
  31422. this._swctx.triangulate();
  31423. this._swctx.getTriangles().forEach(function (triangle) {
  31424. triangle.getPoints().forEach(function (point) {
  31425. indices.push(point.index);
  31426. });
  31427. });
  31428. if (depth > 0) {
  31429. var positionscount = (positions.length / 3); //get the current pointcount
  31430. this._points.elements.forEach(function (p) {
  31431. normals.push(0, -1.0, 0);
  31432. positions.push(p.x, -depth, p.y);
  31433. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  31434. });
  31435. var p1; //we need to change order of point so the triangles are made in the rigth way.
  31436. var p2;
  31437. var poscounter = 0;
  31438. this._swctx.getTriangles().forEach(function (triangle) {
  31439. triangle.getPoints().forEach(function (point) {
  31440. switch (poscounter) {
  31441. case 0:
  31442. p1 = point;
  31443. break;
  31444. case 1:
  31445. p2 = point;
  31446. break;
  31447. case 2:
  31448. indices.push(point.index + positionscount);
  31449. indices.push(p2.index + positionscount);
  31450. indices.push(p1.index + positionscount);
  31451. poscounter = -1;
  31452. break;
  31453. }
  31454. poscounter++;
  31455. //indices.push((<IndexedVector2>point).index + positionscount);
  31456. });
  31457. });
  31458. //Add the sides
  31459. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  31460. this._holes.forEach(function (hole) {
  31461. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  31462. });
  31463. }
  31464. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  31465. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  31466. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  31467. result.setIndices(indices);
  31468. return result;
  31469. };
  31470. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  31471. var StartIndex = positions.length / 3;
  31472. var ulength = 0;
  31473. for (var i = 0; i < points.elements.length; i++) {
  31474. var p = points.elements[i];
  31475. var p1;
  31476. if ((i + 1) > points.elements.length - 1) {
  31477. p1 = points.elements[0];
  31478. }
  31479. else {
  31480. p1 = points.elements[i + 1];
  31481. }
  31482. positions.push(p.x, 0, p.y);
  31483. positions.push(p.x, -depth, p.y);
  31484. positions.push(p1.x, 0, p1.y);
  31485. positions.push(p1.x, -depth, p1.y);
  31486. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  31487. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  31488. var v3 = v2.subtract(v1);
  31489. var v4 = new BABYLON.Vector3(0, 1, 0);
  31490. var vn = BABYLON.Vector3.Cross(v3, v4);
  31491. vn = vn.normalize();
  31492. uvs.push(ulength / bounds.width, 0);
  31493. uvs.push(ulength / bounds.width, 1);
  31494. ulength += v3.length();
  31495. uvs.push((ulength / bounds.width), 0);
  31496. uvs.push((ulength / bounds.width), 1);
  31497. if (!flip) {
  31498. normals.push(-vn.x, -vn.y, -vn.z);
  31499. normals.push(-vn.x, -vn.y, -vn.z);
  31500. normals.push(-vn.x, -vn.y, -vn.z);
  31501. normals.push(-vn.x, -vn.y, -vn.z);
  31502. indices.push(StartIndex);
  31503. indices.push(StartIndex + 1);
  31504. indices.push(StartIndex + 2);
  31505. indices.push(StartIndex + 1);
  31506. indices.push(StartIndex + 3);
  31507. indices.push(StartIndex + 2);
  31508. }
  31509. else {
  31510. normals.push(vn.x, vn.y, vn.z);
  31511. normals.push(vn.x, vn.y, vn.z);
  31512. normals.push(vn.x, vn.y, vn.z);
  31513. normals.push(vn.x, vn.y, vn.z);
  31514. indices.push(StartIndex);
  31515. indices.push(StartIndex + 2);
  31516. indices.push(StartIndex + 1);
  31517. indices.push(StartIndex + 1);
  31518. indices.push(StartIndex + 2);
  31519. indices.push(StartIndex + 3);
  31520. }
  31521. StartIndex += 4;
  31522. }
  31523. ;
  31524. };
  31525. return PolygonMeshBuilder;
  31526. })();
  31527. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  31528. })(BABYLON || (BABYLON = {}));
  31529. var BABYLON;
  31530. (function (BABYLON) {
  31531. var Octree = (function () {
  31532. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  31533. if (maxDepth === void 0) { maxDepth = 2; }
  31534. this.maxDepth = maxDepth;
  31535. this.dynamicContent = new Array();
  31536. this._maxBlockCapacity = maxBlockCapacity || 64;
  31537. this._selectionContent = new BABYLON.SmartArray(1024);
  31538. this._creationFunc = creationFunc;
  31539. }
  31540. // Methods
  31541. Octree.prototype.update = function (worldMin, worldMax, entries) {
  31542. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  31543. };
  31544. Octree.prototype.addMesh = function (entry) {
  31545. for (var index = 0; index < this.blocks.length; index++) {
  31546. var block = this.blocks[index];
  31547. block.addEntry(entry);
  31548. }
  31549. };
  31550. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  31551. this._selectionContent.reset();
  31552. for (var index = 0; index < this.blocks.length; index++) {
  31553. var block = this.blocks[index];
  31554. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  31555. }
  31556. if (allowDuplicate) {
  31557. this._selectionContent.concat(this.dynamicContent);
  31558. }
  31559. else {
  31560. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  31561. }
  31562. return this._selectionContent;
  31563. };
  31564. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  31565. this._selectionContent.reset();
  31566. for (var index = 0; index < this.blocks.length; index++) {
  31567. var block = this.blocks[index];
  31568. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  31569. }
  31570. if (allowDuplicate) {
  31571. this._selectionContent.concat(this.dynamicContent);
  31572. }
  31573. else {
  31574. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  31575. }
  31576. return this._selectionContent;
  31577. };
  31578. Octree.prototype.intersectsRay = function (ray) {
  31579. this._selectionContent.reset();
  31580. for (var index = 0; index < this.blocks.length; index++) {
  31581. var block = this.blocks[index];
  31582. block.intersectsRay(ray, this._selectionContent);
  31583. }
  31584. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  31585. return this._selectionContent;
  31586. };
  31587. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  31588. target.blocks = new Array();
  31589. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  31590. // Segmenting space
  31591. for (var x = 0; x < 2; x++) {
  31592. for (var y = 0; y < 2; y++) {
  31593. for (var z = 0; z < 2; z++) {
  31594. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  31595. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  31596. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  31597. block.addEntries(entries);
  31598. target.blocks.push(block);
  31599. }
  31600. }
  31601. }
  31602. };
  31603. Octree.CreationFuncForMeshes = function (entry, block) {
  31604. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  31605. block.entries.push(entry);
  31606. }
  31607. };
  31608. Octree.CreationFuncForSubMeshes = function (entry, block) {
  31609. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  31610. block.entries.push(entry);
  31611. }
  31612. };
  31613. return Octree;
  31614. })();
  31615. BABYLON.Octree = Octree;
  31616. })(BABYLON || (BABYLON = {}));
  31617. var BABYLON;
  31618. (function (BABYLON) {
  31619. var OctreeBlock = (function () {
  31620. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  31621. this.entries = new Array();
  31622. this._boundingVectors = new Array();
  31623. this._capacity = capacity;
  31624. this._depth = depth;
  31625. this._maxDepth = maxDepth;
  31626. this._creationFunc = creationFunc;
  31627. this._minPoint = minPoint;
  31628. this._maxPoint = maxPoint;
  31629. this._boundingVectors.push(minPoint.clone());
  31630. this._boundingVectors.push(maxPoint.clone());
  31631. this._boundingVectors.push(minPoint.clone());
  31632. this._boundingVectors[2].x = maxPoint.x;
  31633. this._boundingVectors.push(minPoint.clone());
  31634. this._boundingVectors[3].y = maxPoint.y;
  31635. this._boundingVectors.push(minPoint.clone());
  31636. this._boundingVectors[4].z = maxPoint.z;
  31637. this._boundingVectors.push(maxPoint.clone());
  31638. this._boundingVectors[5].z = minPoint.z;
  31639. this._boundingVectors.push(maxPoint.clone());
  31640. this._boundingVectors[6].x = minPoint.x;
  31641. this._boundingVectors.push(maxPoint.clone());
  31642. this._boundingVectors[7].y = minPoint.y;
  31643. }
  31644. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  31645. // Property
  31646. get: function () {
  31647. return this._capacity;
  31648. },
  31649. enumerable: true,
  31650. configurable: true
  31651. });
  31652. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  31653. get: function () {
  31654. return this._minPoint;
  31655. },
  31656. enumerable: true,
  31657. configurable: true
  31658. });
  31659. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  31660. get: function () {
  31661. return this._maxPoint;
  31662. },
  31663. enumerable: true,
  31664. configurable: true
  31665. });
  31666. // Methods
  31667. OctreeBlock.prototype.addEntry = function (entry) {
  31668. if (this.blocks) {
  31669. for (var index = 0; index < this.blocks.length; index++) {
  31670. var block = this.blocks[index];
  31671. block.addEntry(entry);
  31672. }
  31673. return;
  31674. }
  31675. this._creationFunc(entry, this);
  31676. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  31677. this.createInnerBlocks();
  31678. }
  31679. };
  31680. OctreeBlock.prototype.addEntries = function (entries) {
  31681. for (var index = 0; index < entries.length; index++) {
  31682. var mesh = entries[index];
  31683. this.addEntry(mesh);
  31684. }
  31685. };
  31686. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  31687. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  31688. if (this.blocks) {
  31689. for (var index = 0; index < this.blocks.length; index++) {
  31690. var block = this.blocks[index];
  31691. block.select(frustumPlanes, selection, allowDuplicate);
  31692. }
  31693. return;
  31694. }
  31695. if (allowDuplicate) {
  31696. selection.concat(this.entries);
  31697. }
  31698. else {
  31699. selection.concatWithNoDuplicate(this.entries);
  31700. }
  31701. }
  31702. };
  31703. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  31704. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  31705. if (this.blocks) {
  31706. for (var index = 0; index < this.blocks.length; index++) {
  31707. var block = this.blocks[index];
  31708. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  31709. }
  31710. return;
  31711. }
  31712. if (allowDuplicate) {
  31713. selection.concat(this.entries);
  31714. }
  31715. else {
  31716. selection.concatWithNoDuplicate(this.entries);
  31717. }
  31718. }
  31719. };
  31720. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  31721. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  31722. if (this.blocks) {
  31723. for (var index = 0; index < this.blocks.length; index++) {
  31724. var block = this.blocks[index];
  31725. block.intersectsRay(ray, selection);
  31726. }
  31727. return;
  31728. }
  31729. selection.concatWithNoDuplicate(this.entries);
  31730. }
  31731. };
  31732. OctreeBlock.prototype.createInnerBlocks = function () {
  31733. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  31734. };
  31735. return OctreeBlock;
  31736. })();
  31737. BABYLON.OctreeBlock = OctreeBlock;
  31738. })(BABYLON || (BABYLON = {}));
  31739. var BABYLON;
  31740. (function (BABYLON) {
  31741. var BlurPostProcess = (function (_super) {
  31742. __extends(BlurPostProcess, _super);
  31743. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  31744. var _this = this;
  31745. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  31746. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  31747. this.direction = direction;
  31748. this.blurWidth = blurWidth;
  31749. this.onApply = function (effect) {
  31750. effect.setFloat2("screenSize", _this.width, _this.height);
  31751. effect.setVector2("direction", _this.direction);
  31752. effect.setFloat("blurWidth", _this.blurWidth);
  31753. };
  31754. }
  31755. return BlurPostProcess;
  31756. })(BABYLON.PostProcess);
  31757. BABYLON.BlurPostProcess = BlurPostProcess;
  31758. })(BABYLON || (BABYLON = {}));
  31759. var BABYLON;
  31760. (function (BABYLON) {
  31761. var RefractionPostProcess = (function (_super) {
  31762. __extends(RefractionPostProcess, _super);
  31763. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  31764. var _this = this;
  31765. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  31766. this.color = color;
  31767. this.depth = depth;
  31768. this.colorLevel = colorLevel;
  31769. this.onActivate = function (cam) {
  31770. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  31771. };
  31772. this.onApply = function (effect) {
  31773. effect.setColor3("baseColor", _this.color);
  31774. effect.setFloat("depth", _this.depth);
  31775. effect.setFloat("colorLevel", _this.colorLevel);
  31776. effect.setTexture("refractionSampler", _this._refRexture);
  31777. };
  31778. }
  31779. // Methods
  31780. RefractionPostProcess.prototype.dispose = function (camera) {
  31781. if (this._refRexture) {
  31782. this._refRexture.dispose();
  31783. }
  31784. _super.prototype.dispose.call(this, camera);
  31785. };
  31786. return RefractionPostProcess;
  31787. })(BABYLON.PostProcess);
  31788. BABYLON.RefractionPostProcess = RefractionPostProcess;
  31789. })(BABYLON || (BABYLON = {}));
  31790. var BABYLON;
  31791. (function (BABYLON) {
  31792. var BlackAndWhitePostProcess = (function (_super) {
  31793. __extends(BlackAndWhitePostProcess, _super);
  31794. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  31795. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  31796. }
  31797. return BlackAndWhitePostProcess;
  31798. })(BABYLON.PostProcess);
  31799. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  31800. })(BABYLON || (BABYLON = {}));
  31801. var BABYLON;
  31802. (function (BABYLON) {
  31803. var ConvolutionPostProcess = (function (_super) {
  31804. __extends(ConvolutionPostProcess, _super);
  31805. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  31806. var _this = this;
  31807. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  31808. this.kernel = kernel;
  31809. this.onApply = function (effect) {
  31810. effect.setFloat2("screenSize", _this.width, _this.height);
  31811. effect.setArray("kernel", _this.kernel);
  31812. };
  31813. }
  31814. // Statics
  31815. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  31816. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  31817. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  31818. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  31819. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  31820. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  31821. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  31822. return ConvolutionPostProcess;
  31823. })(BABYLON.PostProcess);
  31824. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  31825. })(BABYLON || (BABYLON = {}));
  31826. var BABYLON;
  31827. (function (BABYLON) {
  31828. var FilterPostProcess = (function (_super) {
  31829. __extends(FilterPostProcess, _super);
  31830. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  31831. var _this = this;
  31832. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  31833. this.kernelMatrix = kernelMatrix;
  31834. this.onApply = function (effect) {
  31835. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  31836. };
  31837. }
  31838. return FilterPostProcess;
  31839. })(BABYLON.PostProcess);
  31840. BABYLON.FilterPostProcess = FilterPostProcess;
  31841. })(BABYLON || (BABYLON = {}));
  31842. var BABYLON;
  31843. (function (BABYLON) {
  31844. var FxaaPostProcess = (function (_super) {
  31845. __extends(FxaaPostProcess, _super);
  31846. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  31847. var _this = this;
  31848. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  31849. this.onSizeChanged = function () {
  31850. _this.texelWidth = 1.0 / _this.width;
  31851. _this.texelHeight = 1.0 / _this.height;
  31852. };
  31853. this.onApply = function (effect) {
  31854. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  31855. };
  31856. }
  31857. return FxaaPostProcess;
  31858. })(BABYLON.PostProcess);
  31859. BABYLON.FxaaPostProcess = FxaaPostProcess;
  31860. })(BABYLON || (BABYLON = {}));
  31861. var BABYLON;
  31862. (function (BABYLON) {
  31863. var StereoscopicInterlacePostProcess = (function (_super) {
  31864. __extends(StereoscopicInterlacePostProcess, _super);
  31865. function StereoscopicInterlacePostProcess(name, camB, postProcessA, isStereoscopicHoriz, samplingMode) {
  31866. var _this = this;
  31867. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, camB, samplingMode, camB.getScene().getEngine(), false, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  31868. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  31869. this.onSizeChanged = function () {
  31870. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  31871. };
  31872. this.onApply = function (effect) {
  31873. effect.setTextureFromPostProcess("camASampler", postProcessA);
  31874. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  31875. };
  31876. }
  31877. return StereoscopicInterlacePostProcess;
  31878. })(BABYLON.PostProcess);
  31879. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  31880. })(BABYLON || (BABYLON = {}));
  31881. var BABYLON;
  31882. (function (BABYLON) {
  31883. var LensFlare = (function () {
  31884. function LensFlare(size, position, color, imgUrl, system) {
  31885. this.size = size;
  31886. this.position = position;
  31887. this.dispose = function () {
  31888. if (this.texture) {
  31889. this.texture.dispose();
  31890. }
  31891. // Remove from scene
  31892. var index = this._system.lensFlares.indexOf(this);
  31893. this._system.lensFlares.splice(index, 1);
  31894. };
  31895. this.color = color || new BABYLON.Color3(1, 1, 1);
  31896. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  31897. this._system = system;
  31898. system.lensFlares.push(this);
  31899. }
  31900. return LensFlare;
  31901. })();
  31902. BABYLON.LensFlare = LensFlare;
  31903. })(BABYLON || (BABYLON = {}));
  31904. var BABYLON;
  31905. (function (BABYLON) {
  31906. var LensFlareSystem = (function () {
  31907. function LensFlareSystem(name, emitter, scene) {
  31908. this.name = name;
  31909. this.lensFlares = new Array();
  31910. this.borderLimit = 300;
  31911. this.layerMask = 0x0FFFFFFF;
  31912. this._vertexDeclaration = [2];
  31913. this._vertexStrideSize = 2 * 4;
  31914. this._isEnabled = true;
  31915. this._scene = scene;
  31916. this._emitter = emitter;
  31917. scene.lensFlareSystems.push(this);
  31918. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  31919. // VBO
  31920. var vertices = [];
  31921. vertices.push(1, 1);
  31922. vertices.push(-1, 1);
  31923. vertices.push(-1, -1);
  31924. vertices.push(1, -1);
  31925. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  31926. // Indices
  31927. var indices = [];
  31928. indices.push(0);
  31929. indices.push(1);
  31930. indices.push(2);
  31931. indices.push(0);
  31932. indices.push(2);
  31933. indices.push(3);
  31934. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  31935. // Effects
  31936. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  31937. }
  31938. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  31939. get: function () {
  31940. return this._isEnabled;
  31941. },
  31942. set: function (value) {
  31943. this._isEnabled = value;
  31944. },
  31945. enumerable: true,
  31946. configurable: true
  31947. });
  31948. LensFlareSystem.prototype.getScene = function () {
  31949. return this._scene;
  31950. };
  31951. LensFlareSystem.prototype.getEmitter = function () {
  31952. return this._emitter;
  31953. };
  31954. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  31955. this._emitter = newEmitter;
  31956. };
  31957. LensFlareSystem.prototype.getEmitterPosition = function () {
  31958. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  31959. };
  31960. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  31961. var position = this.getEmitterPosition();
  31962. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  31963. this._positionX = position.x;
  31964. this._positionY = position.y;
  31965. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  31966. if (position.z > 0) {
  31967. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  31968. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  31969. return true;
  31970. }
  31971. }
  31972. return false;
  31973. };
  31974. LensFlareSystem.prototype._isVisible = function () {
  31975. if (!this._isEnabled) {
  31976. return false;
  31977. }
  31978. var emitterPosition = this.getEmitterPosition();
  31979. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  31980. var distance = direction.length();
  31981. direction.normalize();
  31982. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  31983. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  31984. return !pickInfo.hit || pickInfo.distance > distance;
  31985. };
  31986. LensFlareSystem.prototype.render = function () {
  31987. if (!this._effect.isReady())
  31988. return false;
  31989. var engine = this._scene.getEngine();
  31990. var viewport = this._scene.activeCamera.viewport;
  31991. var globalViewport = viewport.toGlobal(engine);
  31992. // Position
  31993. if (!this.computeEffectivePosition(globalViewport)) {
  31994. return false;
  31995. }
  31996. // Visibility
  31997. if (!this._isVisible()) {
  31998. return false;
  31999. }
  32000. // Intensity
  32001. var awayX;
  32002. var awayY;
  32003. if (this._positionX < this.borderLimit + globalViewport.x) {
  32004. awayX = this.borderLimit + globalViewport.x - this._positionX;
  32005. }
  32006. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  32007. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  32008. }
  32009. else {
  32010. awayX = 0;
  32011. }
  32012. if (this._positionY < this.borderLimit + globalViewport.y) {
  32013. awayY = this.borderLimit + globalViewport.y - this._positionY;
  32014. }
  32015. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  32016. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  32017. }
  32018. else {
  32019. awayY = 0;
  32020. }
  32021. var away = (awayX > awayY) ? awayX : awayY;
  32022. if (away > this.borderLimit) {
  32023. away = this.borderLimit;
  32024. }
  32025. var intensity = 1.0 - (away / this.borderLimit);
  32026. if (intensity < 0) {
  32027. return false;
  32028. }
  32029. if (intensity > 1.0) {
  32030. intensity = 1.0;
  32031. }
  32032. // Position
  32033. var centerX = globalViewport.x + globalViewport.width / 2;
  32034. var centerY = globalViewport.y + globalViewport.height / 2;
  32035. var distX = centerX - this._positionX;
  32036. var distY = centerY - this._positionY;
  32037. // Effects
  32038. engine.enableEffect(this._effect);
  32039. engine.setState(false);
  32040. engine.setDepthBuffer(false);
  32041. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  32042. // VBOs
  32043. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  32044. // Flares
  32045. for (var index = 0; index < this.lensFlares.length; index++) {
  32046. var flare = this.lensFlares[index];
  32047. var x = centerX - (distX * flare.position);
  32048. var y = centerY - (distY * flare.position);
  32049. var cw = flare.size;
  32050. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  32051. var cx = 2 * (x / globalViewport.width) - 1.0;
  32052. var cy = 1.0 - 2 * (y / globalViewport.height);
  32053. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  32054. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  32055. // Texture
  32056. this._effect.setTexture("textureSampler", flare.texture);
  32057. // Color
  32058. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  32059. // Draw order
  32060. engine.draw(true, 0, 6);
  32061. }
  32062. engine.setDepthBuffer(true);
  32063. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  32064. return true;
  32065. };
  32066. LensFlareSystem.prototype.dispose = function () {
  32067. if (this._vertexBuffer) {
  32068. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  32069. this._vertexBuffer = null;
  32070. }
  32071. if (this._indexBuffer) {
  32072. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  32073. this._indexBuffer = null;
  32074. }
  32075. while (this.lensFlares.length) {
  32076. this.lensFlares[0].dispose();
  32077. }
  32078. // Remove from scene
  32079. var index = this._scene.lensFlareSystems.indexOf(this);
  32080. this._scene.lensFlareSystems.splice(index, 1);
  32081. };
  32082. return LensFlareSystem;
  32083. })();
  32084. BABYLON.LensFlareSystem = LensFlareSystem;
  32085. })(BABYLON || (BABYLON = {}));
  32086. var BABYLON;
  32087. (function (BABYLON) {
  32088. // We're mainly based on the logic defined into the FreeCamera code
  32089. var DeviceOrientationCamera = (function (_super) {
  32090. __extends(DeviceOrientationCamera, _super);
  32091. function DeviceOrientationCamera(name, position, scene) {
  32092. var _this = this;
  32093. _super.call(this, name, position, scene);
  32094. this._offsetX = null;
  32095. this._offsetY = null;
  32096. this._orientationGamma = 0;
  32097. this._orientationBeta = 0;
  32098. this._initialOrientationGamma = 0;
  32099. this._initialOrientationBeta = 0;
  32100. this.angularSensibility = 10000.0;
  32101. this.moveSensibility = 50.0;
  32102. window.addEventListener("resize", function () {
  32103. _this._initialOrientationGamma = null;
  32104. }, false);
  32105. }
  32106. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  32107. var _this = this;
  32108. if (this._attachedCanvas) {
  32109. return;
  32110. }
  32111. this._attachedCanvas = canvas;
  32112. if (!this._orientationChanged) {
  32113. this._orientationChanged = function (evt) {
  32114. if (!_this._initialOrientationGamma) {
  32115. _this._initialOrientationGamma = evt.gamma;
  32116. _this._initialOrientationBeta = evt.beta;
  32117. }
  32118. _this._orientationGamma = evt.gamma;
  32119. _this._orientationBeta = evt.beta;
  32120. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  32121. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  32122. };
  32123. }
  32124. window.addEventListener("deviceorientation", this._orientationChanged);
  32125. };
  32126. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  32127. if (this._attachedCanvas != canvas) {
  32128. return;
  32129. }
  32130. window.removeEventListener("deviceorientation", this._orientationChanged);
  32131. this._attachedCanvas = null;
  32132. this._orientationGamma = 0;
  32133. this._orientationBeta = 0;
  32134. this._initialOrientationGamma = 0;
  32135. this._initialOrientationBeta = 0;
  32136. };
  32137. DeviceOrientationCamera.prototype._checkInputs = function () {
  32138. if (!this._offsetX) {
  32139. return;
  32140. }
  32141. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  32142. var speed = this._computeLocalCameraSpeed();
  32143. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  32144. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  32145. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  32146. _super.prototype._checkInputs.call(this);
  32147. };
  32148. return DeviceOrientationCamera;
  32149. })(BABYLON.FreeCamera);
  32150. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  32151. })(BABYLON || (BABYLON = {}));
  32152. var BABYLON;
  32153. (function (BABYLON) {
  32154. var Gamepads = (function () {
  32155. function Gamepads(ongamedpadconnected) {
  32156. var _this = this;
  32157. this.babylonGamepads = [];
  32158. this.oneGamepadConnected = false;
  32159. this.isMonitoring = false;
  32160. this.gamepadEventSupported = 'GamepadEvent' in window;
  32161. this.gamepadSupportAvailable = (navigator.getGamepads ||
  32162. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  32163. 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=";
  32164. this._callbackGamepadConnected = ongamedpadconnected;
  32165. if (this.gamepadSupportAvailable) {
  32166. // Checking if the gamepad connected event is supported (like in Firefox)
  32167. if (this.gamepadEventSupported) {
  32168. window.addEventListener('gamepadconnected', function (evt) {
  32169. _this._onGamepadConnected(evt);
  32170. }, false);
  32171. window.addEventListener('gamepaddisconnected', function (evt) {
  32172. _this._onGamepadDisconnected(evt);
  32173. }, false);
  32174. }
  32175. else {
  32176. this._startMonitoringGamepads();
  32177. }
  32178. if (!this.oneGamepadConnected) {
  32179. this._insertGamepadDOMInstructions();
  32180. }
  32181. }
  32182. else {
  32183. this._insertGamepadDOMNotSupported();
  32184. }
  32185. }
  32186. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  32187. Gamepads.gamepadDOMInfo = document.createElement("div");
  32188. var buttonAImage = document.createElement("img");
  32189. buttonAImage.src = this.buttonADataURL;
  32190. var spanMessage = document.createElement("span");
  32191. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  32192. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  32193. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  32194. Gamepads.gamepadDOMInfo.style.position = "absolute";
  32195. Gamepads.gamepadDOMInfo.style.width = "100%";
  32196. Gamepads.gamepadDOMInfo.style.height = "48px";
  32197. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  32198. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  32199. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  32200. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  32201. buttonAImage.style.position = "relative";
  32202. buttonAImage.style.bottom = "8px";
  32203. spanMessage.style.position = "relative";
  32204. spanMessage.style.fontSize = "32px";
  32205. spanMessage.style.bottom = "32px";
  32206. spanMessage.style.color = "green";
  32207. document.body.appendChild(Gamepads.gamepadDOMInfo);
  32208. };
  32209. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  32210. Gamepads.gamepadDOMInfo = document.createElement("div");
  32211. var spanMessage = document.createElement("span");
  32212. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  32213. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  32214. Gamepads.gamepadDOMInfo.style.position = "absolute";
  32215. Gamepads.gamepadDOMInfo.style.width = "100%";
  32216. Gamepads.gamepadDOMInfo.style.height = "40px";
  32217. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  32218. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  32219. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  32220. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  32221. spanMessage.style.position = "relative";
  32222. spanMessage.style.fontSize = "32px";
  32223. spanMessage.style.color = "red";
  32224. document.body.appendChild(Gamepads.gamepadDOMInfo);
  32225. };
  32226. Gamepads.prototype.dispose = function () {
  32227. if (Gamepads.gamepadDOMInfo) {
  32228. document.body.removeChild(Gamepads.gamepadDOMInfo);
  32229. }
  32230. };
  32231. Gamepads.prototype._onGamepadConnected = function (evt) {
  32232. var newGamepad = this._addNewGamepad(evt.gamepad);
  32233. if (this._callbackGamepadConnected)
  32234. this._callbackGamepadConnected(newGamepad);
  32235. this._startMonitoringGamepads();
  32236. };
  32237. Gamepads.prototype._addNewGamepad = function (gamepad) {
  32238. if (!this.oneGamepadConnected) {
  32239. this.oneGamepadConnected = true;
  32240. if (Gamepads.gamepadDOMInfo) {
  32241. document.body.removeChild(Gamepads.gamepadDOMInfo);
  32242. Gamepads.gamepadDOMInfo = null;
  32243. }
  32244. }
  32245. var newGamepad;
  32246. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  32247. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  32248. }
  32249. else {
  32250. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  32251. }
  32252. this.babylonGamepads.push(newGamepad);
  32253. return newGamepad;
  32254. };
  32255. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  32256. // Remove the gamepad from the list of gamepads to monitor.
  32257. for (var i in this.babylonGamepads) {
  32258. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  32259. this.babylonGamepads.splice(i, 1);
  32260. break;
  32261. }
  32262. }
  32263. // If no gamepads are left, stop the polling loop.
  32264. if (this.babylonGamepads.length == 0) {
  32265. this._stopMonitoringGamepads();
  32266. }
  32267. };
  32268. Gamepads.prototype._startMonitoringGamepads = function () {
  32269. if (!this.isMonitoring) {
  32270. this.isMonitoring = true;
  32271. this._checkGamepadsStatus();
  32272. }
  32273. };
  32274. Gamepads.prototype._stopMonitoringGamepads = function () {
  32275. this.isMonitoring = false;
  32276. };
  32277. Gamepads.prototype._checkGamepadsStatus = function () {
  32278. var _this = this;
  32279. // updating gamepad objects
  32280. this._updateGamepadObjects();
  32281. for (var i in this.babylonGamepads) {
  32282. this.babylonGamepads[i].update();
  32283. }
  32284. if (this.isMonitoring) {
  32285. if (window.requestAnimationFrame) {
  32286. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  32287. }
  32288. else if (window.mozRequestAnimationFrame) {
  32289. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  32290. }
  32291. else if (window.webkitRequestAnimationFrame) {
  32292. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  32293. }
  32294. }
  32295. };
  32296. // This function is called only on Chrome, which does not yet support
  32297. // connection/disconnection events, but requires you to monitor
  32298. // an array for changes.
  32299. Gamepads.prototype._updateGamepadObjects = function () {
  32300. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  32301. for (var i = 0; i < gamepads.length; i++) {
  32302. if (gamepads[i]) {
  32303. if (!(gamepads[i].index in this.babylonGamepads)) {
  32304. var newGamepad = this._addNewGamepad(gamepads[i]);
  32305. if (this._callbackGamepadConnected) {
  32306. this._callbackGamepadConnected(newGamepad);
  32307. }
  32308. }
  32309. else {
  32310. this.babylonGamepads[i].browserGamepad = gamepads[i];
  32311. }
  32312. }
  32313. }
  32314. };
  32315. return Gamepads;
  32316. })();
  32317. BABYLON.Gamepads = Gamepads;
  32318. var StickValues = (function () {
  32319. function StickValues(x, y) {
  32320. this.x = x;
  32321. this.y = y;
  32322. }
  32323. return StickValues;
  32324. })();
  32325. BABYLON.StickValues = StickValues;
  32326. var Gamepad = (function () {
  32327. function Gamepad(id, index, browserGamepad) {
  32328. this.id = id;
  32329. this.index = index;
  32330. this.browserGamepad = browserGamepad;
  32331. if (this.browserGamepad.axes.length >= 2) {
  32332. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  32333. }
  32334. if (this.browserGamepad.axes.length >= 4) {
  32335. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  32336. }
  32337. }
  32338. Gamepad.prototype.onleftstickchanged = function (callback) {
  32339. this._onleftstickchanged = callback;
  32340. };
  32341. Gamepad.prototype.onrightstickchanged = function (callback) {
  32342. this._onrightstickchanged = callback;
  32343. };
  32344. Object.defineProperty(Gamepad.prototype, "leftStick", {
  32345. get: function () {
  32346. return this._leftStick;
  32347. },
  32348. set: function (newValues) {
  32349. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  32350. this._onleftstickchanged(newValues);
  32351. }
  32352. this._leftStick = newValues;
  32353. },
  32354. enumerable: true,
  32355. configurable: true
  32356. });
  32357. Object.defineProperty(Gamepad.prototype, "rightStick", {
  32358. get: function () {
  32359. return this._rightStick;
  32360. },
  32361. set: function (newValues) {
  32362. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  32363. this._onrightstickchanged(newValues);
  32364. }
  32365. this._rightStick = newValues;
  32366. },
  32367. enumerable: true,
  32368. configurable: true
  32369. });
  32370. Gamepad.prototype.update = function () {
  32371. if (this._leftStick) {
  32372. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  32373. }
  32374. if (this._rightStick) {
  32375. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  32376. }
  32377. };
  32378. return Gamepad;
  32379. })();
  32380. BABYLON.Gamepad = Gamepad;
  32381. var GenericPad = (function (_super) {
  32382. __extends(GenericPad, _super);
  32383. function GenericPad(id, index, gamepad) {
  32384. _super.call(this, id, index, gamepad);
  32385. this.id = id;
  32386. this.index = index;
  32387. this.gamepad = gamepad;
  32388. this._buttons = new Array(gamepad.buttons.length);
  32389. }
  32390. GenericPad.prototype.onbuttondown = function (callback) {
  32391. this._onbuttondown = callback;
  32392. };
  32393. GenericPad.prototype.onbuttonup = function (callback) {
  32394. this._onbuttonup = callback;
  32395. };
  32396. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  32397. if (newValue !== currentValue) {
  32398. if (this._onbuttondown && newValue === 1) {
  32399. this._onbuttondown(buttonIndex);
  32400. }
  32401. if (this._onbuttonup && newValue === 0) {
  32402. this._onbuttonup(buttonIndex);
  32403. }
  32404. }
  32405. return newValue;
  32406. };
  32407. GenericPad.prototype.update = function () {
  32408. _super.prototype.update.call(this);
  32409. for (var index = 0; index < this._buttons.length; index++) {
  32410. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  32411. }
  32412. };
  32413. return GenericPad;
  32414. })(Gamepad);
  32415. BABYLON.GenericPad = GenericPad;
  32416. (function (Xbox360Button) {
  32417. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  32418. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  32419. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  32420. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  32421. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  32422. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  32423. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  32424. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  32425. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  32426. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  32427. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  32428. var Xbox360Button = BABYLON.Xbox360Button;
  32429. (function (Xbox360Dpad) {
  32430. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  32431. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  32432. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  32433. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  32434. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  32435. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  32436. var Xbox360Pad = (function (_super) {
  32437. __extends(Xbox360Pad, _super);
  32438. function Xbox360Pad() {
  32439. _super.apply(this, arguments);
  32440. this._leftTrigger = 0;
  32441. this._rightTrigger = 0;
  32442. this._buttonA = 0;
  32443. this._buttonB = 0;
  32444. this._buttonX = 0;
  32445. this._buttonY = 0;
  32446. this._buttonBack = 0;
  32447. this._buttonStart = 0;
  32448. this._buttonLB = 0;
  32449. this._buttonRB = 0;
  32450. this._buttonLeftStick = 0;
  32451. this._buttonRightStick = 0;
  32452. this._dPadUp = 0;
  32453. this._dPadDown = 0;
  32454. this._dPadLeft = 0;
  32455. this._dPadRight = 0;
  32456. }
  32457. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  32458. this._onlefttriggerchanged = callback;
  32459. };
  32460. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  32461. this._onrighttriggerchanged = callback;
  32462. };
  32463. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  32464. get: function () {
  32465. return this._leftTrigger;
  32466. },
  32467. set: function (newValue) {
  32468. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  32469. this._onlefttriggerchanged(newValue);
  32470. }
  32471. this._leftTrigger = newValue;
  32472. },
  32473. enumerable: true,
  32474. configurable: true
  32475. });
  32476. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  32477. get: function () {
  32478. return this._rightTrigger;
  32479. },
  32480. set: function (newValue) {
  32481. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  32482. this._onrighttriggerchanged(newValue);
  32483. }
  32484. this._rightTrigger = newValue;
  32485. },
  32486. enumerable: true,
  32487. configurable: true
  32488. });
  32489. Xbox360Pad.prototype.onbuttondown = function (callback) {
  32490. this._onbuttondown = callback;
  32491. };
  32492. Xbox360Pad.prototype.onbuttonup = function (callback) {
  32493. this._onbuttonup = callback;
  32494. };
  32495. Xbox360Pad.prototype.ondpaddown = function (callback) {
  32496. this._ondpaddown = callback;
  32497. };
  32498. Xbox360Pad.prototype.ondpadup = function (callback) {
  32499. this._ondpadup = callback;
  32500. };
  32501. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  32502. if (newValue !== currentValue) {
  32503. if (this._onbuttondown && newValue === 1) {
  32504. this._onbuttondown(buttonType);
  32505. }
  32506. if (this._onbuttonup && newValue === 0) {
  32507. this._onbuttonup(buttonType);
  32508. }
  32509. }
  32510. return newValue;
  32511. };
  32512. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  32513. if (newValue !== currentValue) {
  32514. if (this._ondpaddown && newValue === 1) {
  32515. this._ondpaddown(buttonType);
  32516. }
  32517. if (this._ondpadup && newValue === 0) {
  32518. this._ondpadup(buttonType);
  32519. }
  32520. }
  32521. return newValue;
  32522. };
  32523. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  32524. get: function () {
  32525. return this._buttonA;
  32526. },
  32527. set: function (value) {
  32528. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  32529. },
  32530. enumerable: true,
  32531. configurable: true
  32532. });
  32533. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  32534. get: function () {
  32535. return this._buttonB;
  32536. },
  32537. set: function (value) {
  32538. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  32539. },
  32540. enumerable: true,
  32541. configurable: true
  32542. });
  32543. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  32544. get: function () {
  32545. return this._buttonX;
  32546. },
  32547. set: function (value) {
  32548. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  32549. },
  32550. enumerable: true,
  32551. configurable: true
  32552. });
  32553. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  32554. get: function () {
  32555. return this._buttonY;
  32556. },
  32557. set: function (value) {
  32558. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  32559. },
  32560. enumerable: true,
  32561. configurable: true
  32562. });
  32563. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  32564. get: function () {
  32565. return this._buttonStart;
  32566. },
  32567. set: function (value) {
  32568. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  32569. },
  32570. enumerable: true,
  32571. configurable: true
  32572. });
  32573. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  32574. get: function () {
  32575. return this._buttonBack;
  32576. },
  32577. set: function (value) {
  32578. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  32579. },
  32580. enumerable: true,
  32581. configurable: true
  32582. });
  32583. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  32584. get: function () {
  32585. return this._buttonLB;
  32586. },
  32587. set: function (value) {
  32588. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  32589. },
  32590. enumerable: true,
  32591. configurable: true
  32592. });
  32593. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  32594. get: function () {
  32595. return this._buttonRB;
  32596. },
  32597. set: function (value) {
  32598. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  32599. },
  32600. enumerable: true,
  32601. configurable: true
  32602. });
  32603. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  32604. get: function () {
  32605. return this._buttonLeftStick;
  32606. },
  32607. set: function (value) {
  32608. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  32609. },
  32610. enumerable: true,
  32611. configurable: true
  32612. });
  32613. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  32614. get: function () {
  32615. return this._buttonRightStick;
  32616. },
  32617. set: function (value) {
  32618. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  32619. },
  32620. enumerable: true,
  32621. configurable: true
  32622. });
  32623. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  32624. get: function () {
  32625. return this._dPadUp;
  32626. },
  32627. set: function (value) {
  32628. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  32629. },
  32630. enumerable: true,
  32631. configurable: true
  32632. });
  32633. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  32634. get: function () {
  32635. return this._dPadDown;
  32636. },
  32637. set: function (value) {
  32638. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  32639. },
  32640. enumerable: true,
  32641. configurable: true
  32642. });
  32643. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  32644. get: function () {
  32645. return this._dPadLeft;
  32646. },
  32647. set: function (value) {
  32648. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  32649. },
  32650. enumerable: true,
  32651. configurable: true
  32652. });
  32653. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  32654. get: function () {
  32655. return this._dPadRight;
  32656. },
  32657. set: function (value) {
  32658. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  32659. },
  32660. enumerable: true,
  32661. configurable: true
  32662. });
  32663. Xbox360Pad.prototype.update = function () {
  32664. _super.prototype.update.call(this);
  32665. this.buttonA = this.browserGamepad.buttons[0].value;
  32666. this.buttonB = this.browserGamepad.buttons[1].value;
  32667. this.buttonX = this.browserGamepad.buttons[2].value;
  32668. this.buttonY = this.browserGamepad.buttons[3].value;
  32669. this.buttonLB = this.browserGamepad.buttons[4].value;
  32670. this.buttonRB = this.browserGamepad.buttons[5].value;
  32671. this.leftTrigger = this.browserGamepad.buttons[6].value;
  32672. this.rightTrigger = this.browserGamepad.buttons[7].value;
  32673. this.buttonBack = this.browserGamepad.buttons[8].value;
  32674. this.buttonStart = this.browserGamepad.buttons[9].value;
  32675. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  32676. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  32677. this.dPadUp = this.browserGamepad.buttons[12].value;
  32678. this.dPadDown = this.browserGamepad.buttons[13].value;
  32679. this.dPadLeft = this.browserGamepad.buttons[14].value;
  32680. this.dPadRight = this.browserGamepad.buttons[15].value;
  32681. };
  32682. return Xbox360Pad;
  32683. })(Gamepad);
  32684. BABYLON.Xbox360Pad = Xbox360Pad;
  32685. })(BABYLON || (BABYLON = {}));
  32686. var BABYLON;
  32687. (function (BABYLON) {
  32688. // We're mainly based on the logic defined into the FreeCamera code
  32689. var GamepadCamera = (function (_super) {
  32690. __extends(GamepadCamera, _super);
  32691. function GamepadCamera(name, position, scene) {
  32692. var _this = this;
  32693. _super.call(this, name, position, scene);
  32694. this.angularSensibility = 200;
  32695. this.moveSensibility = 75;
  32696. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  32697. }
  32698. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  32699. // Only the first gamepad can control the camera
  32700. if (gamepad.index === 0) {
  32701. this._gamepad = gamepad;
  32702. }
  32703. };
  32704. GamepadCamera.prototype._checkInputs = function () {
  32705. if (this._gamepad) {
  32706. var LSValues = this._gamepad.leftStick;
  32707. var normalizedLX = LSValues.x / this.moveSensibility;
  32708. var normalizedLY = LSValues.y / this.moveSensibility;
  32709. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  32710. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  32711. var RSValues = this._gamepad.rightStick;
  32712. var normalizedRX = RSValues.x / this.angularSensibility;
  32713. var normalizedRY = RSValues.y / this.angularSensibility;
  32714. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  32715. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  32716. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  32717. var speed = this._computeLocalCameraSpeed() * 50.0;
  32718. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  32719. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  32720. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  32721. }
  32722. _super.prototype._checkInputs.call(this);
  32723. };
  32724. GamepadCamera.prototype.dispose = function () {
  32725. this._gamepads.dispose();
  32726. _super.prototype.dispose.call(this);
  32727. };
  32728. return GamepadCamera;
  32729. })(BABYLON.FreeCamera);
  32730. BABYLON.GamepadCamera = GamepadCamera;
  32731. })(BABYLON || (BABYLON = {}));
  32732. var BABYLON;
  32733. (function (BABYLON) {
  32734. var Analyser = (function () {
  32735. function Analyser(scene) {
  32736. this.SMOOTHING = 0.75;
  32737. this.FFT_SIZE = 512;
  32738. this.BARGRAPHAMPLITUDE = 256;
  32739. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  32740. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  32741. this._scene = scene;
  32742. this._audioEngine = BABYLON.Engine.audioEngine;
  32743. if (this._audioEngine.canUseWebAudio) {
  32744. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  32745. this._webAudioAnalyser.minDecibels = -140;
  32746. this._webAudioAnalyser.maxDecibels = 0;
  32747. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  32748. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  32749. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  32750. }
  32751. }
  32752. Analyser.prototype.getFrequencyBinCount = function () {
  32753. if (this._audioEngine.canUseWebAudio) {
  32754. return this._webAudioAnalyser.frequencyBinCount;
  32755. }
  32756. else {
  32757. return 0;
  32758. }
  32759. };
  32760. Analyser.prototype.getByteFrequencyData = function () {
  32761. if (this._audioEngine.canUseWebAudio) {
  32762. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  32763. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  32764. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  32765. }
  32766. return this._byteFreqs;
  32767. };
  32768. Analyser.prototype.getByteTimeDomainData = function () {
  32769. if (this._audioEngine.canUseWebAudio) {
  32770. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  32771. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  32772. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  32773. }
  32774. return this._byteTime;
  32775. };
  32776. Analyser.prototype.getFloatFrequencyData = function () {
  32777. if (this._audioEngine.canUseWebAudio) {
  32778. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  32779. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  32780. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  32781. }
  32782. return this._floatFreqs;
  32783. };
  32784. Analyser.prototype.drawDebugCanvas = function () {
  32785. var _this = this;
  32786. if (this._audioEngine.canUseWebAudio) {
  32787. if (!this._debugCanvas) {
  32788. this._debugCanvas = document.createElement("canvas");
  32789. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  32790. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  32791. this._debugCanvas.style.position = "absolute";
  32792. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  32793. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  32794. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  32795. document.body.appendChild(this._debugCanvas);
  32796. this._registerFunc = function () {
  32797. _this.drawDebugCanvas();
  32798. };
  32799. this._scene.registerBeforeRender(this._registerFunc);
  32800. }
  32801. if (this._registerFunc) {
  32802. var workingArray = this.getByteFrequencyData();
  32803. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  32804. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  32805. // Draw the frequency domain chart.
  32806. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  32807. var value = workingArray[i];
  32808. var percent = value / this.BARGRAPHAMPLITUDE;
  32809. var height = this.DEBUGCANVASSIZE.height * percent;
  32810. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  32811. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  32812. var hue = i / this.getFrequencyBinCount() * 360;
  32813. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  32814. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  32815. }
  32816. }
  32817. }
  32818. };
  32819. Analyser.prototype.stopDebugCanvas = function () {
  32820. if (this._debugCanvas) {
  32821. this._scene.unregisterBeforeRender(this._registerFunc);
  32822. this._registerFunc = null;
  32823. document.body.removeChild(this._debugCanvas);
  32824. this._debugCanvas = null;
  32825. this._debugCanvasContext = null;
  32826. }
  32827. };
  32828. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  32829. if (this._audioEngine.canUseWebAudio) {
  32830. inputAudioNode.connect(this._webAudioAnalyser);
  32831. this._webAudioAnalyser.connect(outputAudioNode);
  32832. }
  32833. };
  32834. Analyser.prototype.dispose = function () {
  32835. if (this._audioEngine.canUseWebAudio) {
  32836. this._webAudioAnalyser.disconnect();
  32837. }
  32838. };
  32839. return Analyser;
  32840. })();
  32841. BABYLON.Analyser = Analyser;
  32842. })(BABYLON || (BABYLON = {}));
  32843. var BABYLON;
  32844. (function (BABYLON) {
  32845. var AudioEngine = (function () {
  32846. function AudioEngine() {
  32847. this._audioContext = null;
  32848. this._audioContextInitialized = false;
  32849. this.canUseWebAudio = false;
  32850. this.WarnedWebAudioUnsupported = false;
  32851. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  32852. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  32853. this.canUseWebAudio = true;
  32854. }
  32855. }
  32856. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  32857. get: function () {
  32858. if (!this._audioContextInitialized) {
  32859. this._initializeAudioContext();
  32860. }
  32861. return this._audioContext;
  32862. },
  32863. enumerable: true,
  32864. configurable: true
  32865. });
  32866. AudioEngine.prototype._initializeAudioContext = function () {
  32867. try {
  32868. if (this.canUseWebAudio) {
  32869. this._audioContext = new AudioContext();
  32870. // create a global volume gain node
  32871. this.masterGain = this._audioContext.createGain();
  32872. this.masterGain.gain.value = 1;
  32873. this.masterGain.connect(this._audioContext.destination);
  32874. this._audioContextInitialized = true;
  32875. }
  32876. }
  32877. catch (e) {
  32878. this.canUseWebAudio = false;
  32879. BABYLON.Tools.Error("Web Audio: " + e.message);
  32880. }
  32881. };
  32882. AudioEngine.prototype.dispose = function () {
  32883. if (this.canUseWebAudio && this._audioContextInitialized) {
  32884. if (this._connectedAnalyser) {
  32885. this._connectedAnalyser.stopDebugCanvas();
  32886. this._connectedAnalyser.dispose();
  32887. this.masterGain.disconnect();
  32888. this.masterGain.connect(this._audioContext.destination);
  32889. this._connectedAnalyser = null;
  32890. }
  32891. this.masterGain.gain.value = 1;
  32892. }
  32893. this.WarnedWebAudioUnsupported = false;
  32894. };
  32895. AudioEngine.prototype.getGlobalVolume = function () {
  32896. if (this.canUseWebAudio && this._audioContextInitialized) {
  32897. return this.masterGain.gain.value;
  32898. }
  32899. else {
  32900. return -1;
  32901. }
  32902. };
  32903. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  32904. if (this.canUseWebAudio && this._audioContextInitialized) {
  32905. this.masterGain.gain.value = newVolume;
  32906. }
  32907. };
  32908. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  32909. if (this._connectedAnalyser) {
  32910. this._connectedAnalyser.stopDebugCanvas();
  32911. }
  32912. if (this.canUseWebAudio && this._audioContextInitialized) {
  32913. this._connectedAnalyser = analyser;
  32914. this.masterGain.disconnect();
  32915. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  32916. }
  32917. };
  32918. return AudioEngine;
  32919. })();
  32920. BABYLON.AudioEngine = AudioEngine;
  32921. })(BABYLON || (BABYLON = {}));
  32922. var BABYLON;
  32923. (function (BABYLON) {
  32924. var Sound = (function () {
  32925. /**
  32926. * Create a sound and attach it to a scene
  32927. * @param name Name of your sound
  32928. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  32929. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  32930. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel
  32931. */
  32932. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  32933. var _this = this;
  32934. this.autoplay = false;
  32935. this.loop = false;
  32936. this.useCustomAttenuation = false;
  32937. this.spatialSound = false;
  32938. this.refDistance = 1;
  32939. this.rolloffFactor = 1;
  32940. this.maxDistance = 100;
  32941. this.distanceModel = "linear";
  32942. this._panningModel = "equalpower";
  32943. this._playbackRate = 1;
  32944. this._startTime = 0;
  32945. this._startOffset = 0;
  32946. this._position = BABYLON.Vector3.Zero();
  32947. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  32948. this._volume = 1;
  32949. this._isLoaded = false;
  32950. this._isReadyToPlay = false;
  32951. this.isPlaying = false;
  32952. this.isPaused = false;
  32953. this._isDirectional = false;
  32954. // Used if you'd like to create a directional sound.
  32955. // If not set, the sound will be omnidirectional
  32956. this._coneInnerAngle = 360;
  32957. this._coneOuterAngle = 360;
  32958. this._coneOuterGain = 0;
  32959. this._isOutputConnected = false;
  32960. this.name = name;
  32961. this._scene = scene;
  32962. this._readyToPlayCallback = readyToPlayCallback;
  32963. // Default custom attenuation function is a linear attenuation
  32964. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  32965. if (currentDistance < maxDistance) {
  32966. return currentVolume * (1 - currentDistance / maxDistance);
  32967. }
  32968. else {
  32969. return 0;
  32970. }
  32971. };
  32972. if (options) {
  32973. this.autoplay = options.autoplay || false;
  32974. this.loop = options.loop || false;
  32975. // if volume === 0, we need another way to check this option
  32976. if (options.volume !== undefined) {
  32977. this._volume = options.volume;
  32978. }
  32979. this.spatialSound = options.spatialSound || false;
  32980. this.maxDistance = options.maxDistance || 100;
  32981. this.useCustomAttenuation = options.useCustomAttenuation || false;
  32982. this.rolloffFactor = options.rolloffFactor || 1;
  32983. this.refDistance = options.refDistance || 1;
  32984. this.distanceModel = options.distanceModel || "linear";
  32985. this._playbackRate = options.playbackRate || 1;
  32986. }
  32987. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  32988. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  32989. this._soundGain.gain.value = this._volume;
  32990. this._inputAudioNode = this._soundGain;
  32991. this._ouputAudioNode = this._soundGain;
  32992. if (this.spatialSound) {
  32993. this._createSpatialParameters();
  32994. }
  32995. this._scene.mainSoundTrack.AddSound(this);
  32996. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  32997. if (urlOrArrayBuffer) {
  32998. // If it's an URL
  32999. if (typeof (urlOrArrayBuffer) === "string") {
  33000. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, null, true);
  33001. }
  33002. else {
  33003. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  33004. this._soundLoaded(urlOrArrayBuffer);
  33005. }
  33006. else {
  33007. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  33008. }
  33009. }
  33010. }
  33011. }
  33012. else {
  33013. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  33014. this._scene.mainSoundTrack.AddSound(this);
  33015. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  33016. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  33017. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  33018. }
  33019. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  33020. if (this._readyToPlayCallback) {
  33021. window.setTimeout(function () {
  33022. _this._readyToPlayCallback();
  33023. }, 1000);
  33024. }
  33025. }
  33026. }
  33027. Sound.prototype.dispose = function () {
  33028. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  33029. if (this.isPlaying) {
  33030. this.stop();
  33031. }
  33032. this._isReadyToPlay = false;
  33033. if (this.soundTrackId === -1) {
  33034. this._scene.mainSoundTrack.RemoveSound(this);
  33035. }
  33036. else {
  33037. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  33038. }
  33039. if (this._soundGain) {
  33040. this._soundGain.disconnect();
  33041. this._soundGain = null;
  33042. }
  33043. if (this._soundPanner) {
  33044. this._soundPanner.disconnect();
  33045. this._soundPanner = null;
  33046. }
  33047. if (this._soundSource) {
  33048. this._soundSource.disconnect();
  33049. this._soundSource = null;
  33050. }
  33051. this._audioBuffer = null;
  33052. if (this._connectedMesh) {
  33053. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  33054. this._connectedMesh = null;
  33055. }
  33056. }
  33057. };
  33058. Sound.prototype._soundLoaded = function (audioData) {
  33059. var _this = this;
  33060. this._isLoaded = true;
  33061. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  33062. _this._audioBuffer = buffer;
  33063. _this._isReadyToPlay = true;
  33064. if (_this.autoplay) {
  33065. _this.play();
  33066. }
  33067. if (_this._readyToPlayCallback) {
  33068. _this._readyToPlayCallback();
  33069. }
  33070. }, function () { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name); });
  33071. };
  33072. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  33073. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33074. this._audioBuffer = audioBuffer;
  33075. this._isReadyToPlay = true;
  33076. }
  33077. };
  33078. Sound.prototype.updateOptions = function (options) {
  33079. if (options) {
  33080. this.loop = options.loop || this.loop;
  33081. this.maxDistance = options.maxDistance || this.maxDistance;
  33082. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  33083. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  33084. this.refDistance = options.refDistance || this.refDistance;
  33085. this.distanceModel = options.distanceModel || this.distanceModel;
  33086. this._playbackRate = options.playbackRate || this._playbackRate;
  33087. this._updateSpatialParameters();
  33088. if (this.isPlaying) {
  33089. this._soundSource.playbackRate.value = this._playbackRate;
  33090. }
  33091. }
  33092. };
  33093. Sound.prototype._createSpatialParameters = function () {
  33094. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33095. if (this._scene.headphone) {
  33096. this._panningModel = "HRTF";
  33097. }
  33098. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  33099. this._updateSpatialParameters();
  33100. this._soundPanner.connect(this._ouputAudioNode);
  33101. this._inputAudioNode = this._soundPanner;
  33102. }
  33103. };
  33104. Sound.prototype._updateSpatialParameters = function () {
  33105. if (this.spatialSound) {
  33106. if (this.useCustomAttenuation) {
  33107. // Tricks to disable in a way embedded Web Audio attenuation
  33108. this._soundPanner.distanceModel = "linear";
  33109. this._soundPanner.maxDistance = Number.MAX_VALUE;
  33110. this._soundPanner.refDistance = 1;
  33111. this._soundPanner.rolloffFactor = 1;
  33112. this._soundPanner.panningModel = this._panningModel;
  33113. }
  33114. else {
  33115. this._soundPanner.distanceModel = this.distanceModel;
  33116. this._soundPanner.maxDistance = this.maxDistance;
  33117. this._soundPanner.refDistance = this.refDistance;
  33118. this._soundPanner.rolloffFactor = this.rolloffFactor;
  33119. this._soundPanner.panningModel = this._panningModel;
  33120. }
  33121. }
  33122. };
  33123. Sound.prototype.switchPanningModelToHRTF = function () {
  33124. this._panningModel = "HRTF";
  33125. this._switchPanningModel();
  33126. };
  33127. Sound.prototype.switchPanningModelToEqualPower = function () {
  33128. this._panningModel = "equalpower";
  33129. this._switchPanningModel();
  33130. };
  33131. Sound.prototype._switchPanningModel = function () {
  33132. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  33133. this._soundPanner.panningModel = this._panningModel;
  33134. }
  33135. };
  33136. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  33137. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33138. if (this._isOutputConnected) {
  33139. this._ouputAudioNode.disconnect();
  33140. }
  33141. this._ouputAudioNode.connect(soundTrackAudioNode);
  33142. this._isOutputConnected = true;
  33143. }
  33144. };
  33145. /**
  33146. * Transform this sound into a directional source
  33147. * @param coneInnerAngle Size of the inner cone in degree
  33148. * @param coneOuterAngle Size of the outer cone in degree
  33149. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  33150. */
  33151. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  33152. if (coneOuterAngle < coneInnerAngle) {
  33153. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  33154. return;
  33155. }
  33156. this._coneInnerAngle = coneInnerAngle;
  33157. this._coneOuterAngle = coneOuterAngle;
  33158. this._coneOuterGain = coneOuterGain;
  33159. this._isDirectional = true;
  33160. if (this.isPlaying && this.loop) {
  33161. this.stop();
  33162. this.play();
  33163. }
  33164. };
  33165. Sound.prototype.setPosition = function (newPosition) {
  33166. this._position = newPosition;
  33167. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  33168. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  33169. }
  33170. };
  33171. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  33172. this._localDirection = newLocalDirection;
  33173. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  33174. this._updateDirection();
  33175. }
  33176. };
  33177. Sound.prototype._updateDirection = function () {
  33178. var mat = this._connectedMesh.getWorldMatrix();
  33179. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  33180. direction.normalize();
  33181. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  33182. };
  33183. Sound.prototype.updateDistanceFromListener = function () {
  33184. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  33185. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  33186. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  33187. }
  33188. };
  33189. Sound.prototype.setAttenuationFunction = function (callback) {
  33190. this._customAttenuationFunction = callback;
  33191. };
  33192. /**
  33193. * Play the sound
  33194. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  33195. */
  33196. Sound.prototype.play = function (time) {
  33197. var _this = this;
  33198. if (this._isReadyToPlay && this._scene.audioEnabled) {
  33199. try {
  33200. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  33201. if (!this._soundSource) {
  33202. if (this.spatialSound) {
  33203. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  33204. if (this._isDirectional) {
  33205. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  33206. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  33207. this._soundPanner.coneOuterGain = this._coneOuterGain;
  33208. if (this._connectedMesh) {
  33209. this._updateDirection();
  33210. }
  33211. else {
  33212. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  33213. }
  33214. }
  33215. }
  33216. }
  33217. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  33218. this._soundSource.buffer = this._audioBuffer;
  33219. this._soundSource.connect(this._inputAudioNode);
  33220. this._soundSource.loop = this.loop;
  33221. this._soundSource.playbackRate.value = this._playbackRate;
  33222. this._startTime = startTime;
  33223. this._soundSource.onended = function () { _this._onended(); };
  33224. this._soundSource.start(this._startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  33225. this.isPlaying = true;
  33226. this.isPaused = false;
  33227. }
  33228. catch (ex) {
  33229. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  33230. }
  33231. }
  33232. };
  33233. Sound.prototype._onended = function () {
  33234. this.isPlaying = false;
  33235. if (this.onended) {
  33236. this.onended();
  33237. }
  33238. };
  33239. /**
  33240. * Stop the sound
  33241. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  33242. */
  33243. Sound.prototype.stop = function (time) {
  33244. if (this.isPlaying) {
  33245. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  33246. this._soundSource.stop(stopTime);
  33247. this.isPlaying = false;
  33248. }
  33249. };
  33250. Sound.prototype.pause = function () {
  33251. if (this.isPlaying) {
  33252. this.stop(0);
  33253. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  33254. this.isPaused = true;
  33255. }
  33256. };
  33257. Sound.prototype.setVolume = function (newVolume, time) {
  33258. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33259. if (time) {
  33260. this._soundGain.gain.linearRampToValueAtTime(this._volume, BABYLON.Engine.audioEngine.audioContext.currentTime);
  33261. this._soundGain.gain.linearRampToValueAtTime(newVolume, time);
  33262. }
  33263. else {
  33264. this._soundGain.gain.value = newVolume;
  33265. }
  33266. }
  33267. this._volume = newVolume;
  33268. };
  33269. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  33270. this._playbackRate = newPlaybackRate;
  33271. if (this.isPlaying) {
  33272. this._soundSource.playbackRate.value = this._playbackRate;
  33273. }
  33274. };
  33275. Sound.prototype.getVolume = function () {
  33276. return this._volume;
  33277. };
  33278. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  33279. var _this = this;
  33280. this._connectedMesh = meshToConnectTo;
  33281. if (!this.spatialSound) {
  33282. this.spatialSound = true;
  33283. this._createSpatialParameters();
  33284. if (this.isPlaying && this.loop) {
  33285. this.stop();
  33286. this.play();
  33287. }
  33288. }
  33289. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  33290. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  33291. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  33292. };
  33293. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  33294. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  33295. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  33296. this._updateDirection();
  33297. }
  33298. };
  33299. return Sound;
  33300. })();
  33301. BABYLON.Sound = Sound;
  33302. })(BABYLON || (BABYLON = {}));
  33303. var BABYLON;
  33304. (function (BABYLON) {
  33305. var SoundTrack = (function () {
  33306. function SoundTrack(scene, options) {
  33307. this.id = -1;
  33308. this._isMainTrack = false;
  33309. this._isInitialized = false;
  33310. this._scene = scene;
  33311. this.soundCollection = new Array();
  33312. this._options = options;
  33313. if (!this._isMainTrack) {
  33314. this._scene.soundTracks.push(this);
  33315. this.id = this._scene.soundTracks.length - 1;
  33316. }
  33317. }
  33318. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  33319. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33320. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  33321. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  33322. if (this._options) {
  33323. if (this._options.volume) {
  33324. this._outputAudioNode.gain.value = this._options.volume;
  33325. }
  33326. if (this._options.mainTrack) {
  33327. this._isMainTrack = this._options.mainTrack;
  33328. }
  33329. }
  33330. this._isInitialized = true;
  33331. }
  33332. };
  33333. SoundTrack.prototype.dispose = function () {
  33334. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33335. if (this._connectedAnalyser) {
  33336. this._connectedAnalyser.stopDebugCanvas();
  33337. }
  33338. while (this.soundCollection.length) {
  33339. this.soundCollection[0].dispose();
  33340. }
  33341. if (this._outputAudioNode) {
  33342. this._outputAudioNode.disconnect();
  33343. }
  33344. this._outputAudioNode = null;
  33345. }
  33346. };
  33347. SoundTrack.prototype.AddSound = function (sound) {
  33348. if (!this._isInitialized) {
  33349. this._initializeSoundTrackAudioGraph();
  33350. }
  33351. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33352. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  33353. }
  33354. if (sound.soundTrackId) {
  33355. if (sound.soundTrackId === -1) {
  33356. this._scene.mainSoundTrack.RemoveSound(sound);
  33357. }
  33358. else {
  33359. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  33360. }
  33361. }
  33362. this.soundCollection.push(sound);
  33363. sound.soundTrackId = this.id;
  33364. };
  33365. SoundTrack.prototype.RemoveSound = function (sound) {
  33366. var index = this.soundCollection.indexOf(sound);
  33367. if (index !== -1) {
  33368. this.soundCollection.splice(index, 1);
  33369. }
  33370. };
  33371. SoundTrack.prototype.setVolume = function (newVolume) {
  33372. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33373. this._outputAudioNode.gain.value = newVolume;
  33374. }
  33375. };
  33376. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  33377. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33378. for (var i = 0; i < this.soundCollection.length; i++) {
  33379. this.soundCollection[i].switchPanningModelToHRTF();
  33380. }
  33381. }
  33382. };
  33383. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  33384. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33385. for (var i = 0; i < this.soundCollection.length; i++) {
  33386. this.soundCollection[i].switchPanningModelToEqualPower();
  33387. }
  33388. }
  33389. };
  33390. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  33391. if (this._connectedAnalyser) {
  33392. this._connectedAnalyser.stopDebugCanvas();
  33393. }
  33394. this._connectedAnalyser = analyser;
  33395. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33396. this._outputAudioNode.disconnect();
  33397. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  33398. }
  33399. };
  33400. return SoundTrack;
  33401. })();
  33402. BABYLON.SoundTrack = SoundTrack;
  33403. })(BABYLON || (BABYLON = {}));
  33404. var BABYLON;
  33405. (function (BABYLON) {
  33406. var DepthRenderer = (function () {
  33407. function DepthRenderer(scene, type) {
  33408. var _this = this;
  33409. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  33410. this._viewMatrix = BABYLON.Matrix.Zero();
  33411. this._projectionMatrix = BABYLON.Matrix.Zero();
  33412. this._transformMatrix = BABYLON.Matrix.Zero();
  33413. this._worldViewProjection = BABYLON.Matrix.Zero();
  33414. this._scene = scene;
  33415. var engine = scene.getEngine();
  33416. // Render target
  33417. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  33418. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33419. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33420. this._depthMap.refreshRate = 1;
  33421. this._depthMap.renderParticles = false;
  33422. this._depthMap.renderList = null;
  33423. // set default depth value to 1.0 (far away)
  33424. this._depthMap.onClear = function (engine) {
  33425. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  33426. };
  33427. // Custom render function
  33428. var renderSubMesh = function (subMesh) {
  33429. var mesh = subMesh.getRenderingMesh();
  33430. var scene = _this._scene;
  33431. var engine = scene.getEngine();
  33432. // Culling
  33433. engine.setState(subMesh.getMaterial().backFaceCulling);
  33434. // Managing instances
  33435. var batch = mesh._getInstancesRenderList(subMesh._id);
  33436. if (batch.mustReturn) {
  33437. return;
  33438. }
  33439. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  33440. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  33441. engine.enableEffect(_this._effect);
  33442. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  33443. var material = subMesh.getMaterial();
  33444. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  33445. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  33446. // Alpha test
  33447. if (material && material.needAlphaTesting()) {
  33448. var alphaTexture = material.getAlphaTestTexture();
  33449. _this._effect.setTexture("diffuseSampler", alphaTexture);
  33450. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  33451. }
  33452. // Bones
  33453. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  33454. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  33455. }
  33456. // Draw
  33457. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  33458. }
  33459. };
  33460. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  33461. var index;
  33462. for (index = 0; index < opaqueSubMeshes.length; index++) {
  33463. renderSubMesh(opaqueSubMeshes.data[index]);
  33464. }
  33465. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  33466. renderSubMesh(alphaTestSubMeshes.data[index]);
  33467. }
  33468. };
  33469. }
  33470. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  33471. var defines = [];
  33472. var attribs = [BABYLON.VertexBuffer.PositionKind];
  33473. var mesh = subMesh.getMesh();
  33474. var scene = mesh.getScene();
  33475. var material = subMesh.getMaterial();
  33476. // Alpha test
  33477. if (material && material.needAlphaTesting()) {
  33478. defines.push("#define ALPHATEST");
  33479. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33480. attribs.push(BABYLON.VertexBuffer.UVKind);
  33481. defines.push("#define UV1");
  33482. }
  33483. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  33484. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  33485. defines.push("#define UV2");
  33486. }
  33487. }
  33488. // Bones
  33489. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  33490. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33491. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33492. defines.push("#define BONES");
  33493. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  33494. }
  33495. // Instances
  33496. if (useInstances) {
  33497. defines.push("#define INSTANCES");
  33498. attribs.push("world0");
  33499. attribs.push("world1");
  33500. attribs.push("world2");
  33501. attribs.push("world3");
  33502. }
  33503. // Get correct effect
  33504. var join = defines.join("\n");
  33505. if (this._cachedDefines !== join) {
  33506. this._cachedDefines = join;
  33507. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  33508. }
  33509. return this._effect.isReady();
  33510. };
  33511. DepthRenderer.prototype.getDepthMap = function () {
  33512. return this._depthMap;
  33513. };
  33514. // Methods
  33515. DepthRenderer.prototype.dispose = function () {
  33516. this._depthMap.dispose();
  33517. };
  33518. return DepthRenderer;
  33519. })();
  33520. BABYLON.DepthRenderer = DepthRenderer;
  33521. })(BABYLON || (BABYLON = {}));
  33522. var BABYLON;
  33523. (function (BABYLON) {
  33524. var SSAORenderingPipeline = (function (_super) {
  33525. __extends(SSAORenderingPipeline, _super);
  33526. /**
  33527. * @constructor
  33528. * @param {string} name - The rendering pipeline name
  33529. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  33530. * @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 }
  33531. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  33532. */
  33533. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  33534. var _this = this;
  33535. _super.call(this, scene.getEngine(), name);
  33536. // Members
  33537. /**
  33538. * The PassPostProcess id in the pipeline that contains the original scene color
  33539. * @type {string}
  33540. */
  33541. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  33542. /**
  33543. * The SSAO PostProcess id in the pipeline
  33544. * @type {string}
  33545. */
  33546. this.SSAORenderEffect = "SSAORenderEffect";
  33547. /**
  33548. * The horizontal blur PostProcess id in the pipeline
  33549. * @type {string}
  33550. */
  33551. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  33552. /**
  33553. * The vertical blur PostProcess id in the pipeline
  33554. * @type {string}
  33555. */
  33556. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  33557. /**
  33558. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  33559. * @type {string}
  33560. */
  33561. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  33562. /**
  33563. * The output strength of the SSAO post-process. Default value is 1.0.
  33564. * @type {number}
  33565. */
  33566. this.totalStrength = 1.0;
  33567. /**
  33568. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0002
  33569. * @type {number}
  33570. */
  33571. this.radius = 0.0002;
  33572. /**
  33573. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  33574. * Must not be equal to fallOff and superior to fallOff.
  33575. * Default value is 0.0075
  33576. * @type {number}
  33577. */
  33578. this.area = 0.0075;
  33579. /**
  33580. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  33581. * Must not be equal to area and inferior to area.
  33582. * Default value is 0.0002
  33583. * @type {number}
  33584. */
  33585. this.fallOff = 0.0002;
  33586. this._firstUpdate = true;
  33587. this._scene = scene;
  33588. // Set up assets
  33589. this._createRandomTexture();
  33590. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  33591. var ssaoRatio = ratio.ssaoRatio || ratio;
  33592. var combineRatio = ratio.combineRatio || ratio;
  33593. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  33594. this._createSSAOPostProcess(ssaoRatio);
  33595. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(2.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  33596. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 2.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  33597. this._createSSAOCombinePostProcess(combineRatio);
  33598. // Set up pipeline
  33599. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  33600. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  33601. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  33602. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  33603. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  33604. // Finish
  33605. scene.postProcessRenderPipelineManager.addPipeline(this);
  33606. if (cameras)
  33607. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  33608. }
  33609. // Public Methods
  33610. /**
  33611. * Returns the horizontal blur PostProcess
  33612. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  33613. */
  33614. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  33615. return this._blurHPostProcess;
  33616. };
  33617. /**
  33618. * Returns the vertical blur PostProcess
  33619. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  33620. */
  33621. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  33622. return this._blurVPostProcess;
  33623. };
  33624. /**
  33625. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  33626. */
  33627. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  33628. if (disableDepthRender === void 0) { disableDepthRender = false; }
  33629. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  33630. this._originalColorPostProcess = undefined;
  33631. this._ssaoPostProcess = undefined;
  33632. this._blurHPostProcess = undefined;
  33633. this._blurVPostProcess = undefined;
  33634. this._ssaoCombinePostProcess = undefined;
  33635. this._randomTexture.dispose();
  33636. if (disableDepthRender)
  33637. this._scene.disableDepthRenderer();
  33638. };
  33639. // Private Methods
  33640. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  33641. var _this = this;
  33642. var sampleSphere = [
  33643. 0.5381, 0.1856, -0.4319,
  33644. 0.1379, 0.2486, 0.4430,
  33645. 0.3371, 0.5679, -0.0057,
  33646. -0.6999, -0.0451, -0.0019,
  33647. 0.0689, -0.1598, -0.8547,
  33648. 0.0560, 0.0069, -0.1843,
  33649. -0.0146, 0.1402, 0.0762,
  33650. 0.0100, -0.1924, -0.0344,
  33651. -0.3577, -0.5301, -0.4358,
  33652. -0.3169, 0.1063, 0.0158,
  33653. 0.0103, -0.5869, 0.0046,
  33654. -0.0897, -0.4940, 0.3287,
  33655. 0.7119, -0.0154, -0.0918,
  33656. -0.0533, 0.0596, -0.5411,
  33657. 0.0352, -0.0631, 0.5460,
  33658. -0.4776, 0.2847, -0.0271
  33659. ];
  33660. var samplesFactor = 1.0 / 16.0;
  33661. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", ["sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius", "area", "fallOff"], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  33662. this._ssaoPostProcess.onApply = function (effect) {
  33663. if (_this._firstUpdate) {
  33664. effect.setArray3("sampleSphere", sampleSphere);
  33665. effect.setFloat("samplesFactor", samplesFactor);
  33666. effect.setFloat("randTextureTiles", 4.0 / ratio);
  33667. _this._firstUpdate = false;
  33668. }
  33669. effect.setFloat("totalStrength", _this.totalStrength);
  33670. effect.setFloat("radius", _this.radius);
  33671. effect.setFloat("area", _this.area);
  33672. effect.setFloat("fallOff", _this.fallOff);
  33673. effect.setTexture("textureSampler", _this._depthTexture);
  33674. effect.setTexture("randomSampler", _this._randomTexture);
  33675. };
  33676. };
  33677. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  33678. var _this = this;
  33679. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  33680. this._ssaoCombinePostProcess.onApply = function (effect) {
  33681. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  33682. };
  33683. };
  33684. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  33685. var size = 512;
  33686. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  33687. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  33688. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  33689. var context = this._randomTexture.getContext();
  33690. var rand = function (min, max) {
  33691. return Math.random() * (max - min) + min;
  33692. };
  33693. for (var x = 0; x < size; x++) {
  33694. for (var y = 0; y < size; y++) {
  33695. var randVector = BABYLON.Vector3.Zero();
  33696. randVector.x = Math.floor(rand(0.0, 1.0) * 255);
  33697. randVector.y = Math.floor(rand(0.0, 1.0) * 255);
  33698. randVector.z = Math.floor(rand(0.0, 1.0) * 255);
  33699. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  33700. context.fillRect(x, y, 1, 1);
  33701. }
  33702. }
  33703. this._randomTexture.update(false);
  33704. };
  33705. return SSAORenderingPipeline;
  33706. })(BABYLON.PostProcessRenderPipeline);
  33707. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  33708. })(BABYLON || (BABYLON = {}));
  33709. var BABYLON;
  33710. (function (BABYLON) {
  33711. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  33712. var VolumetricLightScatteringPostProcess = (function (_super) {
  33713. __extends(VolumetricLightScatteringPostProcess, _super);
  33714. /**
  33715. * @constructor
  33716. * @param {string} name - The post-process name
  33717. * @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)
  33718. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  33719. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  33720. * @param {number} samples - The post-process quality, default 100
  33721. * @param {number} samplingMode - The post-process filtering mode
  33722. * @param {BABYLON.Engine} engine - The babylon engine
  33723. * @param {boolean} reusable - If the post-process is reusable
  33724. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  33725. */
  33726. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  33727. var _this = this;
  33728. if (samples === void 0) { samples = 100; }
  33729. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  33730. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  33731. this._screenCoordinates = BABYLON.Vector2.Zero();
  33732. /**
  33733. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  33734. * @type {boolean}
  33735. */
  33736. this.useCustomMeshPosition = false;
  33737. /**
  33738. * If the post-process should inverse the light scattering direction
  33739. * @type {boolean}
  33740. */
  33741. this.invert = true;
  33742. /**
  33743. * Set to true to use the diffuseColor instead of the diffuseTexture
  33744. * @type {boolean}
  33745. */
  33746. this.useDiffuseColor = false;
  33747. /**
  33748. * Array containing the excluded meshes not rendered in the internal pass
  33749. */
  33750. this.excludedMeshes = new Array();
  33751. /**
  33752. * Controls the overall intensity of the post-process
  33753. * @type {number}
  33754. */
  33755. this.exposure = 0.3;
  33756. /**
  33757. * Dissipates each sample's contribution in range [0, 1]
  33758. * @type {number}
  33759. */
  33760. this.decay = 0.96815;
  33761. /**
  33762. * Controls the overall intensity of each sample
  33763. * @type {number}
  33764. */
  33765. this.weight = 0.58767;
  33766. /**
  33767. * Controls the density of each sample
  33768. * @type {number}
  33769. */
  33770. this.density = 0.926;
  33771. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  33772. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  33773. // Configure mesh
  33774. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  33775. // Configure
  33776. this._createPass(scene, ratio.passRatio || ratio);
  33777. this.onApply = function (effect) {
  33778. _this._updateMeshScreenCoordinates(scene);
  33779. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  33780. effect.setFloat("exposure", _this.exposure);
  33781. effect.setFloat("decay", _this.decay);
  33782. effect.setFloat("weight", _this.weight);
  33783. effect.setFloat("density", _this.density);
  33784. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  33785. };
  33786. }
  33787. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  33788. var mesh = subMesh.getMesh();
  33789. var defines = [];
  33790. var attribs = [BABYLON.VertexBuffer.PositionKind];
  33791. var material = subMesh.getMaterial();
  33792. var needUV = false;
  33793. // Render this.mesh as default
  33794. if (mesh === this.mesh) {
  33795. if (this.useDiffuseColor) {
  33796. defines.push("#define DIFFUSE_COLOR_RENDER");
  33797. }
  33798. else if (material) {
  33799. if (material.diffuseTexture !== undefined) {
  33800. defines.push("#define BASIC_RENDER");
  33801. }
  33802. else {
  33803. defines.push("#define DIFFUSE_COLOR_RENDER");
  33804. }
  33805. }
  33806. defines.push("#define NEED_UV");
  33807. needUV = true;
  33808. }
  33809. // Alpha test
  33810. if (material) {
  33811. if (material.needAlphaTesting()) {
  33812. defines.push("#define ALPHATEST");
  33813. }
  33814. if (material.opacityTexture !== undefined) {
  33815. defines.push("#define OPACITY");
  33816. if (material.opacityTexture.getAlphaFromRGB) {
  33817. defines.push("#define OPACITYRGB");
  33818. }
  33819. if (!needUV) {
  33820. defines.push("#define NEED_UV");
  33821. }
  33822. }
  33823. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33824. attribs.push(BABYLON.VertexBuffer.UVKind);
  33825. defines.push("#define UV1");
  33826. }
  33827. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  33828. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  33829. defines.push("#define UV2");
  33830. }
  33831. }
  33832. // Bones
  33833. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  33834. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33835. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33836. defines.push("#define BONES");
  33837. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  33838. }
  33839. // Instances
  33840. if (useInstances) {
  33841. defines.push("#define INSTANCES");
  33842. attribs.push("world0");
  33843. attribs.push("world1");
  33844. attribs.push("world2");
  33845. attribs.push("world3");
  33846. }
  33847. // Get correct effect
  33848. var join = defines.join("\n");
  33849. if (this._cachedDefines !== join) {
  33850. this._cachedDefines = join;
  33851. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "opacityLevel", "color"], ["diffuseSampler", "opacitySampler"], join);
  33852. }
  33853. return this._volumetricLightScatteringPass.isReady();
  33854. };
  33855. /**
  33856. * Sets the new light position for light scattering effect
  33857. * @param {BABYLON.Vector3} The new custom light position
  33858. */
  33859. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  33860. this._customMeshPosition = position;
  33861. };
  33862. /**
  33863. * Returns the light position for light scattering effect
  33864. * @return {BABYLON.Vector3} The custom light position
  33865. */
  33866. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  33867. return this._customMeshPosition;
  33868. };
  33869. /**
  33870. * Disposes the internal assets and detaches the post-process from the camera
  33871. */
  33872. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  33873. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  33874. if (rttIndex !== -1) {
  33875. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  33876. }
  33877. this._volumetricLightScatteringRTT.dispose();
  33878. _super.prototype.dispose.call(this, camera);
  33879. };
  33880. /**
  33881. * Returns the render target texture used by the post-process
  33882. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  33883. */
  33884. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  33885. return this._volumetricLightScatteringRTT;
  33886. };
  33887. // Private methods
  33888. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  33889. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  33890. return true;
  33891. }
  33892. return false;
  33893. };
  33894. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  33895. var _this = this;
  33896. var engine = scene.getEngine();
  33897. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  33898. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33899. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33900. this._volumetricLightScatteringRTT.renderList = null;
  33901. this._volumetricLightScatteringRTT.renderParticles = false;
  33902. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  33903. // Custom render function for submeshes
  33904. var renderSubMesh = function (subMesh) {
  33905. var mesh = subMesh.getRenderingMesh();
  33906. if (_this._meshExcluded(mesh)) {
  33907. return;
  33908. }
  33909. var scene = mesh.getScene();
  33910. var engine = scene.getEngine();
  33911. // Culling
  33912. engine.setState(subMesh.getMaterial().backFaceCulling);
  33913. // Managing instances
  33914. var batch = mesh._getInstancesRenderList(subMesh._id);
  33915. if (batch.mustReturn) {
  33916. return;
  33917. }
  33918. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  33919. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  33920. engine.enableEffect(_this._volumetricLightScatteringPass);
  33921. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  33922. var material = subMesh.getMaterial();
  33923. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  33924. // Alpha test
  33925. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  33926. var alphaTexture = material.getAlphaTestTexture();
  33927. if ((_this.useDiffuseColor || alphaTexture === undefined) && mesh === _this.mesh) {
  33928. _this._volumetricLightScatteringPass.setColor3("color", material.diffuseColor);
  33929. }
  33930. if (material.needAlphaTesting() || (mesh === _this.mesh && alphaTexture && !_this.useDiffuseColor)) {
  33931. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  33932. if (alphaTexture) {
  33933. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  33934. }
  33935. }
  33936. if (material.opacityTexture !== undefined) {
  33937. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  33938. _this._volumetricLightScatteringPass.setFloat("opacityLevel", material.opacityTexture.level);
  33939. }
  33940. }
  33941. // Bones
  33942. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  33943. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  33944. }
  33945. // Draw
  33946. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  33947. }
  33948. };
  33949. // Render target texture callbacks
  33950. var savedSceneClearColor;
  33951. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  33952. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  33953. savedSceneClearColor = scene.clearColor;
  33954. scene.clearColor = sceneClearColor;
  33955. };
  33956. this._volumetricLightScatteringRTT.onAfterRender = function () {
  33957. scene.clearColor = savedSceneClearColor;
  33958. };
  33959. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  33960. var engine = scene.getEngine();
  33961. var index;
  33962. for (index = 0; index < opaqueSubMeshes.length; index++) {
  33963. renderSubMesh(opaqueSubMeshes.data[index]);
  33964. }
  33965. engine.setAlphaTesting(true);
  33966. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  33967. renderSubMesh(alphaTestSubMeshes.data[index]);
  33968. }
  33969. engine.setAlphaTesting(false);
  33970. if (transparentSubMeshes.length) {
  33971. // Sort sub meshes
  33972. for (index = 0; index < transparentSubMeshes.length; index++) {
  33973. var submesh = transparentSubMeshes.data[index];
  33974. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  33975. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  33976. }
  33977. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  33978. sortedArray.sort(function (a, b) {
  33979. // Alpha index first
  33980. if (a._alphaIndex > b._alphaIndex) {
  33981. return 1;
  33982. }
  33983. if (a._alphaIndex < b._alphaIndex) {
  33984. return -1;
  33985. }
  33986. // Then distance to camera
  33987. if (a._distanceToCamera < b._distanceToCamera) {
  33988. return 1;
  33989. }
  33990. if (a._distanceToCamera > b._distanceToCamera) {
  33991. return -1;
  33992. }
  33993. return 0;
  33994. });
  33995. // Render sub meshes
  33996. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  33997. for (index = 0; index < sortedArray.length; index++) {
  33998. renderSubMesh(sortedArray[index]);
  33999. }
  34000. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  34001. }
  34002. };
  34003. };
  34004. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  34005. var transform = scene.getTransformMatrix();
  34006. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : this.mesh.position, BABYLON.Matrix.Identity(), transform, this._viewPort);
  34007. this._screenCoordinates.x = pos.x / this._viewPort.width;
  34008. this._screenCoordinates.y = pos.y / this._viewPort.height;
  34009. if (this.invert)
  34010. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  34011. };
  34012. // Static methods
  34013. /**
  34014. * Creates a default mesh for the Volumeric Light Scattering post-process
  34015. * @param {string} The mesh name
  34016. * @param {BABYLON.Scene} The scene where to create the mesh
  34017. * @return {BABYLON.Mesh} the default mesh
  34018. */
  34019. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  34020. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  34021. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  34022. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  34023. return mesh;
  34024. };
  34025. return VolumetricLightScatteringPostProcess;
  34026. })(BABYLON.PostProcess);
  34027. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  34028. })(BABYLON || (BABYLON = {}));
  34029. var BABYLON;
  34030. (function (BABYLON) {
  34031. var LensRenderingPipeline = (function (_super) {
  34032. __extends(LensRenderingPipeline, _super);
  34033. /**
  34034. * @constructor
  34035. *
  34036. * Effect parameters are as follow:
  34037. * {
  34038. * chromatic_aberration: number; // from 0 to x (1 for realism)
  34039. * edge_blur: number; // from 0 to x (1 for realism)
  34040. * distortion: number; // from 0 to x (1 for realism)
  34041. * grain_amount: number; // from 0 to 1
  34042. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  34043. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  34044. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  34045. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  34046. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  34047. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  34048. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  34049. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  34050. * }
  34051. * Note: if an effect parameter is unset, effect is disabled
  34052. *
  34053. * @param {string} name - The rendering pipeline name
  34054. * @param {object} parameters - An object containing all parameters (see above)
  34055. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  34056. * @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)
  34057. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  34058. */
  34059. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  34060. var _this = this;
  34061. if (ratio === void 0) { ratio = 1.0; }
  34062. _super.call(this, scene.getEngine(), name);
  34063. // Lens effects can be of the following:
  34064. // - chromatic aberration (slight shift of RGB colors)
  34065. // - blur on the edge of the lens
  34066. // - lens distortion
  34067. // - depth-of-field blur & highlights enhancing
  34068. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  34069. // - grain effect (noise or custom texture)
  34070. // Two additional texture samplers are needed:
  34071. // - depth map (for depth-of-field)
  34072. // - grain texture
  34073. /**
  34074. * The chromatic aberration PostProcess id in the pipeline
  34075. * @type {string}
  34076. */
  34077. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  34078. /**
  34079. * The highlights enhancing PostProcess id in the pipeline
  34080. * @type {string}
  34081. */
  34082. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  34083. /**
  34084. * The depth-of-field PostProcess id in the pipeline
  34085. * @type {string}
  34086. */
  34087. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  34088. this._scene = scene;
  34089. // Fetch texture samplers
  34090. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  34091. if (parameters.grain_texture) {
  34092. this._grainTexture = parameters.grain_texture;
  34093. }
  34094. else {
  34095. this._createGrainTexture();
  34096. }
  34097. // save parameters
  34098. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  34099. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  34100. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  34101. this._distortion = parameters.distortion ? parameters.distortion : 0;
  34102. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  34103. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  34104. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  34105. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  34106. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  34107. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  34108. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  34109. // Create effects
  34110. this._createChromaticAberrationPostProcess(ratio);
  34111. this._createHighlightsPostProcess(ratio);
  34112. this._createDepthOfFieldPostProcess(ratio / 4);
  34113. // Set up pipeline
  34114. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  34115. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  34116. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  34117. if (this._highlightsGain == -1) {
  34118. this._disableEffect(this.HighlightsEnhancingEffect, null);
  34119. }
  34120. // Finish
  34121. scene.postProcessRenderPipelineManager.addPipeline(this);
  34122. if (cameras) {
  34123. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  34124. }
  34125. }
  34126. // public methods (self explanatory)
  34127. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  34128. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  34129. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  34130. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  34131. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  34132. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  34133. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  34134. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  34135. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  34136. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  34137. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  34138. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  34139. LensRenderingPipeline.prototype.enablePentagonBokeh = function () { this._dofPentagon = true; };
  34140. LensRenderingPipeline.prototype.disablePentagonBokeh = function () { this._dofPentagon = false; };
  34141. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  34142. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  34143. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  34144. this._highlightsGain = amount;
  34145. };
  34146. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  34147. if (this._highlightsGain == -1) {
  34148. this._highlightsGain = 1.0;
  34149. }
  34150. this._highlightsThreshold = amount;
  34151. };
  34152. LensRenderingPipeline.prototype.disableHighlights = function () {
  34153. this._highlightsGain = -1;
  34154. };
  34155. /**
  34156. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  34157. */
  34158. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  34159. if (disableDepthRender === void 0) { disableDepthRender = false; }
  34160. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  34161. this._chromaticAberrationPostProcess = undefined;
  34162. this._highlightsPostProcess = undefined;
  34163. this._depthOfFieldPostProcess = undefined;
  34164. this._grainTexture.dispose();
  34165. if (disableDepthRender)
  34166. this._scene.disableDepthRenderer();
  34167. };
  34168. // colors shifting and distortion
  34169. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  34170. var _this = this;
  34171. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  34172. [], // samplers
  34173. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  34174. this._chromaticAberrationPostProcess.onApply = function (effect) {
  34175. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  34176. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  34177. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  34178. };
  34179. };
  34180. // highlights enhancing
  34181. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  34182. var _this = this;
  34183. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["pentagon", "gain", "threshold", "screen_width", "screen_height"], // uniforms
  34184. [], // samplers
  34185. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  34186. this._highlightsPostProcess.onApply = function (effect) {
  34187. effect.setFloat('gain', _this._highlightsGain);
  34188. effect.setFloat('threshold', _this._highlightsThreshold);
  34189. effect.setBool('pentagon', _this._dofPentagon);
  34190. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  34191. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  34192. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  34193. };
  34194. };
  34195. // colors shifting and distortion
  34196. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  34197. var _this = this;
  34198. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  34199. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  34200. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  34201. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  34202. this._depthOfFieldPostProcess.onApply = function (effect) {
  34203. effect.setTexture("depthSampler", _this._depthTexture);
  34204. effect.setTexture("grainSampler", _this._grainTexture);
  34205. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  34206. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  34207. effect.setFloat('grain_amount', _this._grainAmount);
  34208. effect.setBool('blur_noise', _this._blurNoise);
  34209. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  34210. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  34211. effect.setFloat('distortion', _this._distortion);
  34212. effect.setBool('dof_enabled', (_this._dofDistance != -1));
  34213. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  34214. effect.setFloat('aperture', _this._dofAperture);
  34215. effect.setFloat('darken', _this._dofDarken);
  34216. effect.setFloat('edge_blur', _this._edgeBlur);
  34217. effect.setBool('highlights', (_this._highlightsGain != -1));
  34218. effect.setFloat('near', _this._scene.activeCamera.minZ);
  34219. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  34220. };
  34221. };
  34222. // creates a black and white random noise texture, 512x512
  34223. LensRenderingPipeline.prototype._createGrainTexture = function () {
  34224. var size = 512;
  34225. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  34226. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  34227. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  34228. var context = this._grainTexture.getContext();
  34229. var rand = function (min, max) {
  34230. return Math.random() * (max - min) + min;
  34231. };
  34232. var value;
  34233. for (var x = 0; x < size; x++) {
  34234. for (var y = 0; y < size; y++) {
  34235. value = Math.floor(rand(0.42, 0.58) * 255);
  34236. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  34237. context.fillRect(x, y, 1, 1);
  34238. }
  34239. }
  34240. this._grainTexture.update(false);
  34241. };
  34242. return LensRenderingPipeline;
  34243. })(BABYLON.PostProcessRenderPipeline);
  34244. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  34245. })(BABYLON || (BABYLON = {}));
  34246. //
  34247. // This post-process allows the modification of rendered colors by using
  34248. // a 'look-up table' (LUT). This effect is also called Color Grading.
  34249. //
  34250. // The object needs to be provided an url to a texture containing the color
  34251. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  34252. // Use an image editing software to tweak the LUT to match your needs.
  34253. //
  34254. // For an example of a color LUT, see here:
  34255. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  34256. // For explanations on color grading, see here:
  34257. // http://udn.epicgames.com/Three/ColorGrading.html
  34258. //
  34259. var BABYLON;
  34260. (function (BABYLON) {
  34261. var ColorCorrectionPostProcess = (function (_super) {
  34262. __extends(ColorCorrectionPostProcess, _super);
  34263. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  34264. var _this = this;
  34265. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  34266. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  34267. this._colorTableTexture.anisotropicFilteringLevel = 1;
  34268. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34269. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34270. this.onApply = function (effect) {
  34271. effect.setTexture("colorTable", _this._colorTableTexture);
  34272. };
  34273. }
  34274. return ColorCorrectionPostProcess;
  34275. })(BABYLON.PostProcess);
  34276. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  34277. })(BABYLON || (BABYLON = {}));
  34278. var BABYLON;
  34279. (function (BABYLON) {
  34280. var AnaglyphFreeCamera = (function (_super) {
  34281. __extends(AnaglyphFreeCamera, _super);
  34282. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  34283. _super.call(this, name, position, scene);
  34284. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  34285. }
  34286. return AnaglyphFreeCamera;
  34287. })(BABYLON.FreeCamera);
  34288. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  34289. var AnaglyphArcRotateCamera = (function (_super) {
  34290. __extends(AnaglyphArcRotateCamera, _super);
  34291. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  34292. _super.call(this, name, alpha, beta, radius, target, scene);
  34293. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  34294. }
  34295. return AnaglyphArcRotateCamera;
  34296. })(BABYLON.ArcRotateCamera);
  34297. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  34298. var AnaglyphGamepadCamera = (function (_super) {
  34299. __extends(AnaglyphGamepadCamera, _super);
  34300. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  34301. _super.call(this, name, position, scene);
  34302. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  34303. }
  34304. return AnaglyphGamepadCamera;
  34305. })(BABYLON.GamepadCamera);
  34306. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  34307. var StereoscopicFreeCamera = (function (_super) {
  34308. __extends(StereoscopicFreeCamera, _super);
  34309. function StereoscopicFreeCamera(name, position, interaxialDistance, isSideBySide, scene) {
  34310. _super.call(this, name, position, scene);
  34311. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  34312. }
  34313. return StereoscopicFreeCamera;
  34314. })(BABYLON.FreeCamera);
  34315. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  34316. var StereoscopicArcRotateCamera = (function (_super) {
  34317. __extends(StereoscopicArcRotateCamera, _super);
  34318. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isSideBySide, scene) {
  34319. _super.call(this, name, alpha, beta, radius, target, scene);
  34320. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  34321. }
  34322. return StereoscopicArcRotateCamera;
  34323. })(BABYLON.ArcRotateCamera);
  34324. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  34325. var StereoscopicGamepadCamera = (function (_super) {
  34326. __extends(StereoscopicGamepadCamera, _super);
  34327. function StereoscopicGamepadCamera(name, position, interaxialDistance, isSideBySide, scene) {
  34328. _super.call(this, name, position, scene);
  34329. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  34330. }
  34331. return StereoscopicGamepadCamera;
  34332. })(BABYLON.GamepadCamera);
  34333. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  34334. })(BABYLON || (BABYLON = {}));
  34335. var BABYLON;
  34336. (function (BABYLON) {
  34337. var HDRRenderingPipeline = (function (_super) {
  34338. __extends(HDRRenderingPipeline, _super);
  34339. /**
  34340. * @constructor
  34341. * @param {string} name - The rendering pipeline name
  34342. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  34343. * @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)
  34344. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  34345. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  34346. */
  34347. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  34348. var _this = this;
  34349. if (originalPostProcess === void 0) { originalPostProcess = null; }
  34350. _super.call(this, scene.getEngine(), name);
  34351. /**
  34352. * Public members
  34353. */
  34354. // Gaussian Blur
  34355. /**
  34356. * Gaussian blur coefficient
  34357. * @type {number}
  34358. */
  34359. this.gaussCoeff = 0.3;
  34360. /**
  34361. * Gaussian blur mean
  34362. * @type {number}
  34363. */
  34364. this.gaussMean = 1.0;
  34365. /**
  34366. * Gaussian blur standard deviation
  34367. * @type {number}
  34368. */
  34369. this.gaussStandDev = 0.8;
  34370. // HDR
  34371. /**
  34372. * Exposure, controls the overall intensity of the pipeline
  34373. * @type {number}
  34374. */
  34375. this.exposure = 1.0;
  34376. /**
  34377. * Minimum luminance that the post-process can output. Luminance is >= 0
  34378. * @type {number}
  34379. */
  34380. this.minimumLuminance = 1.0;
  34381. /**
  34382. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  34383. * @type {number}
  34384. */
  34385. this.maximumLuminance = 1e20;
  34386. /**
  34387. * Increase rate for luminance: eye adaptation speed to dark
  34388. * @type {number}
  34389. */
  34390. this.luminanceIncreaserate = 0.5;
  34391. /**
  34392. * Decrease rate for luminance: eye adaptation speed to bright
  34393. * @type {number}
  34394. */
  34395. this.luminanceDecreaseRate = 0.5;
  34396. // Bright pass
  34397. /**
  34398. * Minimum luminance needed to compute HDR
  34399. * @type {number}
  34400. */
  34401. this.brightThreshold = 0.8;
  34402. this._needUpdate = true;
  34403. this._scene = scene;
  34404. // Bright pass
  34405. this._createBrightPassPostProcess(scene, ratio);
  34406. // Down sample X4
  34407. this._createDownSampleX4PostProcess(scene, ratio);
  34408. // Create gaussian blur post-processes
  34409. this._createGaussianBlurPostProcess(scene, ratio);
  34410. // Texture adder
  34411. this._createTextureAdderPostProcess(scene, ratio);
  34412. // Luminance generator
  34413. this._createLuminanceGeneratorPostProcess(scene);
  34414. // HDR
  34415. this._createHDRPostProcess(scene, ratio);
  34416. // Pass postprocess
  34417. if (originalPostProcess === null) {
  34418. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  34419. }
  34420. else {
  34421. this._originalPostProcess = originalPostProcess;
  34422. }
  34423. // Configure pipeline
  34424. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  34425. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  34426. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  34427. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  34428. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  34429. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  34430. var addDownSamplerPostProcess = function (id) {
  34431. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  34432. };
  34433. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  34434. addDownSamplerPostProcess(i);
  34435. }
  34436. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  34437. // Finish
  34438. scene.postProcessRenderPipelineManager.addPipeline(this);
  34439. if (cameras !== null) {
  34440. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  34441. }
  34442. this.update();
  34443. }
  34444. /**
  34445. * Tells the pipeline to update its post-processes
  34446. */
  34447. HDRRenderingPipeline.prototype.update = function () {
  34448. this._needUpdate = true;
  34449. };
  34450. /**
  34451. * Returns the current calculated luminance
  34452. */
  34453. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  34454. return this._hdrCurrentLuminance;
  34455. };
  34456. /**
  34457. * Returns the currently drawn luminance
  34458. */
  34459. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  34460. return this._hdrOutputLuminance;
  34461. };
  34462. /**
  34463. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  34464. */
  34465. HDRRenderingPipeline.prototype.dispose = function () {
  34466. this._originalPostProcess = undefined;
  34467. this._brightPassPostProcess = undefined;
  34468. this._downSampleX4PostProcess = undefined;
  34469. this._guassianBlurHPostProcess = undefined;
  34470. this._guassianBlurVPostProcess = undefined;
  34471. this._textureAdderPostProcess = undefined;
  34472. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  34473. this._downSamplePostProcesses[i] = undefined;
  34474. }
  34475. this._hdrPostProcess = undefined;
  34476. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  34477. };
  34478. /**
  34479. * Creates the HDR post-process and computes the luminance adaptation
  34480. */
  34481. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  34482. var _this = this;
  34483. var hdrLastLuminance = 0.0;
  34484. this._hdrOutputLuminance = -1.0;
  34485. this._hdrCurrentLuminance = 1.0;
  34486. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  34487. this._hdrPostProcess.onApply = function (effect) {
  34488. if (_this._hdrOutputLuminance < 0.0) {
  34489. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  34490. }
  34491. else {
  34492. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  34493. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  34494. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  34495. }
  34496. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  34497. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  34498. }
  34499. else {
  34500. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  34501. }
  34502. }
  34503. _this._hdrOutputLuminance = BABYLON.Tools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  34504. hdrLastLuminance += scene.getEngine().getDeltaTime();
  34505. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  34506. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  34507. effect.setFloat("exposure", _this.exposure);
  34508. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  34509. _this._needUpdate = false;
  34510. };
  34511. };
  34512. /**
  34513. * Texture Adder post-process
  34514. */
  34515. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  34516. var _this = this;
  34517. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  34518. this._textureAdderPostProcess.onApply = function (effect) {
  34519. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  34520. };
  34521. };
  34522. /**
  34523. * Down sample X4 post-process
  34524. */
  34525. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  34526. var _this = this;
  34527. var downSampleX4Offsets = new Array(32);
  34528. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  34529. this._downSampleX4PostProcess.onApply = function (effect) {
  34530. if (_this._needUpdate) {
  34531. var id = 0;
  34532. for (var i = -2; i < 2; i++) {
  34533. for (var j = -2; j < 2; j++) {
  34534. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  34535. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  34536. id += 2;
  34537. }
  34538. }
  34539. }
  34540. effect.setArray2("dsOffsets", downSampleX4Offsets);
  34541. };
  34542. };
  34543. /**
  34544. * Bright pass post-process
  34545. */
  34546. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  34547. var _this = this;
  34548. var brightOffsets = new Array(8);
  34549. var brightPassCallback = function (effect) {
  34550. if (_this._needUpdate) {
  34551. var sU = (1.0 / _this._brightPassPostProcess.width);
  34552. var sV = (1.0 / _this._brightPassPostProcess.height);
  34553. brightOffsets[0] = -0.5 * sU;
  34554. brightOffsets[1] = 0.5 * sV;
  34555. brightOffsets[2] = 0.5 * sU;
  34556. brightOffsets[3] = 0.5 * sV;
  34557. brightOffsets[4] = -0.5 * sU;
  34558. brightOffsets[5] = -0.5 * sV;
  34559. brightOffsets[6] = 0.5 * sU;
  34560. brightOffsets[7] = -0.5 * sV;
  34561. }
  34562. effect.setArray2("dsOffsets", brightOffsets);
  34563. effect.setFloat("brightThreshold", _this.brightThreshold);
  34564. };
  34565. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  34566. this._brightPassPostProcess.onApply = brightPassCallback;
  34567. };
  34568. /**
  34569. * Luminance generator. Creates the luminance post-process and down sample post-processes
  34570. */
  34571. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  34572. var _this = this;
  34573. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  34574. var luminanceOffsets = new Array(8);
  34575. var downSampleOffsets = new Array(18);
  34576. var halfDestPixelSize;
  34577. this._downSamplePostProcesses = new Array(lumSteps);
  34578. // Utils for luminance
  34579. var luminanceUpdateSourceOffsets = function (width, height) {
  34580. var sU = (1.0 / width);
  34581. var sV = (1.0 / height);
  34582. luminanceOffsets[0] = -0.5 * sU;
  34583. luminanceOffsets[1] = 0.5 * sV;
  34584. luminanceOffsets[2] = 0.5 * sU;
  34585. luminanceOffsets[3] = 0.5 * sV;
  34586. luminanceOffsets[4] = -0.5 * sU;
  34587. luminanceOffsets[5] = -0.5 * sV;
  34588. luminanceOffsets[6] = 0.5 * sU;
  34589. luminanceOffsets[7] = -0.5 * sV;
  34590. };
  34591. var luminanceUpdateDestOffsets = function (width, height) {
  34592. var id = 0;
  34593. for (var x = -1; x < 2; x++) {
  34594. for (var y = -1; y < 2; y++) {
  34595. downSampleOffsets[id] = (x) / width;
  34596. downSampleOffsets[id + 1] = (y) / height;
  34597. id += 2;
  34598. }
  34599. }
  34600. };
  34601. // Luminance callback
  34602. var luminanceCallback = function (effect) {
  34603. if (_this._needUpdate) {
  34604. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  34605. }
  34606. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  34607. effect.setArray2("lumOffsets", luminanceOffsets);
  34608. };
  34609. // Down sample callbacks
  34610. var downSampleCallback = function (indice) {
  34611. var i = indice;
  34612. return function (effect) {
  34613. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  34614. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  34615. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  34616. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  34617. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  34618. effect.setArray2("dsOffsets", downSampleOffsets);
  34619. };
  34620. };
  34621. var downSampleAfterRenderCallback = function (effect) {
  34622. // Unpack result
  34623. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  34624. 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);
  34625. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  34626. };
  34627. // Create luminance post-process
  34628. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  34629. 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);
  34630. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  34631. // Create down sample post-processes
  34632. for (var i = lumSteps - 2; i >= 0; i--) {
  34633. var length = Math.pow(3, i);
  34634. ratio = { width: length, height: length };
  34635. var defines = "#define DOWN_SAMPLE\n";
  34636. if (i === 0) {
  34637. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  34638. }
  34639. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  34640. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  34641. if (i === 0) {
  34642. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  34643. }
  34644. }
  34645. };
  34646. /**
  34647. * Gaussian blur post-processes. Horizontal and Vertical
  34648. */
  34649. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  34650. var _this = this;
  34651. var blurOffsetsW = new Array(9);
  34652. var blurOffsetsH = new Array(9);
  34653. var blurWeights = new Array(9);
  34654. var uniforms = ["blurOffsets", "blurWeights"];
  34655. // Utils for gaussian blur
  34656. var calculateBlurOffsets = function (height) {
  34657. var lastOutputDimensions = {
  34658. width: scene.getEngine().getRenderWidth() * (ratio / 4),
  34659. height: scene.getEngine().getRenderHeight() * (ratio / 4)
  34660. };
  34661. for (var i = 0; i < 9; i++) {
  34662. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  34663. if (height) {
  34664. blurOffsetsH[i] = value;
  34665. }
  34666. else {
  34667. blurOffsetsW[i] = value;
  34668. }
  34669. }
  34670. };
  34671. var calculateWeights = function () {
  34672. var x = 0.0;
  34673. for (var i = 0; i < 9; i++) {
  34674. x = (i - 4.0) / 4.0;
  34675. 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));
  34676. }
  34677. };
  34678. // Callback
  34679. var gaussianBlurCallback = function (height) {
  34680. return function (effect) {
  34681. if (_this._needUpdate) {
  34682. calculateWeights();
  34683. calculateBlurOffsets(height);
  34684. }
  34685. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  34686. effect.setArray("blurWeights", blurWeights);
  34687. };
  34688. };
  34689. // Create horizontal gaussian blur post-processes
  34690. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  34691. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  34692. // Create vertical gaussian blur post-process
  34693. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  34694. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  34695. };
  34696. // Luminance generator
  34697. HDRRenderingPipeline.LUM_STEPS = 6;
  34698. return HDRRenderingPipeline;
  34699. })(BABYLON.PostProcessRenderPipeline);
  34700. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  34701. })(BABYLON || (BABYLON = {}));
  34702. var BABYLON;
  34703. (function (BABYLON) {
  34704. var FaceAdjacencies = (function () {
  34705. function FaceAdjacencies() {
  34706. this.edges = new Array();
  34707. this.edgesConnectedCount = 0;
  34708. }
  34709. return FaceAdjacencies;
  34710. })();
  34711. var EdgesRenderer = (function () {
  34712. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  34713. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  34714. if (epsilon === void 0) { epsilon = 0.95; }
  34715. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  34716. this._linesPositions = new Array();
  34717. this._linesNormals = new Array();
  34718. this._linesIndices = new Array();
  34719. this._buffers = new Array();
  34720. this._checkVerticesInsteadOfIndices = false;
  34721. this._source = source;
  34722. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  34723. this._epsilon = epsilon;
  34724. this._prepareRessources();
  34725. this._generateEdgesLines();
  34726. }
  34727. EdgesRenderer.prototype._prepareRessources = function () {
  34728. if (this._lineShader) {
  34729. return;
  34730. }
  34731. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  34732. attributes: ["position", "normal"],
  34733. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  34734. });
  34735. this._lineShader.disableDepthWrite = true;
  34736. this._lineShader.backFaceCulling = false;
  34737. };
  34738. EdgesRenderer.prototype.dispose = function () {
  34739. this._vb0.dispose();
  34740. this._vb1.dispose();
  34741. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  34742. this._lineShader.dispose();
  34743. };
  34744. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  34745. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  34746. return 0;
  34747. }
  34748. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  34749. return 1;
  34750. }
  34751. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  34752. return 2;
  34753. }
  34754. return -1;
  34755. };
  34756. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  34757. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  34758. return 0;
  34759. }
  34760. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  34761. return 1;
  34762. }
  34763. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  34764. return 2;
  34765. }
  34766. return -1;
  34767. };
  34768. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  34769. var needToCreateLine;
  34770. if (edge === undefined) {
  34771. needToCreateLine = true;
  34772. }
  34773. else {
  34774. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  34775. needToCreateLine = dotProduct < this._epsilon;
  34776. }
  34777. if (needToCreateLine) {
  34778. var offset = this._linesPositions.length / 3;
  34779. var normal = p0.subtract(p1);
  34780. normal.normalize();
  34781. // Positions
  34782. this._linesPositions.push(p0.x);
  34783. this._linesPositions.push(p0.y);
  34784. this._linesPositions.push(p0.z);
  34785. this._linesPositions.push(p0.x);
  34786. this._linesPositions.push(p0.y);
  34787. this._linesPositions.push(p0.z);
  34788. this._linesPositions.push(p1.x);
  34789. this._linesPositions.push(p1.y);
  34790. this._linesPositions.push(p1.z);
  34791. this._linesPositions.push(p1.x);
  34792. this._linesPositions.push(p1.y);
  34793. this._linesPositions.push(p1.z);
  34794. // Normals
  34795. this._linesNormals.push(p1.x);
  34796. this._linesNormals.push(p1.y);
  34797. this._linesNormals.push(p1.z);
  34798. this._linesNormals.push(-1);
  34799. this._linesNormals.push(p1.x);
  34800. this._linesNormals.push(p1.y);
  34801. this._linesNormals.push(p1.z);
  34802. this._linesNormals.push(1);
  34803. this._linesNormals.push(p0.x);
  34804. this._linesNormals.push(p0.y);
  34805. this._linesNormals.push(p0.z);
  34806. this._linesNormals.push(-1);
  34807. this._linesNormals.push(p0.x);
  34808. this._linesNormals.push(p0.y);
  34809. this._linesNormals.push(p0.z);
  34810. this._linesNormals.push(1);
  34811. // Indices
  34812. this._linesIndices.push(offset);
  34813. this._linesIndices.push(offset + 1);
  34814. this._linesIndices.push(offset + 2);
  34815. this._linesIndices.push(offset);
  34816. this._linesIndices.push(offset + 2);
  34817. this._linesIndices.push(offset + 3);
  34818. }
  34819. };
  34820. EdgesRenderer.prototype._generateEdgesLines = function () {
  34821. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34822. var indices = this._source.getIndices();
  34823. // First let's find adjacencies
  34824. var adjacencies = new Array();
  34825. var faceNormals = new Array();
  34826. var index;
  34827. var faceAdjacencies;
  34828. // Prepare faces
  34829. for (index = 0; index < indices.length; index += 3) {
  34830. faceAdjacencies = new FaceAdjacencies();
  34831. var p0Index = indices[index];
  34832. var p1Index = indices[index + 1];
  34833. var p2Index = indices[index + 2];
  34834. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  34835. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  34836. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  34837. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  34838. faceNormal.normalize();
  34839. faceNormals.push(faceNormal);
  34840. adjacencies.push(faceAdjacencies);
  34841. }
  34842. // Scan
  34843. for (index = 0; index < adjacencies.length; index++) {
  34844. faceAdjacencies = adjacencies[index];
  34845. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  34846. var otherFaceAdjacencies = adjacencies[otherIndex];
  34847. if (faceAdjacencies.edgesConnectedCount === 3) {
  34848. break;
  34849. }
  34850. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  34851. continue;
  34852. }
  34853. var otherP0 = indices[otherIndex * 3];
  34854. var otherP1 = indices[otherIndex * 3 + 1];
  34855. var otherP2 = indices[otherIndex * 3 + 2];
  34856. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  34857. var otherEdgeIndex;
  34858. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  34859. continue;
  34860. }
  34861. switch (edgeIndex) {
  34862. case 0:
  34863. if (this._checkVerticesInsteadOfIndices) {
  34864. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  34865. }
  34866. else {
  34867. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  34868. }
  34869. break;
  34870. case 1:
  34871. if (this._checkVerticesInsteadOfIndices) {
  34872. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  34873. }
  34874. else {
  34875. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  34876. }
  34877. break;
  34878. case 2:
  34879. if (this._checkVerticesInsteadOfIndices) {
  34880. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  34881. }
  34882. else {
  34883. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  34884. }
  34885. break;
  34886. }
  34887. if (otherEdgeIndex === -1) {
  34888. continue;
  34889. }
  34890. faceAdjacencies.edges[edgeIndex] = otherIndex;
  34891. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  34892. faceAdjacencies.edgesConnectedCount++;
  34893. otherFaceAdjacencies.edgesConnectedCount++;
  34894. if (faceAdjacencies.edgesConnectedCount === 3) {
  34895. break;
  34896. }
  34897. }
  34898. }
  34899. }
  34900. // Create lines
  34901. for (index = 0; index < adjacencies.length; index++) {
  34902. // 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
  34903. var current = adjacencies[index];
  34904. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  34905. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  34906. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  34907. }
  34908. // Merge into a single mesh
  34909. var engine = this._source.getScene().getEngine();
  34910. this._vb0 = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  34911. this._vb1 = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  34912. this._buffers[BABYLON.VertexBuffer.PositionKind] = this._vb0;
  34913. this._buffers[BABYLON.VertexBuffer.NormalKind] = this._vb1;
  34914. this._ib = engine.createIndexBuffer(this._linesIndices);
  34915. this._indicesCount = this._linesIndices.length;
  34916. };
  34917. EdgesRenderer.prototype.render = function () {
  34918. if (!this._lineShader.isReady()) {
  34919. return;
  34920. }
  34921. var scene = this._source.getScene();
  34922. var engine = scene.getEngine();
  34923. this._lineShader._preBind();
  34924. // VBOs
  34925. engine.bindMultiBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  34926. scene.resetCachedMaterial();
  34927. this._lineShader.setColor4("color", this._source.edgesColor);
  34928. this._lineShader.setFloat("width", this._source.edgesWidth / 50.0);
  34929. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  34930. this._lineShader.bind(this._source.getWorldMatrix());
  34931. // Draw order
  34932. engine.draw(true, 0, this._indicesCount);
  34933. this._lineShader.unbind();
  34934. engine.setDepthWrite(true);
  34935. };
  34936. return EdgesRenderer;
  34937. })();
  34938. BABYLON.EdgesRenderer = EdgesRenderer;
  34939. })(BABYLON || (BABYLON = {}));
  34940. var BABYLON;
  34941. (function (BABYLON) {
  34942. (function (TonemappingOperator) {
  34943. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  34944. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  34945. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  34946. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  34947. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  34948. var TonemappingOperator = BABYLON.TonemappingOperator;
  34949. ;
  34950. var TonemapPostProcess = (function (_super) {
  34951. __extends(TonemapPostProcess, _super);
  34952. function TonemapPostProcess(name, operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  34953. var _this = this;
  34954. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  34955. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  34956. this._operator = operator;
  34957. this._exposureAdjustment = exposureAdjustment;
  34958. var params = ["_ExposureAdjustment"];
  34959. var defines = "#define ";
  34960. if (operator === TonemappingOperator.Hable)
  34961. defines += "HABLE_TONEMAPPING";
  34962. else if (operator === TonemappingOperator.Reinhard)
  34963. defines += "REINHARD_TONEMAPPING";
  34964. else if (operator === TonemappingOperator.HejiDawson)
  34965. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  34966. else if (operator === TonemappingOperator.Photographic)
  34967. defines += "PHOTOGRAPHIC_TONEMAPPING";
  34968. _super.call(this, name, "tonemap", params, null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  34969. this.onApply = function (effect) {
  34970. effect.setFloat("_ExposureAdjustment", _this._exposureAdjustment);
  34971. };
  34972. }
  34973. return TonemapPostProcess;
  34974. })(BABYLON.PostProcess);
  34975. BABYLON.TonemapPostProcess = TonemapPostProcess;
  34976. })(BABYLON || (BABYLON = {}));
  34977. var BABYLON;
  34978. (function (BABYLON) {
  34979. var maxSimultaneousLights = 4;
  34980. var PBRMaterialDefines = (function (_super) {
  34981. __extends(PBRMaterialDefines, _super);
  34982. function PBRMaterialDefines() {
  34983. _super.call(this);
  34984. this.ALBEDO = false;
  34985. this.CLIPPLANE = false;
  34986. this.ALPHATEST = false;
  34987. this.FOG = false;
  34988. this.NORMAL = false;
  34989. this.UV1 = false;
  34990. this.UV2 = false;
  34991. this.VERTEXCOLOR = false;
  34992. this.VERTEXALPHA = false;
  34993. this.BONES = false;
  34994. this.BONES4 = false;
  34995. this.BonesPerMesh = 0;
  34996. this.INSTANCES = false;
  34997. this.POINTSIZE = false;
  34998. this._keys = Object.keys(this);
  34999. }
  35000. return PBRMaterialDefines;
  35001. })(BABYLON.MaterialDefines);
  35002. var PBRMaterial = (function (_super) {
  35003. __extends(PBRMaterial, _super);
  35004. function PBRMaterial(name, scene) {
  35005. _super.call(this, name, scene);
  35006. this.albedoColor = new BABYLON.Color3(1, 1, 1);
  35007. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  35008. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  35009. this._scaledDiffuse = new BABYLON.Color3();
  35010. this._scaledSpecular = new BABYLON.Color3();
  35011. this._defines = new PBRMaterialDefines();
  35012. this._cachedDefines = new PBRMaterialDefines();
  35013. this._cachedDefines.BonesPerMesh = -1;
  35014. }
  35015. PBRMaterial.prototype.needAlphaBlending = function () {
  35016. return this.alpha < 1.0;
  35017. };
  35018. PBRMaterial.prototype.needAlphaTesting = function () {
  35019. return false;
  35020. };
  35021. PBRMaterial.prototype.getAlphaTestTexture = function () {
  35022. return null;
  35023. };
  35024. // Methods
  35025. PBRMaterial.prototype.isReady = function (mesh, useInstances) {
  35026. if (this.checkReadyOnlyOnce) {
  35027. if (this._wasPreviouslyReady) {
  35028. return true;
  35029. }
  35030. }
  35031. var scene = this.getScene();
  35032. if (!this.checkReadyOnEveryCall) {
  35033. if (this._renderId === scene.getRenderId()) {
  35034. return true;
  35035. }
  35036. }
  35037. var engine = scene.getEngine();
  35038. var needNormals = false;
  35039. var needUVs = false;
  35040. this._defines.reset();
  35041. // Textures
  35042. if (scene.texturesEnabled) {
  35043. }
  35044. // Effect
  35045. if (scene.clipPlane) {
  35046. this._defines.CLIPPLANE = true;
  35047. }
  35048. if (engine.getAlphaTesting()) {
  35049. this._defines.ALPHATEST = true;
  35050. }
  35051. // Point size
  35052. if (this.pointsCloud || scene.forcePointsCloud) {
  35053. this._defines.POINTSIZE = true;
  35054. }
  35055. // Fog
  35056. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  35057. this._defines.FOG = true;
  35058. }
  35059. // Lights
  35060. // Attribs
  35061. if (mesh) {
  35062. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35063. this._defines.NORMAL = true;
  35064. }
  35065. if (needUVs) {
  35066. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35067. this._defines.UV1 = true;
  35068. }
  35069. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35070. this._defines.UV2 = true;
  35071. }
  35072. }
  35073. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  35074. this._defines.VERTEXCOLOR = true;
  35075. if (mesh.hasVertexAlpha) {
  35076. this._defines.VERTEXALPHA = true;
  35077. }
  35078. }
  35079. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  35080. this._defines.BONES = true;
  35081. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  35082. this._defines.BONES4 = true;
  35083. }
  35084. // Instances
  35085. if (useInstances) {
  35086. this._defines.INSTANCES = true;
  35087. }
  35088. }
  35089. // Get correct effect
  35090. if (!this._defines.isEqual(this._cachedDefines)) {
  35091. this._defines.cloneTo(this._cachedDefines);
  35092. scene.resetCachedMaterial();
  35093. // Fallbacks
  35094. var fallbacks = new BABYLON.EffectFallbacks();
  35095. if (this._defines.FOG) {
  35096. fallbacks.addFallback(1, "FOG");
  35097. }
  35098. if (this._defines.BONES4) {
  35099. fallbacks.addFallback(0, "BONES4");
  35100. }
  35101. //Attributes
  35102. var attribs = [BABYLON.VertexBuffer.PositionKind];
  35103. if (this._defines.NORMAL) {
  35104. attribs.push(BABYLON.VertexBuffer.NormalKind);
  35105. }
  35106. if (this._defines.UV1) {
  35107. attribs.push(BABYLON.VertexBuffer.UVKind);
  35108. }
  35109. if (this._defines.UV2) {
  35110. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  35111. }
  35112. if (this._defines.VERTEXCOLOR) {
  35113. attribs.push(BABYLON.VertexBuffer.ColorKind);
  35114. }
  35115. if (this._defines.BONES) {
  35116. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35117. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35118. }
  35119. if (this._defines.INSTANCES) {
  35120. attribs.push("world0");
  35121. attribs.push("world1");
  35122. attribs.push("world2");
  35123. attribs.push("world3");
  35124. }
  35125. // Legacy browser patch
  35126. var join = this._defines.toString();
  35127. this._effect = scene.getEngine().createEffect("pbr", attribs, ["world", "view", "viewProjection", "vEyePosition", "vAlbedoColor",
  35128. "vFogInfos", "vFogColor", "pointSize",
  35129. "mBones",
  35130. "vClipPlane",
  35131. ], [], join, fallbacks, this.onCompiled, this.onError);
  35132. }
  35133. if (!this._effect.isReady()) {
  35134. return false;
  35135. }
  35136. this._renderId = scene.getRenderId();
  35137. this._wasPreviouslyReady = true;
  35138. return true;
  35139. };
  35140. PBRMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  35141. this._effect.setMatrix("world", world);
  35142. };
  35143. PBRMaterial.prototype.bind = function (world, mesh) {
  35144. var scene = this.getScene();
  35145. // Matrices
  35146. this.bindOnlyWorldMatrix(world);
  35147. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  35148. // Bones
  35149. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  35150. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  35151. }
  35152. if (scene.getCachedMaterial() !== this) {
  35153. // Clip plane
  35154. if (scene.clipPlane) {
  35155. var clipPlane = scene.clipPlane;
  35156. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  35157. }
  35158. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  35159. }
  35160. // Point size
  35161. if (this.pointsCloud) {
  35162. this._effect.setFloat("pointSize", this.pointSize);
  35163. }
  35164. // Colors
  35165. this._effect.setColor4("vAlbedoColor", this.albedoColor, this.alpha * mesh.visibility);
  35166. // View
  35167. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  35168. this._effect.setMatrix("view", scene.getViewMatrix());
  35169. }
  35170. // Fog
  35171. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  35172. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  35173. this._effect.setColor3("vFogColor", scene.fogColor);
  35174. }
  35175. _super.prototype.bind.call(this, world, mesh);
  35176. };
  35177. PBRMaterial.prototype.getAnimatables = function () {
  35178. var results = [];
  35179. return results;
  35180. };
  35181. PBRMaterial.prototype.dispose = function (forceDisposeEffect) {
  35182. _super.prototype.dispose.call(this, forceDisposeEffect);
  35183. };
  35184. PBRMaterial.prototype.clone = function (name) {
  35185. var newPBRMaterial = new PBRMaterial(name, this.getScene());
  35186. // Base material
  35187. this.copyTo(newPBRMaterial);
  35188. // PBRMaterial material
  35189. newPBRMaterial.albedoColor = this.albedoColor.clone();
  35190. return newPBRMaterial;
  35191. };
  35192. return PBRMaterial;
  35193. })(BABYLON.Material);
  35194. BABYLON.PBRMaterial = PBRMaterial;
  35195. })(BABYLON || (BABYLON = {}));
  35196. var BABYLON;
  35197. (function (BABYLON) {
  35198. var ReflectionProbe = (function () {
  35199. function ReflectionProbe(name, size, scene, generateMipMaps) {
  35200. var _this = this;
  35201. if (generateMipMaps === void 0) { generateMipMaps = true; }
  35202. this.name = name;
  35203. this._viewMatrix = BABYLON.Matrix.Identity();
  35204. this._target = BABYLON.Vector3.Zero();
  35205. this._add = BABYLON.Vector3.Zero();
  35206. this.position = BABYLON.Vector3.Zero();
  35207. this._scene = scene;
  35208. this._scene.reflectionProbes.push(this);
  35209. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  35210. this._renderTargetTexture.onBeforeRender = function (faceIndex) {
  35211. switch (faceIndex) {
  35212. case 0:
  35213. _this._add.copyFromFloats(1, 0, 0);
  35214. break;
  35215. case 1:
  35216. _this._add.copyFromFloats(-1, 0, 0);
  35217. break;
  35218. case 2:
  35219. _this._add.copyFromFloats(0, -1, 0);
  35220. break;
  35221. case 3:
  35222. _this._add.copyFromFloats(0, 1, 0);
  35223. break;
  35224. case 4:
  35225. _this._add.copyFromFloats(0, 0, 1);
  35226. break;
  35227. case 5:
  35228. _this._add.copyFromFloats(0, 0, -1);
  35229. break;
  35230. }
  35231. if (_this._attachedMesh) {
  35232. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  35233. }
  35234. _this.position.addToRef(_this._add, _this._target);
  35235. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  35236. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  35237. };
  35238. this._renderTargetTexture.onAfterUnbind = function () {
  35239. scene.updateTransformMatrix(true);
  35240. };
  35241. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  35242. }
  35243. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  35244. get: function () {
  35245. return this._renderTargetTexture.refreshRate;
  35246. },
  35247. set: function (value) {
  35248. this._renderTargetTexture.refreshRate = value;
  35249. },
  35250. enumerable: true,
  35251. configurable: true
  35252. });
  35253. ReflectionProbe.prototype.getScene = function () {
  35254. return this._scene;
  35255. };
  35256. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  35257. get: function () {
  35258. return this._renderTargetTexture;
  35259. },
  35260. enumerable: true,
  35261. configurable: true
  35262. });
  35263. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  35264. get: function () {
  35265. return this._renderTargetTexture.renderList;
  35266. },
  35267. enumerable: true,
  35268. configurable: true
  35269. });
  35270. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  35271. this._attachedMesh = mesh;
  35272. };
  35273. ReflectionProbe.prototype.dispose = function () {
  35274. var index = this._scene.reflectionProbes.indexOf(this);
  35275. if (index !== -1) {
  35276. // Remove from the scene if found
  35277. this._scene.reflectionProbes.splice(index, 1);
  35278. }
  35279. };
  35280. return ReflectionProbe;
  35281. })();
  35282. BABYLON.ReflectionProbe = ReflectionProbe;
  35283. })(BABYLON || (BABYLON = {}));
  35284. var BABYLON;
  35285. (function (BABYLON) {
  35286. var SolidParticle = (function () {
  35287. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape) {
  35288. this.color = new BABYLON.Color4(1, 1, 1, 1); // color
  35289. this.position = BABYLON.Vector3.Zero(); // position
  35290. this.rotation = BABYLON.Vector3.Zero(); // rotation
  35291. this.scale = new BABYLON.Vector3(1, 1, 1); // scale
  35292. this.uvs = new BABYLON.Vector4(0, 0, 1, 1); // uvs
  35293. this.velocity = BABYLON.Vector3.Zero(); // velocity
  35294. this.alive = true; // alive
  35295. this.idx = particleIndex;
  35296. this._pos = positionIndex;
  35297. this._model = model;
  35298. this.shapeId = shapeId;
  35299. this.idxInShape = idxInShape;
  35300. }
  35301. return SolidParticle;
  35302. })();
  35303. BABYLON.SolidParticle = SolidParticle;
  35304. var ModelShape = (function () {
  35305. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  35306. this.shapeID = id;
  35307. this._shape = shape;
  35308. this._shapeUV = shapeUV;
  35309. this._positionFunction = posFunction;
  35310. this._vertexFunction = vtxFunction;
  35311. }
  35312. return ModelShape;
  35313. })();
  35314. BABYLON.ModelShape = ModelShape;
  35315. })(BABYLON || (BABYLON = {}));
  35316. var BABYLON;
  35317. (function (BABYLON) {
  35318. var SolidParticleSystem = (function () {
  35319. function SolidParticleSystem(name, scene) {
  35320. // public members
  35321. this.particles = new Array();
  35322. this.nbParticles = 0;
  35323. this.billboard = false;
  35324. this.counter = 0;
  35325. this._positions = new Array();
  35326. this._indices = new Array();
  35327. this._normals = new Array();
  35328. this._colors = new Array();
  35329. this._uvs = new Array();
  35330. this._index = 0; // indices index
  35331. this._shapeCounter = 0;
  35332. this._copy = new BABYLON.SolidParticle(null, null, null, null, null);
  35333. this._color = new BABYLON.Color4(0, 0, 0, 0);
  35334. this._computeParticleColor = true;
  35335. this._computeParticleTexture = true;
  35336. this._computeParticleRotation = true;
  35337. this._computeParticleVertex = false;
  35338. this._cam_axisZ = BABYLON.Vector3.Zero();
  35339. this._cam_axisY = BABYLON.Vector3.Zero();
  35340. this._cam_axisX = BABYLON.Vector3.Zero();
  35341. this._axisX = BABYLON.Axis.X;
  35342. this._axisY = BABYLON.Axis.Y;
  35343. this._axisZ = BABYLON.Axis.Z;
  35344. this._fakeCamPos = BABYLON.Vector3.Zero();
  35345. this._rotMatrix = new BABYLON.Matrix();
  35346. this._invertedMatrix = new BABYLON.Matrix();
  35347. this._rotated = BABYLON.Vector3.Zero();
  35348. this._quaternion = new BABYLON.Quaternion();
  35349. this._vertex = BABYLON.Vector3.Zero();
  35350. this._yaw = 0.0;
  35351. this._pitch = 0.0;
  35352. this._roll = 0.0;
  35353. this._halfroll = 0.0;
  35354. this._halfpitch = 0.0;
  35355. this._halfyaw = 0.0;
  35356. this._sinRoll = 0.0;
  35357. this._cosRoll = 0.0;
  35358. this._sinPitch = 0.0;
  35359. this._cosPitch = 0.0;
  35360. this._sinYaw = 0.0;
  35361. this._cosYaw = 0.0;
  35362. this.name = name;
  35363. this._scene = scene;
  35364. this._camera = scene.activeCamera;
  35365. }
  35366. // build the SPS mesh : returns the mesh
  35367. SolidParticleSystem.prototype.buildMesh = function (updatable) {
  35368. if (updatable === void 0) { updatable = true; }
  35369. if (this.nbParticles === 0) {
  35370. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  35371. this.addShape(triangle, 1);
  35372. triangle.dispose();
  35373. }
  35374. this._positions32 = new Float32Array(this._positions);
  35375. this._uvs32 = new Float32Array(this._uvs);
  35376. this._colors32 = new Float32Array(this._colors);
  35377. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  35378. this._normals32 = new Float32Array(this._normals);
  35379. var vertexData = new BABYLON.VertexData();
  35380. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  35381. vertexData.indices = this._indices;
  35382. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  35383. if (this._uvs32) {
  35384. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  35385. ;
  35386. }
  35387. if (this._colors32) {
  35388. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  35389. }
  35390. var mesh = new BABYLON.Mesh(name, this._scene);
  35391. vertexData.applyToMesh(mesh, updatable);
  35392. this.mesh = mesh;
  35393. // free memory
  35394. this._positions = null;
  35395. this._normals = null;
  35396. this._uvs = null;
  35397. this._colors = null;
  35398. if (!updatable) {
  35399. this.particles.length = 0;
  35400. }
  35401. return mesh;
  35402. };
  35403. //reset copy
  35404. SolidParticleSystem.prototype._resetCopy = function () {
  35405. this._copy.position.x = 0;
  35406. this._copy.position.y = 0;
  35407. this._copy.position.z = 0;
  35408. this._copy.rotation.x = 0;
  35409. this._copy.rotation.y = 0;
  35410. this._copy.rotation.z = 0;
  35411. this._copy.quaternion = null;
  35412. this._copy.scale.x = 1;
  35413. this._copy.scale.y = 1;
  35414. this._copy.scale.z = 1;
  35415. this._copy.uvs.x = 0;
  35416. this._copy.uvs.y = 0;
  35417. this._copy.uvs.z = 1;
  35418. this._copy.uvs.w = 1;
  35419. this._copy.color = null;
  35420. };
  35421. // _meshBuilder : inserts the shape model in the global SPS mesh
  35422. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, idx, idxInShape, options) {
  35423. var i;
  35424. var u = 0;
  35425. var c = 0;
  35426. this._resetCopy();
  35427. if (options && options.positionFunction) {
  35428. options.positionFunction(this._copy, idx, idxInShape);
  35429. }
  35430. if (this._copy.quaternion) {
  35431. this._quaternion.x = this._copy.quaternion.x;
  35432. this._quaternion.y = this._copy.quaternion.y;
  35433. this._quaternion.z = this._copy.quaternion.z;
  35434. this._quaternion.w = this._copy.quaternion.w;
  35435. }
  35436. else {
  35437. this._yaw = this._copy.rotation.y;
  35438. this._pitch = this._copy.rotation.x;
  35439. this._roll = this._copy.rotation.z;
  35440. this._quaternionRotationYPR();
  35441. }
  35442. this._quaternionToRotationMatrix();
  35443. for (i = 0; i < shape.length; i++) {
  35444. this._vertex.x = shape[i].x;
  35445. this._vertex.y = shape[i].y;
  35446. this._vertex.z = shape[i].z;
  35447. if (options && options.vertexFunction) {
  35448. options.vertexFunction(this._copy, this._vertex, i);
  35449. }
  35450. this._vertex.x *= this._copy.scale.x;
  35451. this._vertex.y *= this._copy.scale.y;
  35452. this._vertex.z *= this._copy.scale.z;
  35453. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  35454. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  35455. if (meshUV) {
  35456. 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);
  35457. u += 2;
  35458. }
  35459. if (this._copy.color) {
  35460. this._color = this._copy.color;
  35461. }
  35462. else if (meshCol && meshCol[c]) {
  35463. this._color.r = meshCol[c];
  35464. this._color.g = meshCol[c + 1];
  35465. this._color.b = meshCol[c + 2];
  35466. this._color.a = meshCol[c + 3];
  35467. }
  35468. else {
  35469. this._color.r = 1;
  35470. this._color.g = 1;
  35471. this._color.b = 1;
  35472. this._color.a = 1;
  35473. }
  35474. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  35475. c += 4;
  35476. }
  35477. for (i = 0; i < meshInd.length; i++) {
  35478. indices.push(p + meshInd[i]);
  35479. }
  35480. };
  35481. // returns a shape array from positions array
  35482. SolidParticleSystem.prototype._posToShape = function (positions) {
  35483. var shape = [];
  35484. for (var i = 0; i < positions.length; i += 3) {
  35485. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  35486. }
  35487. return shape;
  35488. };
  35489. // returns a shapeUV array from a Vector4 uvs
  35490. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  35491. var shapeUV = [];
  35492. if (uvs) {
  35493. for (var i = 0; i < uvs.length; i++)
  35494. shapeUV.push(uvs[i]);
  35495. }
  35496. return shapeUV;
  35497. };
  35498. // adds a new particle object in the particles array
  35499. SolidParticleSystem.prototype._addParticle = function (p, idxpos, model, shapeId, idxInShape) {
  35500. this.particles.push(new BABYLON.SolidParticle(p, idxpos, model, shapeId, idxInShape));
  35501. };
  35502. // add solid particles from a shape model in the particles array
  35503. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  35504. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35505. var meshInd = mesh.getIndices();
  35506. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  35507. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  35508. var shape = this._posToShape(meshPos);
  35509. var shapeUV = this._uvsToShapeUV(meshUV);
  35510. var posfunc = options ? options.positionFunction : null;
  35511. var vtxfunc = options ? options.vertexFunction : null;
  35512. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  35513. // particles
  35514. for (var i = 0; i < nb; i++) {
  35515. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, this.nbParticles + i, i, options);
  35516. this._addParticle(this.nbParticles + i, this._positions.length, modelShape, this._shapeCounter, i);
  35517. this._index += shape.length;
  35518. }
  35519. this.nbParticles += nb;
  35520. this._shapeCounter++;
  35521. return this._shapeCounter;
  35522. };
  35523. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  35524. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  35525. this._resetCopy();
  35526. if (particle._model._positionFunction) {
  35527. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  35528. }
  35529. if (this._copy.quaternion) {
  35530. this._quaternion.x = this._copy.quaternion.x;
  35531. this._quaternion.y = this._copy.quaternion.y;
  35532. this._quaternion.z = this._copy.quaternion.z;
  35533. this._quaternion.w = this._copy.quaternion.w;
  35534. }
  35535. else {
  35536. this._yaw = this._copy.rotation.y;
  35537. this._pitch = this._copy.rotation.x;
  35538. this._roll = this._copy.rotation.z;
  35539. this._quaternionRotationYPR();
  35540. }
  35541. this._quaternionToRotationMatrix();
  35542. this._shape = particle._model._shape;
  35543. for (var pt = 0; pt < this._shape.length; pt++) {
  35544. this._vertex.x = this._shape[pt].x;
  35545. this._vertex.y = this._shape[pt].y;
  35546. this._vertex.z = this._shape[pt].z;
  35547. if (particle._model._vertexFunction) {
  35548. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  35549. }
  35550. this._vertex.x *= this._copy.scale.x;
  35551. this._vertex.y *= this._copy.scale.y;
  35552. this._vertex.z *= this._copy.scale.z;
  35553. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  35554. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  35555. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  35556. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  35557. }
  35558. particle.position.x = 0;
  35559. particle.position.y = 0;
  35560. particle.position.z = 0;
  35561. particle.rotation.x = 0;
  35562. particle.rotation.y = 0;
  35563. particle.rotation.z = 0;
  35564. particle.quaternion = null;
  35565. particle.scale.x = 1;
  35566. particle.scale.y = 1;
  35567. particle.scale.z = 1;
  35568. };
  35569. // rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed
  35570. SolidParticleSystem.prototype.rebuildMesh = function () {
  35571. for (var p = 0; p < this.particles.length; p++) {
  35572. this._rebuildParticle(this.particles[p]);
  35573. }
  35574. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  35575. };
  35576. // sets all the particles : updates the VBO
  35577. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  35578. if (start === void 0) { start = 0; }
  35579. if (end === void 0) { end = this.nbParticles - 1; }
  35580. if (update === void 0) { update = true; }
  35581. // custom beforeUpdate
  35582. this.beforeUpdateParticles(start, end, update);
  35583. this._cam_axisX.x = 1;
  35584. this._cam_axisX.y = 0;
  35585. this._cam_axisX.z = 0;
  35586. this._cam_axisY.x = 0;
  35587. this._cam_axisY.y = 1;
  35588. this._cam_axisY.z = 0;
  35589. this._cam_axisZ.x = 0;
  35590. this._cam_axisZ.y = 0;
  35591. this._cam_axisZ.z = 1;
  35592. // if the particles will always face the camera
  35593. if (this.billboard) {
  35594. // compute a fake camera position : un-rotate the camera position by the current mesh rotation
  35595. this._yaw = this.mesh.rotation.y;
  35596. this._pitch = this.mesh.rotation.x;
  35597. this._roll = this.mesh.rotation.z;
  35598. this._quaternionRotationYPR();
  35599. this._quaternionToRotationMatrix();
  35600. this._rotMatrix.invertToRef(this._invertedMatrix);
  35601. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertedMatrix, this._fakeCamPos);
  35602. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the cam-mesh axis (_cam_axisZ)
  35603. (this._fakeCamPos).subtractToRef(this.mesh.position, this._cam_axisZ);
  35604. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  35605. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._cam_axisY, this._cam_axisX);
  35606. this._cam_axisY.normalize();
  35607. this._cam_axisX.normalize();
  35608. this._cam_axisZ.normalize();
  35609. }
  35610. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  35611. var idx = 0;
  35612. var index = 0;
  35613. var colidx = 0;
  35614. var colorIndex = 0;
  35615. var uvidx = 0;
  35616. var uvIndex = 0;
  35617. // particle loop
  35618. end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
  35619. for (var p = start; p <= end; p++) {
  35620. this._particle = this.particles[p];
  35621. this._shape = this._particle._model._shape;
  35622. this._shapeUV = this._particle._model._shapeUV;
  35623. // call to custom user function to update the particle properties
  35624. this.updateParticle(this._particle);
  35625. // particle rotation matrix
  35626. if (this.billboard) {
  35627. this._particle.rotation.x = 0.0;
  35628. this._particle.rotation.y = 0.0;
  35629. }
  35630. if (this._computeParticleRotation) {
  35631. if (this._particle.quaternion) {
  35632. this._quaternion.x = this._particle.quaternion.x;
  35633. this._quaternion.y = this._particle.quaternion.y;
  35634. this._quaternion.z = this._particle.quaternion.z;
  35635. this._quaternion.w = this._particle.quaternion.w;
  35636. }
  35637. else {
  35638. this._yaw = this._particle.rotation.y;
  35639. this._pitch = this._particle.rotation.x;
  35640. this._roll = this._particle.rotation.z;
  35641. this._quaternionRotationYPR();
  35642. }
  35643. this._quaternionToRotationMatrix();
  35644. }
  35645. for (var pt = 0; pt < this._shape.length; pt++) {
  35646. idx = index + pt * 3;
  35647. colidx = colorIndex + pt * 4;
  35648. uvidx = uvIndex + pt * 2;
  35649. this._vertex.x = this._shape[pt].x;
  35650. this._vertex.y = this._shape[pt].y;
  35651. this._vertex.z = this._shape[pt].z;
  35652. if (this._computeParticleVertex) {
  35653. this.updateParticleVertex(this._particle, this._vertex, pt);
  35654. }
  35655. this._vertex.x *= this._particle.scale.x;
  35656. this._vertex.y *= this._particle.scale.y;
  35657. this._vertex.z *= this._particle.scale.z;
  35658. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  35659. 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;
  35660. 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;
  35661. 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;
  35662. if (this._computeParticleColor) {
  35663. this._colors32[colidx] = this._particle.color.r;
  35664. this._colors32[colidx + 1] = this._particle.color.g;
  35665. this._colors32[colidx + 2] = this._particle.color.b;
  35666. this._colors32[colidx + 3] = this._particle.color.a;
  35667. }
  35668. if (this._computeParticleTexture) {
  35669. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  35670. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  35671. }
  35672. }
  35673. index = idx + 3;
  35674. colorIndex = colidx + 4;
  35675. uvIndex = uvidx + 2;
  35676. }
  35677. if (update) {
  35678. if (this._computeParticleColor) {
  35679. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  35680. }
  35681. if (this._computeParticleTexture) {
  35682. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  35683. }
  35684. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  35685. if (!this.mesh.areNormalsFrozen) {
  35686. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32);
  35687. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  35688. }
  35689. }
  35690. this.afterUpdateParticles(start, end, update);
  35691. };
  35692. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  35693. this._halfroll = this._roll * 0.5;
  35694. this._halfpitch = this._pitch * 0.5;
  35695. this._halfyaw = this._yaw * 0.5;
  35696. this._sinRoll = Math.sin(this._halfroll);
  35697. this._cosRoll = Math.cos(this._halfroll);
  35698. this._sinPitch = Math.sin(this._halfpitch);
  35699. this._cosPitch = Math.cos(this._halfpitch);
  35700. this._sinYaw = Math.sin(this._halfyaw);
  35701. this._cosYaw = Math.cos(this._halfyaw);
  35702. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  35703. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  35704. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  35705. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  35706. };
  35707. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  35708. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  35709. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  35710. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  35711. this._rotMatrix.m[3] = 0;
  35712. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  35713. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  35714. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  35715. this._rotMatrix.m[7] = 0;
  35716. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  35717. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  35718. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  35719. this._rotMatrix.m[11] = 0;
  35720. this._rotMatrix.m[12] = 0;
  35721. this._rotMatrix.m[13] = 0;
  35722. this._rotMatrix.m[14] = 0;
  35723. this._rotMatrix.m[15] = 1.0;
  35724. };
  35725. // dispose the SPS
  35726. SolidParticleSystem.prototype.dispose = function () {
  35727. this.mesh.dispose();
  35728. };
  35729. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  35730. // getters
  35731. get: function () {
  35732. return this._computeParticleRotation;
  35733. },
  35734. // Optimizer setters
  35735. set: function (val) {
  35736. this._computeParticleRotation = val;
  35737. },
  35738. enumerable: true,
  35739. configurable: true
  35740. });
  35741. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  35742. get: function () {
  35743. return this._computeParticleColor;
  35744. },
  35745. set: function (val) {
  35746. this._computeParticleColor = val;
  35747. },
  35748. enumerable: true,
  35749. configurable: true
  35750. });
  35751. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  35752. get: function () {
  35753. return this._computeParticleTexture;
  35754. },
  35755. set: function (val) {
  35756. this._computeParticleTexture = val;
  35757. },
  35758. enumerable: true,
  35759. configurable: true
  35760. });
  35761. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  35762. get: function () {
  35763. return this._computeParticleVertex;
  35764. },
  35765. set: function (val) {
  35766. this._computeParticleVertex = val;
  35767. },
  35768. enumerable: true,
  35769. configurable: true
  35770. });
  35771. // =======================================================================
  35772. // Particle behavior logic
  35773. // these following methods may be overwritten by the user to fit his needs
  35774. // init : sets all particles first values and calls updateParticle to set them in space
  35775. // can be overwritten by the user
  35776. SolidParticleSystem.prototype.initParticles = function () {
  35777. };
  35778. // recycles a particle : can by overwritten by the user
  35779. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  35780. return particle;
  35781. };
  35782. // updates a particle : can be overwritten by the user
  35783. // will be called on each particle by setParticles() :
  35784. // ex : just set a particle position or velocity and recycle conditions
  35785. SolidParticleSystem.prototype.updateParticle = function (particle) {
  35786. return particle;
  35787. };
  35788. // updates a vertex of a particle : can be overwritten by the user
  35789. // will be called on each vertex particle by setParticles() :
  35790. // particle : the current particle
  35791. // vertex : the current index of the current particle
  35792. // pt : the index of the current vertex in the particle shape
  35793. // ex : just set a vertex particle position
  35794. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  35795. return vertex;
  35796. };
  35797. // will be called before any other treatment by setParticles()
  35798. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  35799. };
  35800. // will be called after all setParticles() treatments
  35801. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  35802. };
  35803. return SolidParticleSystem;
  35804. })();
  35805. BABYLON.SolidParticleSystem = SolidParticleSystem;
  35806. })(BABYLON || (BABYLON = {}));
  35807. BABYLON.Effect.ShadersStore={"anaglyphPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D leftSampler;\r\n\r\nvoid main(void)\r\n{\r\n vec4 leftFrag = texture2D(leftSampler, vUV);\r\n leftFrag = vec4(1.0, leftFrag.g, leftFrag.b, 1.0);\r\n\r\n\tvec4 rightFrag = texture2D(textureSampler, vUV);\r\n rightFrag = vec4(rightFrag.r, 1.0, 1.0, 1.0);\r\n\r\n gl_FragColor = vec4(rightFrag.rgb * leftFrag.rgb, 1.0);\r\n}","blackAndWhitePixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nvoid main(void) \r\n{\r\n\tfloat luminance = dot(texture2D(textureSampler, vUV).rgb, vec3(0.3, 0.59, 0.11));\r\n\tgl_FragColor = vec4(luminance, luminance, luminance, 1.0);\r\n}","blurPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Parameters\r\nuniform vec2 screenSize;\r\nuniform vec2 direction;\r\nuniform float blurWidth;\r\n\r\nvoid main(void)\r\n{\r\n\tfloat weights[7];\r\n\tweights[0] = 0.05;\r\n\tweights[1] = 0.1;\r\n\tweights[2] = 0.2;\r\n\tweights[3] = 0.3;\r\n\tweights[4] = 0.2;\r\n\tweights[5] = 0.1;\r\n\tweights[6] = 0.05;\r\n\r\n\tvec2 texelSize = vec2(1.0 / screenSize.x, 1.0 / screenSize.y);\r\n\tvec2 texelStep = texelSize * direction * blurWidth;\r\n\tvec2 start = vUV - 3.0 * texelStep;\r\n\r\n\tvec4 baseColor = vec4(0., 0., 0., 0.);\r\n\tvec2 texelOffset = vec2(0., 0.);\r\n\r\n\tfor (int i = 0; i < 7; i++)\r\n\t{\r\n\t\tbaseColor += texture2D(textureSampler, start + texelOffset) * weights[i];\r\n\t\ttexelOffset += texelStep;\r\n\t}\r\n\r\n\tgl_FragColor = baseColor;\r\n}","brickPixelShader":"precision highp float;\r\n\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nuniform float numberOfBricksHeight;\r\nuniform float numberOfBricksWidth;\r\nuniform vec3 brickColor;\r\nuniform vec3 jointColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nfloat round(float number){\r\n\treturn sign(number)*floor(abs(number) + 0.5);\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tfloat brickW = 1.0 / numberOfBricksWidth;\r\n\tfloat brickH = 1.0 / numberOfBricksHeight;\r\n\tfloat jointWPercentage = 0.01;\r\n\tfloat jointHPercentage = 0.05;\r\n\tvec3 color = brickColor;\r\n\tfloat yi = vUV.y / brickH;\r\n\tfloat nyi = round(yi);\r\n\tfloat xi = vUV.x / brickW;\r\n\r\n\tif (mod(floor(yi), 2.0) == 0.0){\r\n\t\txi = xi - 0.5;\r\n\t}\r\n\r\n\tfloat nxi = round(xi);\r\n\tvec2 brickvUV = vec2((xi - floor(xi)) / brickH, (yi - floor(yi)) / brickW);\r\n\r\n\tif (yi < nyi + jointHPercentage && yi > nyi - jointHPercentage){\r\n\t\tcolor = mix(jointColor, vec3(0.37, 0.25, 0.25), (yi - nyi) / jointHPercentage + 0.2);\r\n\t}\r\n\telse if (xi < nxi + jointWPercentage && xi > nxi - jointWPercentage){\r\n\t\tcolor = mix(jointColor, vec3(0.44, 0.44, 0.44), (xi - nxi) / jointWPercentage + 0.2);\r\n\t}\r\n\telse {\r\n\t\tfloat brickColorSwitch = mod(floor(yi) + floor(xi), 3.0);\r\n\r\n\t\tif (brickColorSwitch == 0.0)\r\n\t\t\tcolor = mix(color, vec3(0.33, 0.33, 0.33), 0.3);\r\n\t\telse if (brickColorSwitch == 2.0)\r\n\t\t\tcolor = mix(color, vec3(0.11, 0.11, 0.11), 0.3);\r\n\t}\r\n\r\n\tgl_FragColor = vec4(color, 1.0);\r\n}","chromaticAberrationPixelShader":"// BABYLON.JS Chromatic Aberration GLSL Shader\r\n// Author: Olivier Guyot\r\n// Separates very slightly R, G and B colors on the edges of the screen\r\n// Inspired by Francois Tarlier & Martins Upitis\r\n\r\nprecision highp float;\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\t// original color\r\n\r\n// uniforms\r\nuniform float chromatic_aberration;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 centered_screen_pos = vec2(vUV.x - 0.5, vUV.y - 0.5);\r\n\tfloat radius2 = centered_screen_pos.x*centered_screen_pos.x\r\n\t\t+ centered_screen_pos.y*centered_screen_pos.y;\r\n\tfloat radius = sqrt(radius2);\r\n\r\n\tvec4 original = texture2D(textureSampler, vUV);\r\n\r\n\tif (chromatic_aberration > 0.0) {\r\n\t\t//index of refraction of each color channel, causing chromatic dispersion\r\n\t\tvec3 ref_indices = vec3(-0.3, 0.0, 0.3);\r\n\t\tfloat ref_shiftX = chromatic_aberration * radius * 17.0 / screen_width;\r\n\t\tfloat ref_shiftY = chromatic_aberration * radius * 17.0 / screen_height;\r\n\r\n\t\t// shifts for red, green & blue\r\n\t\tvec2 ref_coords_r = vec2(vUV.x + ref_indices.r*ref_shiftX, vUV.y + ref_indices.r*ref_shiftY*0.5);\r\n\t\tvec2 ref_coords_g = vec2(vUV.x + ref_indices.g*ref_shiftX, vUV.y + ref_indices.g*ref_shiftY*0.5);\r\n\t\tvec2 ref_coords_b = vec2(vUV.x + ref_indices.b*ref_shiftX, vUV.y + ref_indices.b*ref_shiftY*0.5);\r\n\r\n\t\toriginal.r = texture2D(textureSampler, ref_coords_r).r;\r\n\t\toriginal.g = texture2D(textureSampler, ref_coords_g).g;\r\n\t\toriginal.b = texture2D(textureSampler, ref_coords_b).b;\r\n\t}\r\n\r\n\tgl_FragColor = original;\r\n}","cloudPixelShader":"precision highp float;\r\n\r\nvarying vec2 vUV;\r\n\r\nuniform vec4 skyColor;\r\nuniform vec4 cloudColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main() {\r\n\r\n\tvec2 p = vUV * 12.0;\r\n\tvec4 c = mix(skyColor, cloudColor, fbm(p));\r\n\tgl_FragColor = c;\r\n\r\n}\r\n\r\n","colorPixelShader":"precision highp float;\r\n\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tgl_FragColor = color;\r\n}","colorVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\n\r\n// Uniforms\r\nuniform mat4 worldViewProjection;\r\n\r\nvoid main(void) {\r\n\tgl_Position = worldViewProjection * vec4(position, 1.0);\r\n}","colorCorrectionPixelShader":"precision highp float;\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\t// screen render\r\nuniform sampler2D colorTable;\t\t// color table with modified colors\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// constants\r\nconst float SLICE_COUNT = 16.0;\t\t// how many slices in the color cube; 1 slice = 1 pixel\r\n// it means the image is 256x16 pixels\r\n\r\nvec4 sampleAs3DTexture(sampler2D texture, vec3 uv, float width) {\r\n\tfloat sliceSize = 1.0 / width; // space of 1 slice\r\n\tfloat slicePixelSize = sliceSize / width; // space of 1 pixel\r\n\tfloat sliceInnerSize = slicePixelSize * (width - 1.0); // space of width pixels\r\n\tfloat zSlice0 = min(floor(uv.z * width), width - 1.0);\r\n\tfloat zSlice1 = min(zSlice0 + 1.0, width - 1.0);\r\n\tfloat xOffset = slicePixelSize * 0.5 + uv.x * sliceInnerSize;\r\n\tfloat s0 = xOffset + (zSlice0 * sliceSize);\r\n\tfloat s1 = xOffset + (zSlice1 * sliceSize);\r\n\tvec4 slice0Color = texture2D(texture, vec2(s0, uv.y));\r\n\tvec4 slice1Color = texture2D(texture, vec2(s1, uv.y));\r\n\tfloat zOffset = mod(uv.z * width, 1.0);\r\n\tvec4 result = mix(slice0Color, slice1Color, zOffset);\r\n\treturn result;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 screen_color = texture2D(textureSampler, vUV);\r\n\tgl_FragColor = sampleAs3DTexture(colorTable, screen_color.rgb, SLICE_COUNT);\r\n\r\n}","convolutionPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nuniform vec2 screenSize;\r\nuniform float kernel[9];\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 onePixel = vec2(1.0, 1.0) / screenSize;\r\n\tvec4 colorSum =\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, -1)) * kernel[0] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, -1)) * kernel[1] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, -1)) * kernel[2] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, 0)) * kernel[3] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, 0)) * kernel[4] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, 0)) * kernel[5] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, 1)) * kernel[6] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, 1)) * kernel[7] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, 1)) * kernel[8];\r\n\r\n\tfloat kernelWeight =\r\n\t\tkernel[0] +\r\n\t\tkernel[1] +\r\n\t\tkernel[2] +\r\n\t\tkernel[3] +\r\n\t\tkernel[4] +\r\n\t\tkernel[5] +\r\n\t\tkernel[6] +\r\n\t\tkernel[7] +\r\n\t\tkernel[8];\r\n\r\n\tif (kernelWeight <= 0.0) {\r\n\t\tkernelWeight = 1.0;\r\n\t}\r\n\r\n\tgl_FragColor = vec4((colorSum / kernelWeight).rgb, 1);\r\n}","defaultPixelShader":"precision highp float;\r\n\r\n// Constants\r\n#define RECIPROCAL_PI2 0.15915494\r\n\r\nuniform vec3 vEyePosition;\r\nuniform vec3 vAmbientColor;\r\nuniform vec4 vDiffuseColor;\r\n#ifdef SPECULARTERM\r\nuniform vec4 vSpecularColor;\r\n#endif\r\nuniform vec3 vEmissiveColor;\r\n\r\n// Input\r\nvarying vec3 vPositionW;\r\n\r\n#ifdef NORMAL\r\nvarying vec3 vNormalW;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n// Lights\r\n#ifdef LIGHT0\r\nuniform vec4 vLightData0;\r\nuniform vec4 vLightDiffuse0;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular0;\r\n#endif\r\n#ifdef SHADOW0\r\nvarying vec4 vPositionFromLight0;\r\nuniform sampler2D shadowSampler0;\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\nvarying vec4 vPositionFromLight1;\r\nuniform sampler2D shadowSampler1;\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\nvarying vec4 vPositionFromLight2;\r\nuniform sampler2D shadowSampler2;\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\nvarying vec4 vPositionFromLight3;\r\nuniform sampler2D shadowSampler3;\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\n\tvarying vec3 vPositionUVW;\r\n#else\r\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\r\n\tvarying vec3 vDirectionW;\r\n#endif\r\n\r\n\t#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\r\n\t\tuniform mat4 reflectionMatrix;\r\n\t#endif\r\n\t#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION)\r\n\t\tuniform mat4 view;\r\n\t#endif\r\n#endif\r\n\r\nvec3 computeReflectionCoords(vec4 worldPos, vec3 worldNormal)\r\n{\r\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\r\n\tvec3 direction = normalize(vDirectionW);\r\n\r\n\tfloat t = clamp(direction.y * -0.5 + 0.5, 0., 1.0);\r\n\tfloat s = atan(direction.z, direction.x) * RECIPROCAL_PI2 + 0.5;\r\n\r\n\treturn vec3(s, t, 0);\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_SPHERICAL\r\n\tvec3 viewDir = normalize(vec3(view * worldPos));\r\n\tvec3 viewNormal = normalize(vec3(view * vec4(worldNormal, 0.0)));\r\n\r\n\tvec3 r = reflect(viewDir, viewNormal);\r\n\tr.z = r.z - 1.0;\r\n\r\n\tfloat m = 2.0 * length(r);\r\n\r\n\treturn vec3(r.x / m + 0.5, 1.0 - r.y / m - 0.5, 0);\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_PLANAR\r\n\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\tvec3 coords = normalize(reflect(viewDir, worldNormal));\r\n\r\n\treturn vec3(reflectionMatrix * vec4(coords, 1));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_CUBIC\r\n\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\tvec3 coords = reflect(viewDir, worldNormal);\r\n#ifdef INVERTCUBICMAP\r\n\tcoords.y = 1.0 - coords.y;\r\n#endif\r\n\treturn vec3(reflectionMatrix * vec4(coords, 0));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_PROJECTION\r\n\treturn vec3(reflectionMatrix * (view * worldPos));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_SKYBOX\r\n\treturn vPositionUVW;\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_EXPLICIT\r\n\treturn vec3(0, 0, 0);\r\n#endif\r\n}\r\n\r\n#ifdef REFLECTIONFRESNEL\r\nuniform vec4 reflectionLeftColor;\r\nuniform vec4 reflectionRightColor;\r\n#endif\r\n\r\n#endif\r\n\r\n// Shadows\r\n#ifdef SHADOWS\r\n\r\nfloat unpack(vec4 color)\r\n{\r\n\tconst vec4 bit_shift = vec4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0);\r\n\treturn dot(color, bit_shift);\r\n}\r\n\r\nfloat unpackHalf(vec2 color)\r\n{\r\n\treturn color.x + (color.y / 255.0);\r\n}\r\n\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 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\r\n// Bump\r\n#ifdef BUMP\r\n#extension GL_OES_standard_derivatives : enable\r\nvarying vec2 vBumpUV;\r\nuniform vec2 vBumpInfos;\r\nuniform sampler2D bumpSampler;\r\n\r\n// Thanks to http://www.thetenthplanet.de/archives/1180\r\nmat3 cotangent_frame(vec3 normal, vec3 p, vec2 uv)\r\n{\r\n\t// get edge vectors of the pixel triangle\r\n\tvec3 dp1 = dFdx(p);\r\n\tvec3 dp2 = dFdy(p);\r\n\tvec2 duv1 = dFdx(uv);\r\n\tvec2 duv2 = dFdy(uv);\r\n\r\n\t// solve the linear system\r\n\tvec3 dp2perp = cross(dp2, normal);\r\n\tvec3 dp1perp = cross(normal, dp1);\r\n\tvec3 tangent = dp2perp * duv1.x + dp1perp * duv2.x;\r\n\tvec3 binormal = dp2perp * duv1.y + dp1perp * duv2.y;\r\n\r\n\t// construct a scale-invariant frame \r\n\tfloat invmax = inversesqrt(max(dot(tangent, tangent), dot(binormal, binormal)));\r\n\treturn mat3(tangent * invmax, binormal * invmax, normal);\r\n}\r\n\r\nvec3 perturbNormal(vec3 viewDir)\r\n{\r\n\tvec3 map = texture2D(bumpSampler, vBumpUV).xyz;\r\n\tmap = map * 255. / 127. - 128. / 127.;\r\n\tmat3 TBN = cotangent_frame(vNormalW * vBumpInfos.y, -viewDir, vBumpUV);\r\n\treturn normalize(TBN * map);\r\n}\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn clamp(fogCoeff, 0.0, 1.0);\r\n}\r\n#endif\r\n\r\n// Light Computing\r\nstruct lightingInfo\r\n{\r\n\tvec3 diffuse;\r\n#ifdef SPECULARTERM\r\n\tvec3 specular;\r\n#endif\r\n};\r\n\r\nlightingInfo computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, float range, float glossiness) {\r\n\tlightingInfo result;\r\n\r\n\tvec3 lightVectorW;\r\n\tfloat attenuation = 1.0;\r\n\tif (lightData.w == 0.)\r\n\t{\r\n\t\tvec3 direction = lightData.xyz - vPositionW;\r\n\r\n\t\tattenuation = max(0., 1.0 - length(direction) / range);\r\n\t\tlightVectorW = normalize(direction);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tlightVectorW = normalize(-lightData.xyz);\r\n\t}\r\n\r\n\t// diffuse\r\n\tfloat ndl = max(0., dot(vNormal, lightVectorW));\r\n\tresult.diffuse = ndl * diffuseColor * attenuation;\r\n\r\n#ifdef SPECULARTERM\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightVectorW);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = pow(specComp, max(1., glossiness));\r\n\r\n\tresult.specular = specComp * specularColor * attenuation;\r\n#endif\r\n\treturn result;\r\n}\r\n\r\nlightingInfo computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec3 diffuseColor, vec3 specularColor, float range, float glossiness) {\r\n\tlightingInfo result;\r\n\r\n\tvec3 direction = lightData.xyz - vPositionW;\r\n\tvec3 lightVectorW = normalize(direction);\r\n\tfloat attenuation = max(0., 1.0 - length(direction) / range);\r\n\r\n\t// diffuse\r\n\tfloat cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\r\n\tfloat spotAtten = 0.0;\r\n\r\n\tif (cosAngle >= lightDirection.w)\r\n\t{\r\n\t\tcosAngle = max(0., pow(cosAngle, lightData.w));\r\n\t\tspotAtten = clamp((cosAngle - lightDirection.w) / (1. - cosAngle), 0.0, 1.0);\r\n\r\n\t\t// Diffuse\r\n\t\tfloat ndl = max(0., dot(vNormal, -lightDirection.xyz));\r\n\t\tresult.diffuse = ndl * spotAtten * diffuseColor * attenuation;\r\n\r\n#ifdef SPECULARTERM\r\n\t\t// Specular\r\n\t\tvec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\r\n\t\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\t\tspecComp = pow(specComp, max(1., glossiness));\r\n\r\n\t\tresult.specular = specComp * specularColor * spotAtten * attenuation;\r\n#endif\r\n\r\n\t\treturn result;\r\n\t}\r\n\r\n\tresult.diffuse = vec3(0.);\r\n#ifdef SPECULARTERM\r\n\tresult.specular = vec3(0.);\r\n#endif\r\n\r\n\treturn result;\r\n}\r\n\r\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, vec3 groundColor, float glossiness) {\r\n\tlightingInfo result;\r\n\r\n\t// Diffuse\r\n\tfloat ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\r\n\tresult.diffuse = mix(groundColor, diffuseColor, ndl);\r\n\r\n#ifdef SPECULARTERM\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightData.xyz);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = pow(specComp, max(1., glossiness));\r\n\r\n\tresult.specular = specComp * specularColor;\r\n#endif\r\n\r\n\treturn result;\r\n}\r\n\r\nvoid main(void) {\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tvec3 viewDirectionW = normalize(vEyePosition - vPositionW);\r\n\r\n\t// Base color\r\n\tvec4 baseColor = vec4(1., 1., 1., 1.);\r\n\tvec3 diffuseColor = vDiffuseColor.rgb;\r\n\r\n\t// Alpha\r\n\tfloat alpha = vDiffuseColor.a;\r\n\r\n#ifdef DIFFUSE\r\n\tbaseColor = texture2D(diffuseSampler, vDiffuseUV);\r\n\r\n#ifdef ALPHATEST\r\n\tif (baseColor.a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n#ifdef ALPHAFROMDIFFUSE\r\n\talpha *= baseColor.a;\r\n#endif\r\n\r\n\tbaseColor.rgb *= vDiffuseInfos.y;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\n\tbaseColor.rgb *= vColor.rgb;\r\n#endif\r\n\r\n\t// Bump\r\n#ifdef NORMAL\r\n\tvec3 normalW = normalize(vNormalW);\r\n#else\r\n\tvec3 normalW = vec3(1.0, 1.0, 1.0);\r\n#endif\r\n\r\n\r\n#ifdef BUMP\r\n\tnormalW = perturbNormal(viewDirectionW);\r\n#endif\r\n\r\n\t// Ambient color\r\n\tvec3 baseAmbientColor = vec3(1., 1., 1.);\r\n\r\n#ifdef AMBIENT\r\n\tbaseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\r\n#endif\r\n\r\n\r\n\t// Specular map\r\n#ifdef SPECULARTERM\r\n\tfloat glossiness = vSpecularColor.a;\r\n\tvec3 specularColor = vSpecularColor.rgb;\r\n\r\n#ifdef SPECULAR\r\n\tvec4 specularMapColor = texture2D(specularSampler, vSpecularUV);\r\n\tspecularColor = specularMapColor.rgb;\r\n#ifdef GLOSSINESS\r\n\tglossiness = glossiness * specularMapColor.a;\r\n#endif\r\n#endif\r\n#else\r\n\tfloat glossiness = 0.;\r\n#endif\r\n\r\n\t// Lighting\r\n\tvec3 diffuseBase = vec3(0., 0., 0.);\r\n#ifdef SPECULARTERM\r\n\tvec3 specularBase = vec3(0., 0., 0.);\r\n#endif\r\n\tfloat shadow = 1.;\r\n\r\n#ifdef LIGHT0\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular0 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT0\r\n\tlightingInfo info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a, glossiness);\r\n#endif\r\n#ifdef HEMILIGHT0\r\n\tlightingInfo info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightGround0, glossiness);\r\n#endif\r\n#ifdef POINTDIRLIGHT0\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\tshadow = computeShadowWithPCF(vPositionFromLight0, shadowSampler0, shadowsInfo0.y, shadowsInfo0.z, shadowsInfo0.x);\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.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#ifdef POINTDIRLIGHT1\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\tshadow = computeShadowWithPCF(vPositionFromLight1, shadowSampler1, shadowsInfo1.y, shadowsInfo1.z, shadowsInfo1.x);\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.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#ifdef POINTDIRLIGHT2\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\tshadow = computeShadowWithPCF(vPositionFromLight2, shadowSampler2, shadowsInfo2.y, shadowsInfo2.z, shadowsInfo2.x);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight2, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\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#ifdef POINTDIRLIGHT3\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\tshadow = computeShadowWithPCF(vPositionFromLight3, shadowSampler3, shadowsInfo3.y, shadowsInfo3.z, shadowsInfo3.x);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight3, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\r\n#endif\t\r\n#endif\t\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n#endif\r\n\r\n\t// Reflection\r\n\tvec3 reflectionColor = vec3(0., 0., 0.);\r\n\r\n\r\n#ifdef REFLECTION\r\n\tvec3 vReflectionUVW = computeReflectionCoords(vec4(vPositionW, 1.0), normalW);\r\n\r\n#ifdef REFLECTIONMAP_3D\r\n\tfloat bias = 0.;\r\n\r\n#ifdef ROUGHNESS\r\n\tbias = vReflectionInfos.y;\r\n#endif\r\n\r\n#ifdef SPECULARTERM\r\n#ifdef SPECULAR\r\n#ifdef GLOSSINESS\r\n\tbias *= (1.0 - specularMapColor.a);\r\n#endif\r\n#endif\r\n#endif\r\n\r\n\treflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW, bias).rgb * vReflectionInfos.x * shadow;\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 * shadow;\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\tvec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\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\t#ifdef USELIGHTMAPASSHADOWMAP\r\n\t\tcolor.rgb *= lightmapColor;\r\n\t#else\r\n\t\tcolor.rgb += lightmapColor;\r\n\t#endif\r\n#endif\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tcolor.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","defaultVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\n#ifdef NORMAL\r\nattribute vec3 normal;\r\n#endif\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#ifdef VERTEXCOLOR\r\nattribute vec4 color;\r\n#endif\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniforms\r\n\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 view;\r\nuniform mat4 viewProjection;\r\n\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform mat4 diffuseMatrix;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform mat4 ambientMatrix;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\r\nvarying vec2 vOpacityUV;\r\nuniform mat4 opacityMatrix;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform mat4 emissiveMatrix;\r\n#endif\r\n\r\n#ifdef LIGHTMAP\r\nvarying vec2 vLightmapUV;\r\nuniform vec2 vLightmapInfos;\r\nuniform mat4 lightmapMatrix;\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform mat4 specularMatrix;\r\n#endif\r\n\r\n#ifdef BUMP\r\nvarying vec2 vBumpUV;\r\nuniform vec2 vBumpInfos;\r\nuniform mat4 bumpMatrix;\r\n#endif\r\n\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\n#ifdef POINTSIZE\r\nuniform float pointSize;\r\n#endif\r\n\r\n// Output\r\nvarying vec3 vPositionW;\r\n#ifdef NORMAL\r\nvarying vec3 vNormalW;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\n#ifdef SHADOWS\r\n#ifdef LIGHT0\r\nuniform mat4 lightMatrix0;\r\nvarying vec4 vPositionFromLight0;\r\n#endif\r\n#ifdef LIGHT1\r\nuniform mat4 lightMatrix1;\r\nvarying vec4 vPositionFromLight1;\r\n#endif\r\n#ifdef LIGHT2\r\nuniform mat4 lightMatrix2;\r\nvarying vec4 vPositionFromLight2;\r\n#endif\r\n#ifdef LIGHT3\r\nuniform mat4 lightMatrix3;\r\nvarying vec4 vPositionFromLight3;\r\n#endif\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_SKYBOX\r\nvarying vec3 vPositionUVW;\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\r\nvarying vec3 vDirectionW;\r\n#endif\r\n\r\nvoid main(void) {\r\n\tmat4 finalWorld;\r\n\r\n#ifdef REFLECTIONMAP_SKYBOX\r\n\tvPositionUVW = position;\r\n#endif \r\n\r\n#ifdef INSTANCES\r\n\tfinalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tfinalWorld = world;\r\n#endif\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\r\n#ifdef BONES4\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\r\n#else\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2);\r\n#endif \r\n\r\n#endif\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n\r\n\tvec4 worldPos = finalWorld * vec4(position, 1.0);\r\n\tvPositionW = vec3(worldPos);\r\n\r\n#ifdef NORMAL\r\n\tvNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\r\n\tvDirectionW = normalize(vec3(finalWorld * vec4(position, 0.0)));\r\n#endif\r\n\r\n\t// Texture coordinates\r\n#ifndef UV1\r\n\tvec2 uv = vec2(0., 0.);\r\n#endif\r\n#ifndef UV2\r\n\tvec2 uv2 = vec2(0., 0.);\r\n#endif\r\n\r\n#ifdef DIFFUSE\r\n\tif (vDiffuseInfos.x == 0.)\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef AMBIENT\r\n\tif (vAmbientInfos.x == 0.)\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tif (vOpacityInfos.x == 0.)\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\n\tif (vEmissiveInfos.x == 0.)\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef LIGHTMAP\r\n\tif (vLightmapInfos.x == 0.)\r\n\t{\r\n\t\tvLightmapUV = vec2(lightmapMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvLightmapUV = vec2(lightmapMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\n\tif (vSpecularInfos.x == 0.)\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef BUMP\r\n\tif (vBumpInfos.x == 0.)\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = (view * worldPos).z;\r\n#endif\r\n\r\n\t// Shadows\r\n#ifdef SHADOWS\r\n#ifdef LIGHT0\r\n\tvPositionFromLight0 = lightMatrix0 * worldPos;\r\n#endif\r\n#ifdef LIGHT1\r\n\tvPositionFromLight1 = lightMatrix1 * worldPos;\r\n#endif\r\n#ifdef LIGHT2\r\n\tvPositionFromLight2 = lightMatrix2 * worldPos;\r\n#endif\r\n#ifdef LIGHT3\r\n\tvPositionFromLight3 = lightMatrix3 * worldPos;\r\n#endif\r\n#endif\r\n\r\n\t// Vertex color\r\n#ifdef VERTEXCOLOR\r\n\tvColor = color;\r\n#endif\r\n\r\n\t// Point size\r\n#ifdef POINTSIZE\r\n\tgl_PointSize = pointSize;\r\n#endif\r\n}","depthPixelShader":"precision highp float;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\nuniform float far;\r\n\r\nvoid main(void)\r\n{\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tfloat depth = (gl_FragCoord.z / gl_FragCoord.w) / far;\r\n\tgl_FragColor = vec4(depth, depth * depth, 0.0, 1.0);\r\n}","depthVertexShader":"precision highp float;\r\n\r\n// Attribute\r\nattribute vec3 position;\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniform\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 viewProjection;\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\n#if defined(ALPHATEST) || defined(NEED_UV)\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n#else\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n#endif\r\n\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}","depthBoxBlurPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Parameters\r\nuniform vec2 screenSize;\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 colorDepth = vec4(0.0);\r\n\r\n\tfor (int x = -OFFSET; x <= OFFSET; x++)\r\n\t\tfor (int y = -OFFSET; y <= OFFSET; y++)\r\n\t\t\tcolorDepth += texture2D(textureSampler, vUV + vec2(x, y) / screenSize);\r\n\r\n\tgl_FragColor = (colorDepth / float((OFFSET * 2 + 1) * (OFFSET * 2 + 1)));\r\n}","depthOfFieldPixelShader":"// BABYLON.JS Depth-of-field GLSL Shader\r\n// Author: Olivier Guyot\r\n// Does depth-of-field blur, edge blur\r\n// Inspired by Francois Tarlier & Martins Upitis\r\n\r\nprecision highp float;\r\n\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D highlightsSampler;\r\nuniform sampler2D depthSampler;\r\nuniform sampler2D grainSampler;\r\n\r\n// uniforms\r\nuniform float grain_amount;\r\nuniform bool blur_noise;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\nuniform float distortion;\r\nuniform bool dof_enabled;\r\n//uniform float focus_distance;\t\t// not needed; already used to compute screen distance\r\nuniform float screen_distance;\t\t// precomputed screen distance from lens center; based on focal length & desired focus distance\r\nuniform float aperture;\r\nuniform float darken;\r\nuniform float edge_blur;\r\nuniform bool highlights;\r\n\r\n// preconputed uniforms (not effect parameters)\r\nuniform float near;\r\nuniform float far;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// constants\r\n#define PI \t\t3.14159265\r\n#define TWOPI \t6.28318530\r\n#define inverse_focal_length 0.1\t// a property of the lens used\r\n\r\n// common calculations\r\nvec2 centered_screen_pos;\r\nvec2 distorted_coords;\r\nfloat radius2;\r\nfloat radius;\r\n\r\n\r\n// on-the-fly constant noise\r\nvec2 rand(vec2 co)\r\n{\r\n\tfloat noise1 = (fract(sin(dot(co, vec2(12.9898, 78.233))) * 43758.5453));\r\n\tfloat noise2 = (fract(sin(dot(co, vec2(12.9898, 78.233)*2.0)) * 43758.5453));\r\n\treturn clamp(vec2(noise1, noise2), 0.0, 1.0);\r\n}\r\n\r\n// applies edge distortion on texture coords\r\nvec2 getDistortedCoords(vec2 coords) {\r\n\r\n\tif (distortion == 0.0) { return coords; }\r\n\r\n\tvec2 direction = 1.0 * normalize(centered_screen_pos);\r\n\tvec2 dist_coords = vec2(0.5, 0.5);\r\n\tdist_coords.x = 0.5 + direction.x * radius2 * 1.0;\r\n\tdist_coords.y = 0.5 + direction.y * radius2 * 1.0;\r\n\tfloat dist_amount = clamp(distortion*0.23, 0.0, 1.0);\r\n\r\n\tdist_coords = mix(coords, dist_coords, dist_amount);\r\n\r\n\treturn dist_coords;\r\n}\r\n\r\n// sample screen with an offset (randomize offset angle for better smothness), returns partial sample weight\r\nfloat sampleScreen(inout vec4 color, const in vec2 offset, const in float weight) {\r\n\r\n\t// compute coords with offset (a random angle is added)\r\n\tvec2 coords = distorted_coords;\r\n\tfloat angle = rand(coords * 100.0).x * TWOPI;\r\n\tcoords += vec2(offset.x * cos(angle) - offset.y * sin(angle), offset.x * sin(angle) + offset.y * cos(angle));\r\n\r\n\tcolor += texture2D(textureSampler, coords)*weight;\r\n\r\n\treturn weight;\r\n}\r\n\r\n// returns blur level according to blur size required\r\nfloat getBlurLevel(float size) {\r\n\treturn min(3.0, ceil(size / 1.0));\r\n}\r\n\r\n// returns original screen color after blur\r\nvec4 getBlurColor(float size) {\r\n\r\n\tvec4 col = texture2D(textureSampler, distorted_coords);\r\n\tif (size == 0.0) { return col; }\r\n\r\n\t// there are max. 30 samples; the number of samples chosen is dependant on the blur size\r\n\t// there can be 10, 20 or 30 samples chosen; levels of blur are then 1, 2 or 3\r\n\tfloat blur_level = getBlurLevel(size);\r\n\r\n\tfloat w = (size / screen_width);\r\n\tfloat h = (size / screen_height);\r\n\tfloat total_weight = 1.0;\r\n\tvec2 sample_coords;\r\n\r\n\ttotal_weight += sampleScreen(col, vec2(-0.50*w, 0.24*h), 0.93);\r\n\ttotal_weight += sampleScreen(col, vec2(0.30*w, -0.75*h), 0.90);\r\n\ttotal_weight += sampleScreen(col, vec2(0.36*w, 0.96*h), 0.87);\r\n\ttotal_weight += sampleScreen(col, vec2(-1.08*w, -0.55*h), 0.85);\r\n\ttotal_weight += sampleScreen(col, vec2(1.33*w, -0.37*h), 0.83);\r\n\ttotal_weight += sampleScreen(col, vec2(-0.82*w, 1.31*h), 0.80);\r\n\ttotal_weight += sampleScreen(col, vec2(-0.31*w, -1.67*h), 0.78);\r\n\ttotal_weight += sampleScreen(col, vec2(1.47*w, 1.11*h), 0.76);\r\n\ttotal_weight += sampleScreen(col, vec2(-1.97*w, 0.19*h), 0.74);\r\n\ttotal_weight += sampleScreen(col, vec2(1.42*w, -1.57*h), 0.72);\r\n\r\n\tif (blur_level > 1.0) {\r\n\t\ttotal_weight += sampleScreen(col, vec2(0.01*w, 2.25*h), 0.70);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-1.62*w, -1.74*h), 0.67);\r\n\t\ttotal_weight += sampleScreen(col, vec2(2.49*w, 0.20*h), 0.65);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-2.07*w, 1.61*h), 0.63);\r\n\t\ttotal_weight += sampleScreen(col, vec2(0.46*w, -2.70*h), 0.61);\r\n\t\ttotal_weight += sampleScreen(col, vec2(1.55*w, 2.40*h), 0.59);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-2.88*w, -0.75*h), 0.56);\r\n\t\ttotal_weight += sampleScreen(col, vec2(2.73*w, -1.44*h), 0.54);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-1.08*w, 3.02*h), 0.52);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-1.28*w, -3.05*h), 0.49);\r\n\t}\r\n\r\n\tif (blur_level > 2.0) {\r\n\t\ttotal_weight += sampleScreen(col, vec2(3.11*w, 1.43*h), 0.46);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-3.36*w, 1.08*h), 0.44);\r\n\t\ttotal_weight += sampleScreen(col, vec2(1.80*w, -3.16*h), 0.41);\r\n\t\ttotal_weight += sampleScreen(col, vec2(0.83*w, 3.65*h), 0.38);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-3.16*w, -2.19*h), 0.34);\r\n\t\ttotal_weight += sampleScreen(col, vec2(3.92*w, -0.53*h), 0.31);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-2.59*w, 3.12*h), 0.26);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-0.20*w, -4.15*h), 0.22);\r\n\t\ttotal_weight += sampleScreen(col, vec2(3.02*w, 3.00*h), 0.15);\r\n\t}\r\n\r\n\tcol /= total_weight;\t\t// scales color according to weights\r\n\r\n\t\t\t\t\t\t\t\t// darken if out of focus\r\n\tif (darken > 0.0) {\r\n\t\tcol.rgb *= clamp(0.3, 1.0, 1.05 - size*0.5*darken);\r\n\t}\r\n\r\n\t// blur levels debug\r\n\t// if(blur_level == 1.0) { col.b *= 0.5; }\r\n\t// if(blur_level == 2.0) { col.r *= 0.5; }\r\n\t// if(blur_level == 3.0) { col.g *= 0.5; }\r\n\r\n\treturn col;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\r\n\t// Common calc: position relative to screen center, screen radius, distorted coords, position in texel space\r\n\tcentered_screen_pos = vec2(vUV.x - 0.5, vUV.y - 0.5);\r\n\tradius2 = centered_screen_pos.x*centered_screen_pos.x + centered_screen_pos.y*centered_screen_pos.y;\r\n\tradius = sqrt(radius2);\r\n\tdistorted_coords = getDistortedCoords(vUV);\t\t// we distort the screen coordinates (lens \"magnifying\" effect)\r\n\tvec2 texels_coords = vec2(vUV.x * screen_width, vUV.y * screen_height);\t// varies from 0 to SCREEN_WIDTH or _HEIGHT\r\n\r\n\tfloat depth = texture2D(depthSampler, distorted_coords).r;\t// depth value from DepthRenderer: 0 to 1\r\n\tfloat distance = near + (far - near)*depth;\t\t// actual distance from the lens\r\n\tvec4 color = texture2D(textureSampler, vUV);\t// original raster\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t// compute the circle of confusion size (CoC), i.e. blur radius depending on depth\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t// screen_distance is precomputed in code\r\n\tfloat coc = abs(aperture * (screen_distance * (inverse_focal_length - 1.0 / distance) - 1.0));\r\n\r\n\t// disable blur\r\n\tif (dof_enabled == false || coc < 0.07) { coc = 0.0; }\r\n\r\n\t// blur from edge blur effect\r\n\tfloat edge_blur_amount = 0.0;\r\n\tif (edge_blur > 0.0) {\r\n\t\tedge_blur_amount = clamp((radius*2.0 - 1.0 + 0.15*edge_blur) * 1.5, 0.0, 1.0) * 1.3;\r\n\t}\r\n\r\n\t// total blur amount\r\n\tfloat blur_amount = max(edge_blur_amount, coc);\r\n\r\n\t// apply blur if necessary\r\n\tif (blur_amount == 0.0) {\r\n\t\tgl_FragColor = texture2D(textureSampler, distorted_coords);\r\n\t}\r\n\telse {\r\n\r\n\t\t// add blurred color\r\n\t\tgl_FragColor = getBlurColor(blur_amount * 1.7);\r\n\r\n\t\t// if we have computed highlights: enhance highlights\r\n\t\tif (highlights) {\r\n\t\t\tgl_FragColor.rgb += clamp(coc, 0.0, 1.0)*texture2D(highlightsSampler, distorted_coords).rgb;\r\n\t\t}\r\n\r\n\t\tif (blur_noise) {\r\n\t\t\t// we put a slight amount of noise in the blurred color\r\n\t\t\tvec2 noise = rand(distorted_coords) * 0.01 * blur_amount;\r\n\t\t\tvec2 blurred_coord = vec2(distorted_coords.x + noise.x, distorted_coords.y + noise.y);\r\n\t\t\tgl_FragColor = 0.04 * texture2D(textureSampler, blurred_coord) + 0.96 * gl_FragColor;\r\n\t\t}\r\n\t}\r\n\r\n\r\n\t// apply grain\r\n\tif (grain_amount > 0.0) {\r\n\t\tvec4 grain_color = texture2D(grainSampler, texels_coords*0.003);\r\n\t\tgl_FragColor.rgb += (-0.5 + grain_color.rgb) * 0.30 * grain_amount;\r\n\t}\r\n\r\n}\r\n","displayPassPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D passSampler;\r\n\r\nvoid main(void)\r\n{\r\n gl_FragColor = texture2D(passSampler, vUV);\r\n}","filterPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nuniform mat4 kernelMatrix;\r\n\r\nvoid main(void)\r\n{\r\n\tvec3 baseColor = texture2D(textureSampler, vUV).rgb;\r\n\tvec3 updatedColor = (kernelMatrix * vec4(baseColor, 1.0)).rgb;\r\n\r\n\tgl_FragColor = vec4(updatedColor, 1.0);\r\n}","firePixelShader":"precision highp float;\r\n\r\nuniform float time;\r\nuniform vec3 c1;\r\nuniform vec3 c2;\r\nuniform vec3 c3;\r\nuniform vec3 c4;\r\nuniform vec3 c5;\r\nuniform vec3 c6;\r\nuniform vec2 speed;\r\nuniform float shift;\r\nuniform float alphaThreshold;\r\n\r\nvarying vec2 vUV;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main() {\r\n\tvec2 p = vUV * 8.0;\r\n\tfloat q = fbm(p - time * 0.1);\r\n\tvec2 r = vec2(fbm(p + q + time * speed.x - p.x - p.y), fbm(p + q - time * speed.y));\r\n\tvec3 c = mix(c1, c2, fbm(p + r)) + mix(c3, c4, r.x) - mix(c5, c6, r.y);\r\n\tvec3 color = c * cos(shift * vUV.y);\r\n\tfloat luminance = dot(color.rgb, vec3(0.3, 0.59, 0.11));\r\n\r\n\tgl_FragColor = vec4(color, luminance * alphaThreshold + (1.0 - alphaThreshold));\r\n}","fxaaPixelShader":"precision highp float;\r\n\r\n#define FXAA_REDUCE_MIN (1.0/128.0)\r\n#define FXAA_REDUCE_MUL (1.0/8.0)\r\n#define FXAA_SPAN_MAX 8.0\r\n\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 texelSize;\r\n\r\nvoid main(){\r\n\tvec2 localTexelSize = texelSize;\r\n\tvec4 rgbNW = texture2D(textureSampler, (vUV + vec2(-1.0, -1.0) * localTexelSize));\r\n\tvec4 rgbNE = texture2D(textureSampler, (vUV + vec2(1.0, -1.0) * localTexelSize));\r\n\tvec4 rgbSW = texture2D(textureSampler, (vUV + vec2(-1.0, 1.0) * localTexelSize));\r\n\tvec4 rgbSE = texture2D(textureSampler, (vUV + vec2(1.0, 1.0) * localTexelSize));\r\n\tvec4 rgbM = texture2D(textureSampler, vUV);\r\n\tvec4 luma = vec4(0.299, 0.587, 0.114, 1.0);\r\n\tfloat lumaNW = dot(rgbNW, luma);\r\n\tfloat lumaNE = dot(rgbNE, luma);\r\n\tfloat lumaSW = dot(rgbSW, luma);\r\n\tfloat lumaSE = dot(rgbSE, luma);\r\n\tfloat lumaM = dot(rgbM, luma);\r\n\tfloat lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\r\n\tfloat lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\r\n\r\n\tvec2 dir = vec2(-((lumaNW + lumaNE) - (lumaSW + lumaSE)), ((lumaNW + lumaSW) - (lumaNE + lumaSE)));\r\n\r\n\tfloat dirReduce = max(\r\n\t\t(lumaNW + lumaNE + lumaSW + lumaSE) * (0.25 * FXAA_REDUCE_MUL),\r\n\t\tFXAA_REDUCE_MIN);\r\n\r\n\tfloat rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\r\n\tdir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),\r\n\t\tmax(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),\r\n\t\tdir * rcpDirMin)) * localTexelSize;\r\n\r\n\tvec4 rgbA = 0.5 * (\r\n\t\ttexture2D(textureSampler, vUV + dir * (1.0 / 3.0 - 0.5)) +\r\n\t\ttexture2D(textureSampler, vUV + dir * (2.0 / 3.0 - 0.5)));\r\n\r\n\tvec4 rgbB = rgbA * 0.5 + 0.25 * (\r\n\t\ttexture2D(textureSampler, vUV + dir * -0.5) +\r\n\t\ttexture2D(textureSampler, vUV + dir * 0.5));\r\n\tfloat lumaB = dot(rgbB, luma);\r\n\tif ((lumaB < lumaMin) || (lumaB > lumaMax)) {\r\n\t\tgl_FragColor = rgbA;\r\n\t}\r\n\telse {\r\n\t\tgl_FragColor = rgbB;\r\n\t}\r\n}","grassPixelShader":"precision highp float;\r\n\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nuniform vec3 herb1Color;\r\nuniform vec3 herb2Color;\r\nuniform vec3 herb3Color;\r\nuniform vec3 groundColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main(void) {\r\n\tvec3 color = mix(groundColor, herb1Color, rand(gl_FragCoord.xy * 4.0));\r\n\tcolor = mix(color, herb2Color, rand(gl_FragCoord.xy * 8.0));\r\n\tcolor = mix(color, herb3Color, rand(gl_FragCoord.xy));\r\n\tcolor = mix(color, herb1Color, fbm(gl_FragCoord.xy * 16.0));\r\n\tgl_FragColor = vec4(color, 1.0);\r\n}","hdrPixelShader":"precision highp float;\r\n\r\nuniform sampler2D textureSampler;\r\nvarying vec2 vUV;\r\n\r\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\r\nuniform float blurOffsets[9];\r\nuniform float blurWeights[9];\r\n\r\nvoid main(void) {\r\n\tvec4 color = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\tfor (int i = 0; i < 9; i++) {\r\n\t\t#ifdef GAUSSIAN_BLUR_H\r\n\t\tcolor += (texture2D(textureSampler, vUV + vec2(blurOffsets[i], 0.0)) * blurWeights[i]);\r\n\t\t#else\r\n\t\tcolor += (texture2D(textureSampler, vUV + vec2(0.0, blurOffsets[i])) * blurWeights[i]);\r\n\t\t#endif\r\n\t}\r\n\r\n\tcolor.a = 1.0;\r\n\tgl_FragColor = color;\r\n}\r\n#endif\r\n\r\n#if defined(TEXTURE_ADDER)\r\nuniform sampler2D otherSampler;\r\n\r\nvoid main() {\r\n\tvec4 sum = texture2D(textureSampler, vUV) + texture2D(otherSampler, vUV);\r\n\tsum.a = clamp(sum.a, 0.0, 1.0);\r\n\r\n\tgl_FragColor = sum;\r\n}\r\n#endif\r\n\r\n#if defined(LUMINANCE_GENERATOR)\r\nuniform vec2 lumOffsets[4];\r\n\r\nvoid main() {\r\n\tfloat average = 0.0;\r\n\tvec4 color = vec4(0.0, 0.0, 0.0, 0.0);\r\n\tfloat maximum = -1e20;\r\n\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\tcolor = texture2D(textureSampler, vUV + lumOffsets[i]);\r\n\r\n\t\tfloat GreyValue = length(color.rgb);\r\n\r\n\t\tmaximum = max(maximum, GreyValue);\r\n\t\taverage += (0.25 * log(1e-5 + GreyValue));\r\n\t}\r\n\r\n\taverage = exp(average);\r\n\r\n\tgl_FragColor = vec4(average, maximum, 0.0, 1.0);\r\n\r\n}\r\n#endif\r\n\r\n#if defined(DOWN_SAMPLE)\r\nuniform vec2 dsOffsets[9];\r\nuniform float halfDestPixelSize;\r\n\r\n#ifdef FINAL_DOWN_SAMPLE\r\nvec4 pack(float value) {\r\n\tconst vec4 bit_shift = vec4(255.0 * 255.0 * 255.0, 255.0 * 255.0, 255.0, 1.0);\r\n\tconst vec4 bit_mask = vec4(0.0, 1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0);\r\n\r\n\tvec4 res = fract(value * bit_shift);\r\n\tres -= res.xxyz * bit_mask;\r\n\r\n\treturn res;\r\n}\r\n#endif\r\n\r\nvoid main() {\r\n\tvec4 color = vec4(0.0, 0.0, 0.0, 0.0);\r\n\tfloat average = 0.0;\r\n\r\n\tfor (int i = 0; i < 9; i++) {\r\n\t\tcolor = texture2D(textureSampler, vUV + vec2(halfDestPixelSize, halfDestPixelSize) + dsOffsets[i]);\r\n\t\taverage += color.r;\r\n\t}\r\n\r\n\taverage /= 9.0;\r\n\r\n\t#ifndef FINAL_DOWN_SAMPLE\r\n\tgl_FragColor = vec4(average, average, 0.0, 1.0);\r\n\t#else\r\n\tgl_FragColor = pack(average);\r\n\t#endif\r\n}\r\n#endif\r\n\r\n#if defined(BRIGHT_PASS)\r\nuniform vec2 dsOffsets[4];\r\nuniform float brightThreshold;\r\n\r\nvoid main() {\r\n\tvec4 average = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\taverage = texture2D(textureSampler, vUV + vec2(dsOffsets[0].x, dsOffsets[0].y));\r\n\taverage += texture2D(textureSampler, vUV + vec2(dsOffsets[1].x, dsOffsets[1].y));\r\n\taverage += texture2D(textureSampler, vUV + vec2(dsOffsets[2].x, dsOffsets[2].y));\r\n\taverage += texture2D(textureSampler, vUV + vec2(dsOffsets[3].x, dsOffsets[3].y));\r\n\r\n\taverage *= 0.25;\r\n\r\n\tfloat luminance = length(average.rgb);\r\n\r\n\tif (luminance < brightThreshold) {\r\n\t\taverage = vec4(0.0, 0.0, 0.0, 1.0);\r\n\t}\r\n\r\n\tgl_FragColor = average;\r\n}\r\n#endif\r\n\r\n#if defined(DOWN_SAMPLE_X4)\r\nuniform vec2 dsOffsets[16];\r\n\r\nvoid main() {\r\n\tvec4 average = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\taverage = texture2D(textureSampler, vUV + dsOffsets[0]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[1]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[2]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[3]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[4]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[5]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[6]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[7]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[8]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[9]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[10]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[11]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[12]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[13]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[14]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[15]);\r\n\r\n\taverage /= 16.0;\r\n\r\n\tgl_FragColor = average;\r\n}\r\n#endif\r\n\r\n#if defined(HDR)\r\nuniform sampler2D otherSampler;\r\n\r\nuniform float exposure;\r\nuniform float avgLuminance;\r\n\r\nvoid main() {\r\n\tvec4 color = texture2D(textureSampler, vUV) + texture2D(otherSampler, vUV);\r\n\tvec4 adjustedColor = color / avgLuminance * exposure;\r\n\r\n\tcolor = adjustedColor;\r\n\tcolor.a = 1.0;\r\n\r\n\tgl_FragColor = color;\r\n}\r\n#endif\r\n","layerPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Color\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(textureSampler, vUV);\r\n\r\n\tgl_FragColor = baseColor * color;\r\n}","layerVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Uniforms\r\nuniform mat4 textureMatrix;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\r\n\tvUV = vec2(textureMatrix * vec4(position * madd + madd, 1.0, 0.0));\r\n\tgl_Position = vec4(position, 0.0, 1.0);\r\n}","legacydefaultPixelShader":"precision highp float;\r\n\r\n#define MAP_PROJECTION\t4.\r\n\r\n// Constants\r\nuniform vec3 vEyePosition;\r\nuniform vec3 vAmbientColor;\r\nuniform vec4 vDiffuseColor;\r\n#ifdef SPECULARTERM\r\nuniform vec4 vSpecularColor;\r\n#endif\r\nuniform vec3 vEmissiveColor;\r\n\r\n// Input\r\nvarying vec3 vPositionW;\r\nvarying vec3 vNormalW;\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n// Lights\r\n#ifdef LIGHT0\r\nuniform vec4 vLightData0;\r\nuniform vec4 vLightDiffuse0;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular0;\r\n#endif\r\n#ifdef SHADOW0\r\nvarying vec4 vPositionFromLight0;\r\nuniform sampler2D shadowSampler0;\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\nvarying vec4 vPositionFromLight1;\r\nuniform sampler2D shadowSampler1;\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\nvarying vec4 vPositionFromLight2;\r\nuniform sampler2D shadowSampler2;\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\nvarying vec4 vPositionFromLight3;\r\nuniform sampler2D shadowSampler3;\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 bitShift = vec4(1. / (255. * 255. * 255.), 1. / (255. * 255.), 1. / 255., 1.);\r\n\treturn dot(color, bitShift);\r\n}\r\n\r\nfloat unpackHalf(vec2 color)\r\n{\r\n\treturn color.x + (color.y / 255.0);\r\n}\r\n\r\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tvec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\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));\r\n\r\n\tif (depth.z > shadow)\r\n\t{\r\n\t\treturn 0.;\r\n\t}\r\n\treturn 1.;\r\n}\r\n\r\n// Thanks to http://devmaster.net/\r\nfloat ChebychevInequality(vec2 moments, float t)\r\n{\r\n\tif (t <= moments.x)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat variance = moments.y - (moments.x * moments.x);\r\n\tvariance = max(variance, 0.);\r\n\r\n\tfloat d = t - moments.x;\r\n\treturn variance / (variance + d * d);\r\n}\r\n\r\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tvec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\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\tvec4 texel = texture2D(shadowSampler, uv);\r\n\r\n\tvec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\r\n\treturn clamp(1.3 - ChebychevInequality(moments, depth.z), 0., 1.0);\r\n}\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn clamp(fogCoeff, 0.0, 1.0);\r\n}\r\n#endif\r\n\r\n// Light Computing\r\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#ifdef POINTDIRLIGHT0\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);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight0, shadowSampler0);\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#ifdef POINTDIRLIGHT1\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);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight1, shadowSampler1);\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#ifdef POINTDIRLIGHT2\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);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight2, shadowSampler2);\r\n#endif\t\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#ifdef POINTDIRLIGHT3\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);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight3, shadowSampler3);\r\n#endif\t\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n#endif\r\n\r\n\t// Reflection\r\n\tvec3 reflectionColor = vec3(0., 0., 0.);\r\n\r\n#ifdef REFLECTION\r\n#ifdef REFLECTIONMAP_3D\r\n\t\treflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.x;\r\n#else\r\n\t\tvec2 coords = vReflectionUVW.xy;\r\n\r\n#ifdef REFLECTIONMAP_PROJECTION\r\n\t\tcoords /= vReflectionUVW.z;\r\n#endif\r\n\r\n\t\tcoords.y = 1.0 - coords.y;\r\n\r\n\t\treflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.x;\r\n#endif\r\n\r\n#ifdef REFLECTIONFRESNEL\r\n\tfloat reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\r\n\r\n\treflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#endif\r\n#endif\r\n\r\n\t// Alpha\r\n\tfloat alpha = vDiffuseColor.a;\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\r\n#ifdef OPACITYRGB\r\n\topacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\r\n#else\r\n\talpha *= opacityMap.a * vOpacityInfos.y;\r\n#endif\r\n#endif\r\n\r\n#ifdef VERTEXALPHA\r\n\talpha *= vColor.a;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\n\tfloat opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\r\n\r\n\talpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\r\n#endif\r\n\r\n\t// Emissive\r\n\tvec3 emissiveColor = vEmissiveColor;\r\n#ifdef EMISSIVE\r\n\temissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\n\tfloat emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\r\n\r\n\temissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\r\n#endif\r\n\r\n\t// Specular map\r\n#ifdef SPECULARTERM\r\n\tvec3 specularColor = vSpecularColor.rgb;\r\n#ifdef SPECULAR\r\n\tspecularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\r\n#endif\r\n#endif\r\n\r\n\t// Fresnel\r\n#ifdef DIFFUSEFRESNEL\r\n\tfloat diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\r\n\r\n\tdiffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\r\n#endif\r\n\r\n\t// Composition\r\n\tvec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n#ifdef SPECULARTERM\r\n\tvec3 finalSpecular = specularBase * specularColor;\r\n#else\r\n\tvec3 finalSpecular = vec3(0.0);\r\n#endif\r\n\r\n\tvec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tcolor.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","legacydefaultVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\nattribute vec3 normal;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#ifdef VERTEXCOLOR\r\nattribute vec4 color;\r\n#endif\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniforms\r\nuniform mat4 world;\r\nuniform mat4 view;\r\nuniform mat4 viewProjection;\r\n\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform mat4 diffuseMatrix;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform mat4 ambientMatrix;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\r\nvarying vec2 vOpacityUV;\r\nuniform mat4 opacityMatrix;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform mat4 emissiveMatrix;\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform mat4 specularMatrix;\r\n#endif\r\n\r\n#ifdef BUMP\r\nvarying vec2 vBumpUV;\r\nuniform vec2 vBumpInfos;\r\nuniform mat4 bumpMatrix;\r\n#endif\r\n\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\n// Output\r\nvarying vec3 vPositionW;\r\nvarying vec3 vNormalW;\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\n#ifdef SHADOWS\r\n#ifdef LIGHT0\r\nuniform mat4 lightMatrix0;\r\nvarying vec4 vPositionFromLight0;\r\n#endif\r\n#ifdef LIGHT1\r\nuniform mat4 lightMatrix1;\r\nvarying vec4 vPositionFromLight1;\r\n#endif\r\n#ifdef LIGHT2\r\nuniform mat4 lightMatrix2;\r\nvarying vec4 vPositionFromLight2;\r\n#endif\r\n#ifdef LIGHT3\r\nuniform mat4 lightMatrix3;\r\nvarying vec4 vPositionFromLight3;\r\n#endif\r\n#endif\r\n\r\n#ifdef REFLECTION\r\nuniform vec3 vEyePosition;\r\nvarying vec3 vReflectionUVW;\r\nuniform mat4 reflectionMatrix;\r\n\r\nvec3 computeReflectionCoords(vec4 worldPos, vec3 worldNormal)\r\n{\r\n#ifdef REFLECTIONMAP_SPHERICAL\r\n\tvec3 coords = vec3(view * vec4(worldNormal, 0.0));\r\n\r\n\treturn vec3(reflectionMatrix * vec4(coords, 1.0));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_PLANAR\r\n\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\tvec3 coords = normalize(reflect(viewDir, worldNormal));\r\n\r\n\treturn vec3(reflectionMatrix * vec4(coords, 1));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_CUBIC\r\n\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\tvec3 coords = reflect(viewDir, worldNormal);\r\n#ifdef INVERTCUBICMAP\r\n\tcoords.y = 1.0 - coords.y;\r\n#endif\r\n\treturn vec3(reflectionMatrix * vec4(coords, 0));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_PROJECTION\r\n\treturn vec3(reflectionMatrix * (view * worldPos));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_SKYBOX\r\n\treturn position;\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_EXPLICIT\r\n\treturn vec3(0, 0, 0);\r\n#endif\r\n}\r\n#endif\r\n\r\nvoid main(void) {\r\n\tmat4 finalWorld;\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\r\n#ifdef BONES4\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = world * (m0 + m1 + m2 + m3);\r\n#else\r\n\tfinalWorld = world * (m0 + m1 + m2);\r\n#endif \r\n\r\n#else\r\n\tfinalWorld = world;\r\n#endif\r\n\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n\r\n\tvec4 worldPos = finalWorld * vec4(position, 1.0);\r\n\tvPositionW = vec3(worldPos);\r\n\tvNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\r\n\r\n\t// Texture coordinates\r\n#ifndef UV1\r\n\tvec2 uv = vec2(0., 0.);\r\n#endif\r\n#ifndef UV2\r\n\tvec2 uv2 = vec2(0., 0.);\r\n#endif\r\n\r\n#ifdef DIFFUSE\r\n\tif (vDiffuseInfos.x == 0.)\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef AMBIENT\r\n\tif (vAmbientInfos.x == 0.)\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tif (vOpacityInfos.x == 0.)\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\t\r\n#ifdef REFLECTION\r\n\tvReflectionUVW = computeReflectionCoords(vec4(vPositionW, 1.0), vNormalW);\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\n\tif (vEmissiveInfos.x == 0.)\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\n\tif (vSpecularInfos.x == 0.)\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef BUMP\r\n\tif (vBumpInfos.x == 0.)\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = (view * worldPos).z;\r\n#endif\r\n\r\n\t// Shadows\r\n#ifdef SHADOWS\r\n#ifdef LIGHT0\r\n\tvPositionFromLight0 = lightMatrix0 * worldPos;\r\n#endif\r\n#ifdef LIGHT1\r\n\tvPositionFromLight1 = lightMatrix1 * worldPos;\r\n#endif\r\n#ifdef LIGHT2\r\n\tvPositionFromLight2 = lightMatrix2 * worldPos;\r\n#endif\r\n#ifdef LIGHT3\r\n\tvPositionFromLight3 = lightMatrix3 * worldPos;\r\n#endif\r\n#endif\r\n\r\n\t// Vertex color\r\n#ifdef VERTEXCOLOR\r\n\tvColor = color;\r\n#endif\r\n}","lensFlarePixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Color\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(textureSampler, vUV);\r\n\r\n\tgl_FragColor = baseColor * color;\r\n}","lensFlareVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Uniforms\r\nuniform mat4 viewportMatrix;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = viewportMatrix * vec4(position, 0.0, 1.0);\r\n}","lensHighlightsPixelShader":"precision highp float;\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\t// original color\r\n\r\n// uniforms\r\nuniform float gain;\r\nuniform float threshold;\r\nuniform bool pentagon;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// apply luminance filter\r\nvec4 highlightColor(vec4 color) {\r\n\tvec4 highlight = color;\r\n\tfloat luminance = dot(highlight.rgb, vec3(0.2125, 0.7154, 0.0721));\r\n\tfloat lum_threshold;\r\n\tif (threshold > 1.0) { lum_threshold = 0.94 + 0.01 * threshold; }\r\n\telse { lum_threshold = 0.5 + 0.44 * threshold; }\r\n\r\n\tluminance = clamp((luminance - lum_threshold) * (1.0 / (1.0 - lum_threshold)), 0.0, 1.0);\r\n\r\n\thighlight *= luminance * gain;\r\n\thighlight.a = 1.0;\r\n\r\n\treturn highlight;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 original = texture2D(textureSampler, vUV);\r\n\r\n\t// quick exit if no highlight computing\r\n\tif (gain == -1.0) {\r\n\t\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\t\treturn;\r\n\t}\r\n\r\n\tfloat w = 2.0 / screen_width;\r\n\tfloat h = 2.0 / screen_height;\r\n\r\n\tfloat weight = 1.0;\r\n\r\n\t// compute blurred color\r\n\tvec4 blurred = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\tif (pentagon) {\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.84*w, 0.43*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.48*w, -1.29*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.61*w, 1.51*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.55*w, -0.74*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.71*w, -0.52*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.94*w, 1.59*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.40*w, -1.87*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.62*w, 1.16*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.09*w, 0.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.46*w, -1.71*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.08*w, 2.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.85*w, -1.89*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.89*w, 0.16*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.29*w, 1.88*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.40*w, -2.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.54*w, 2.26*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.60*w, -0.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.31*w, -1.30*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.83*w, 2.53*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.12*w, -2.48*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.60*w, 1.11*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.82*w, 0.99*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.50*w, -2.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.85*w, 3.33*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.94*w, -1.92*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.27*w, -0.53*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.95*w, 2.48*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.23*w, -3.04*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.17*w, 2.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.97*w, -0.04*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.25*w, -2.00*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.31*w, 3.08*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.94*w, -2.59*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.37*w, 0.64*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.13*w, 1.93*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.03*w, -3.65*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.60*w, 3.17*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.14*w, -1.19*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.00*w, -1.19*h)));\r\n\t}\r\n\telse {\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.85*w, 0.36*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.52*w, -1.14*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.46*w, 1.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.46*w, -0.83*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.79*w, -0.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.11*w, 1.62*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.29*w, -2.07*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.69*w, 1.39*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.28*w, 0.12*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.65*w, -1.69*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.08*w, 2.44*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.63*w, -1.90*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.55*w, 0.31*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.13*w, 1.52*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.56*w, -2.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.38*w, 2.34*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.64*w, -0.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.53*w, -1.21*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.06*w, 2.63*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.00*w, -2.69*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.59*w, 1.32*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.82*w, 0.78*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.57*w, -2.50*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.54*w, 2.93*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.39*w, -1.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.01*w, -0.28*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.04*w, 2.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.02*w, -3.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.09*w, 2.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.07*w, -0.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.44*w, -1.90*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.52*w, 3.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.68*w, -2.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.01*w, 0.79*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.76*w, 1.46*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.05*w, -2.94*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.21*w, 2.88*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.84*w, -1.30*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.98*w, -0.96*h)));\r\n\t}\r\n\r\n\tblurred /= 39.0;\r\n\r\n\tgl_FragColor = blurred;\r\n\r\n\t//if(vUV.x > 0.5) { gl_FragColor.rgb *= 0.0; }\r\n}","linePixelShader":"precision highp float;\r\n\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tgl_FragColor = color;\r\n}","lineVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\nattribute vec4 normal;\r\n\r\n// Uniforms\r\nuniform mat4 worldViewProjection;\r\n\r\nuniform float width;\r\nuniform float aspectRatio;\r\n\r\nvoid main(void) {\r\n\tvec4 viewPosition = worldViewProjection * vec4(position, 1.0);\r\n\tvec4 viewPositionNext = worldViewProjection * vec4(normal.xyz, 1.0);\r\n\r\n\tvec2 currentScreen = viewPosition.xy / viewPosition.w;\r\n\tvec2 nextScreen = viewPositionNext.xy / viewPositionNext.w;\r\n\r\n\tcurrentScreen.x *= aspectRatio;\r\n\tnextScreen.x *= aspectRatio;\r\n\r\n\tvec2 dir = normalize(nextScreen - currentScreen);\r\n\tvec2 normalDir = vec2(-dir.y, dir.x);\r\n\r\n\tnormalDir *= width / 2.0;\r\n\tnormalDir.x /= aspectRatio;\r\n\r\n\tvec4 offset = vec4(normalDir * normal.w, 0.0, 0.0);\r\n\tgl_Position = viewPosition + offset;\r\n}","marblePixelShader":"precision highp float;\r\n\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nuniform float numberOfTilesHeight;\r\nuniform float numberOfTilesWidth;\r\nuniform float amplitude;\r\nuniform vec3 brickColor;\r\nuniform vec3 jointColor;\r\n\r\nconst vec3 tileSize = vec3(1.1, 1.0, 1.1);\r\nconst vec3 tilePct = vec3(0.98, 1.0, 0.98);\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat turbulence(vec2 P)\r\n{\r\n\tfloat val = 0.0;\r\n\tfloat freq = 1.0;\r\n\tfor (int i = 0; i < 4; i++)\r\n\t{\r\n\t\tval += abs(noise(P*freq) / freq);\r\n\t\tfreq *= 2.07;\r\n\t}\r\n\treturn val;\r\n}\r\n\r\nfloat round(float number){\r\n\treturn sign(number)*floor(abs(number) + 0.5);\r\n}\r\n\r\nvec3 marble_color(float x)\r\n{\r\n\tvec3 col;\r\n\tx = 0.5*(x + 1.);\r\n\tx = sqrt(x); \r\n\tx = sqrt(x);\r\n\tx = sqrt(x);\r\n\tcol = vec3(.2 + .75*x); \r\n\tcol.b *= 0.95; \r\n\treturn col;\r\n}\r\n\r\nvoid main()\r\n{\r\n\tfloat brickW = 1.0 / numberOfTilesWidth;\r\n\tfloat brickH = 1.0 / numberOfTilesHeight;\r\n\tfloat jointWPercentage = 0.01;\r\n\tfloat jointHPercentage = 0.01;\r\n\tvec3 color = brickColor;\r\n\tfloat yi = vUV.y / brickH;\r\n\tfloat nyi = round(yi);\r\n\tfloat xi = vUV.x / brickW;\r\n\r\n\tif (mod(floor(yi), 2.0) == 0.0){\r\n\t\txi = xi - 0.5;\r\n\t}\r\n\r\n\tfloat nxi = round(xi);\r\n\tvec2 brickvUV = vec2((xi - floor(xi)) / brickH, (yi - floor(yi)) / brickW);\r\n\r\n\tif (yi < nyi + jointHPercentage && yi > nyi - jointHPercentage){\r\n\t\tcolor = mix(jointColor, vec3(0.37, 0.25, 0.25), (yi - nyi) / jointHPercentage + 0.2);\r\n\t}\r\n\telse if (xi < nxi + jointWPercentage && xi > nxi - jointWPercentage){\r\n\t\tcolor = mix(jointColor, vec3(0.44, 0.44, 0.44), (xi - nxi) / jointWPercentage + 0.2);\r\n\t}\r\n\telse {\r\n\t\tfloat t = 6.28 * brickvUV.x / (tileSize.x + noise(vec2(vUV)*6.0));\r\n\t\tt += amplitude * turbulence(brickvUV.xy);\r\n\t\tt = sin(t);\r\n\t\tcolor = marble_color(t);\r\n\t}\r\n\r\n\tgl_FragColor = vec4(color, 0.0);\r\n}","outlinePixelShader":"precision highp float;\r\n\r\nuniform vec4 color;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\nvoid main(void) {\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","outlineVertexShader":"precision highp float;\r\n\r\n// Attribute\r\nattribute vec3 position;\r\nattribute vec3 normal;\r\n\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniform\r\nuniform float offset;\r\n\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 viewProjection;\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n\tvec3 offsetPosition = position + normal * offset;\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\r\n\tgl_Position = viewProjection * finalWorld * vec4(offsetPosition, 1.0);\r\n#else\r\n\tgl_Position = viewProjection * finalWorld * vec4(offsetPosition, 1.0);\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}","particlesPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\nuniform vec4 textureMask;\r\nuniform sampler2D diffuseSampler;\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\nvoid main(void) {\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\tvec4 baseColor = texture2D(diffuseSampler, vUV);\r\n\r\n\tgl_FragColor = (baseColor * textureMask + (vec4(1., 1., 1., 1.) - textureMask)) * vColor;\r\n}","particlesVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\nattribute vec4 color;\r\nattribute vec4 options;\r\n\r\n// Uniforms\r\nuniform mat4 view;\r\nuniform mat4 projection;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nuniform mat4 invView;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\nvoid main(void) {\t\r\n\tvec3 viewPos = (view * vec4(position, 1.0)).xyz; \r\n\tvec3 cornerPos;\r\n\tfloat size = options.y;\r\n\tfloat angle = options.x;\r\n\tvec2 offset = options.zw;\r\n\r\n\tcornerPos = vec3(offset.x - 0.5, offset.y - 0.5, 0.) * size;\r\n\r\n\t// Rotate\r\n\tvec3 rotatedCorner;\r\n\trotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\r\n\trotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\r\n\trotatedCorner.z = 0.;\r\n\r\n\t// Position\r\n\tviewPos += rotatedCorner;\r\n\tgl_Position = projection * vec4(viewPos, 1.0); \r\n\t\r\n\tvColor = color;\r\n\tvUV = offset;\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tvec4 worldPos = invView * vec4(viewPos, 1.0);\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n}","passPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nvoid main(void) \r\n{\r\n\tgl_FragColor = texture2D(textureSampler, vUV);\r\n}","pbrPixelShader":"precision highp float;\r\n\r\n// Constants\r\nuniform vec3 vEyePosition;\r\nuniform vec4 vAlbedoColor;\r\n\r\n// Input\r\nvarying vec3 vPositionW;\r\n\r\n#ifdef NORMAL\r\nvarying vec3 vNormalW;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn clamp(fogCoeff, 0.0, 1.0);\r\n}\r\n#endif\r\n\r\nvoid main(void) {\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tvec3 viewDirectionW = normalize(vEyePosition - vPositionW);\r\n\r\n\t// Base color\r\n\tvec3 baseColor = vAlbedoColor.rgb;\r\n\r\n\t// Alpha\r\n\tfloat alpha = vAlbedoColor.a;\r\n\r\n#ifdef VERTEXCOLOR\r\n\tbaseColor *= vColor.rgb;\r\n#endif\r\n\r\n#ifdef VERTEXALPHA\r\n\talpha *= vColor.a;\r\n#endif\r\n\r\n\t// Composition\r\n vec4 color = vec4(clamp(baseColor, 0.0, 1.0), alpha);\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tcolor.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","pbrVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\n#ifdef NORMAL\r\nattribute vec3 normal;\r\n#endif\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#ifdef VERTEXCOLOR\r\nattribute vec4 color;\r\n#endif\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniforms\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 view;\r\nuniform mat4 viewProjection;\r\n\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\n#ifdef POINTSIZE\r\nuniform float pointSize;\r\n#endif\r\n\r\n// Output\r\nvarying vec3 vPositionW;\r\n#ifdef NORMAL\r\nvarying vec3 vNormalW;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\nvoid main(void) {\r\n\tmat4 finalWorld;\r\n\r\n#ifdef INSTANCES\r\n\tfinalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tfinalWorld = world;\r\n#endif\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\r\n#ifdef BONES4\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\r\n#else\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2);\r\n#endif \r\n\r\n#endif\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n\r\n\tvec4 worldPos = finalWorld * vec4(position, 1.0);\r\n\tvPositionW = vec3(worldPos);\r\n\r\n#ifdef NORMAL\r\n\tvNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\r\n#endif\r\n\r\n\t// Texture coordinates\r\n#ifndef UV1\r\n\tvec2 uv = vec2(0., 0.);\r\n#endif\r\n#ifndef UV2\r\n\tvec2 uv2 = vec2(0., 0.);\r\n#endif\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = (view * worldPos).z;\r\n#endif\r\n\r\n\t// Vertex color\r\n#ifdef VERTEXCOLOR\r\n\tvColor = color;\r\n#endif\r\n\r\n\t// Point size\r\n#ifdef POINTSIZE\r\n\tgl_PointSize = pointSize;\r\n#endif\r\n}","postprocessVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = vec4(position, 0.0, 1.0);\r\n}","proceduralVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Output\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\tvPosition = position;\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = vec4(position, 0.0, 1.0);\r\n}","refractionPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D refractionSampler;\r\n\r\n// Parameters\r\nuniform vec3 baseColor;\r\nuniform float depth;\r\nuniform float colorLevel;\r\n\r\nvoid main() {\r\n\tfloat ref = 1.0 - texture2D(refractionSampler, vUV).r;\r\n\r\n\tvec2 uv = vUV - vec2(0.5);\r\n\tvec2 offset = uv * depth * ref;\r\n\tvec3 sourceColor = texture2D(textureSampler, vUV - offset).rgb;\r\n\r\n\tgl_FragColor = vec4(sourceColor + sourceColor * ref * colorLevel, 1.0);\r\n}","roadPixelShader":"precision highp float;\r\n\r\nvarying vec2 vUV; \r\nuniform vec3 roadColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main(void) {\r\n\tfloat ratioy = mod(gl_FragCoord.y * 100.0 , fbm(vUV * 2.0));\r\n\tvec3 color = roadColor * ratioy;\r\n\tgl_FragColor = vec4(color, 1.0);\r\n}","shadowMapPixelShader":"precision highp float;\r\n\r\nvec4 pack(float depth)\r\n{\r\n\tconst vec4 bit_shift = vec4(255.0 * 255.0 * 255.0, 255.0 * 255.0, 255.0, 1.0);\r\n\tconst vec4 bit_mask = vec4(0.0, 1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0);\r\n\r\n\tvec4 res = fract(depth * bit_shift);\r\n\tres -= res.xxyz * bit_mask;\r\n\r\n\treturn res;\r\n}\r\n\r\n// Thanks to http://devmaster.net/\r\nvec2 packHalf(float depth) \r\n{ \r\n\tconst vec2 bitOffset = vec2(1.0 / 255., 0.);\r\n\tvec2 color = vec2(depth, fract(depth * 255.));\r\n\r\n\treturn color - (color.yy * bitOffset);\r\n}\r\n\r\nvarying vec4 vPosition;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\tfloat depth = vPosition.z / vPosition.w;\r\n\tdepth = depth * 0.5 + 0.5;\r\n\r\n#ifdef VSM\r\n\tfloat moment1 = depth;\r\n\tfloat moment2 = moment1 * moment1;\r\n\r\n\tgl_FragColor = vec4(packHalf(moment1), packHalf(moment2));\r\n#else\r\n\tgl_FragColor = pack(depth);\r\n#endif\r\n}","shadowMapVertexShader":"precision highp float;\r\n\r\n// Attribute\r\nattribute vec3 position;\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniform\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 viewProjection;\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\nvarying vec4 vPosition;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\r\n#endif\r\n\r\n\tvPosition = viewProjection * finalWorld * vec4(position, 1.0);\r\n\tgl_Position = vPosition;\r\n\r\n#ifdef ALPHATEST\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}","spritesPixelShader":"precision highp float;\r\n\r\nuniform bool alphaTest;\r\n\r\nvarying vec4 vColor;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn min(1., max(0., fogCoeff));\r\n}\r\n#endif\r\n\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(diffuseSampler, vUV);\r\n\r\n\tif (alphaTest) \r\n\t{\r\n\t\tif (baseColor.a < 0.95)\r\n\t\t\tdiscard;\r\n\t}\r\n\r\n\tbaseColor *= vColor;\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tbaseColor.rgb = fog * baseColor.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\r\n\tgl_FragColor = baseColor;\r\n}","spritesVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec4 position;\r\nattribute vec4 options;\r\nattribute vec4 cellInfo;\r\nattribute vec4 color;\r\n\r\n// Uniforms\r\nuniform vec2 textureInfos;\r\nuniform mat4 view;\r\nuniform mat4 projection;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\nvoid main(void) {\t\r\n\tvec3 viewPos = (view * vec4(position.xyz, 1.0)).xyz; \r\n\tvec2 cornerPos;\r\n\t\r\n\tfloat angle = position.w;\r\n\tvec2 size = vec2(options.x, options.y);\r\n\tvec2 offset = options.zw;\r\n\tvec2 uvScale = textureInfos.xy;\r\n\r\n\tcornerPos = vec2(offset.x - 0.5, offset.y - 0.5) * size;\r\n\r\n\t// Rotate\r\n\tvec3 rotatedCorner;\r\n\trotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\r\n\trotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\r\n\trotatedCorner.z = 0.;\r\n\r\n\t// Position\r\n\tviewPos += rotatedCorner;\r\n\tgl_Position = projection * vec4(viewPos, 1.0); \r\n\r\n\t// Color\r\n\tvColor = color;\r\n\t\r\n\t// Texture\r\n\tvec2 uvOffset = vec2(abs(offset.x - cellInfo.x), 1.0 - abs(offset.y - cellInfo.y));\r\n\r\n\tvUV = (uvOffset + cellInfo.zw) * uvScale;\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = viewPos.z;\r\n#endif\r\n}","ssaoPixelShader":"precision highp float;\r\n\r\n#define SAMPLES 16\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D randomSampler;\r\n\r\nuniform float randTextureTiles;\r\nuniform float samplesFactor;\r\nuniform vec3 sampleSphere[16];\r\n\r\nuniform float totalStrength;\r\nuniform float radius;\r\nuniform float area;\r\nuniform float fallOff;\r\n\r\nvarying vec2 vUV;\r\n\r\nconst vec2 offset1 = vec2(0.0, 0.001);\r\nconst vec2 offset2 = vec2(0.001, 0.0);\r\n\r\nvec3 normalFromDepth(const float depth, const vec2 coords) {\r\n\tfloat depth1 = texture2D(textureSampler, coords + offset1).r;\r\n\tfloat depth2 = texture2D(textureSampler, coords + offset2).r;\r\n\r\n vec3 p1 = vec3(offset1, depth1 - depth);\r\n vec3 p2 = vec3(offset2, depth2 - depth);\r\n\r\n vec3 normal = cross(p1, p2);\r\n normal.z = -normal.z;\r\n\r\n return normalize(normal);\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tconst float base = 0.2;\r\n\r\n\tvec3 random = texture2D(randomSampler, vUV * randTextureTiles).rgb;\r\n\tfloat depth = texture2D(textureSampler, vUV).r;\r\n\tvec3 position = vec3(vUV, depth);\r\n\tvec3 normal = normalFromDepth(depth, vUV);\r\n\tfloat radiusDepth = radius / depth;\r\n\tfloat occlusion = 0.0;\r\n\r\n\tvec3 ray;\r\n\tvec3 hemiRay;\r\n\tfloat occlusionDepth;\r\n\tfloat difference;\r\n\r\n\tfor (int i = 0; i < SAMPLES; i++)\r\n\t{\r\n\t\tray = radiusDepth * reflect(sampleSphere[i], random);\r\n\t\themiRay = position + sign(dot(ray, normal)) * ray;\r\n\r\n\t\tocclusionDepth = texture2D(textureSampler, clamp(hemiRay.xy, 0.0, 1.0)).r;\r\n\t\tdifference = depth - occlusionDepth;\r\n\r\n\t\tocclusion += step(fallOff, difference) * (1.0 - smoothstep(fallOff, area, difference));\r\n\t}\r\n\r\n\tfloat ao = 1.0 - totalStrength * occlusion * samplesFactor;\r\n\r\n\tfloat result = clamp(ao + base, 0.0, 1.0);\r\n\tgl_FragColor.r = result;\r\n\tgl_FragColor.g = result;\r\n\tgl_FragColor.b = result;\r\n\tgl_FragColor.a = 1.0;\r\n}\r\n","ssaoCombinePixelShader":"precision highp float;\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D originalColor;\r\n\r\nvarying vec2 vUV;\r\n\r\nvoid main(void) {\r\n\tgl_FragColor = texture2D(originalColor, vUV) * texture2D(textureSampler, vUV);\r\n}\r\n","stereoscopicInterlacePixelShader":"precision highp float;\r\n\r\nconst vec3 TWO = vec3(2.0, 2.0, 2.0);\r\n\r\nvarying vec2 vUV;\r\nuniform sampler2D camASampler;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 stepSize;\r\n\r\nvoid main(void)\r\n{\r\n bool useCamB;\r\n vec2 texCoord1;\r\n vec2 texCoord2;\r\n \r\n vec3 frag1;\r\n vec3 frag2;\r\n \r\n#ifdef IS_STEREOSCOPIC_HORIZ\r\n\t useCamB = vUV.x > 0.5;\r\n\t texCoord1 = vec2(useCamB ? (vUV.x - 0.5) * 2.0 : vUV.x * 2.0, vUV.y);\r\n\t texCoord2 = vec2(texCoord1.x + stepSize.x, vUV.y);\r\n#else\r\n\t useCamB = vUV.y > 0.5;\r\n\t texCoord1 = vec2(vUV.x, useCamB ? (vUV.y - 0.5) * 2.0 : vUV.y * 2.0);\r\n\t texCoord2 = vec2(vUV.x, texCoord1.y + stepSize.y);\r\n#endif\r\n \r\n // cannot assign a sampler to a variable, so must duplicate texture accesses\r\n if (useCamB){\r\n frag1 = texture2D(textureSampler, texCoord1).rgb;\r\n frag2 = texture2D(textureSampler, texCoord2).rgb;\r\n }else{\r\n frag1 = texture2D(camASampler , texCoord1).rgb;\r\n frag2 = texture2D(camASampler , texCoord2).rgb;\r\n }\r\n \r\n gl_FragColor = vec4((frag1 + frag2) / TWO, 1.0);\r\n}","tonemapPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Constants\r\nuniform float _ExposureAdjustment;\r\n\r\n#if defined(HABLE_TONEMAPPING)\r\n const float A = 0.15;\r\n const float B = 0.50;\r\n const float C = 0.10;\r\n const float D = 0.20;\r\n const float E = 0.02;\r\n const float F = 0.30;\r\n const float W = 11.2;\r\n#endif\r\n\r\nfloat Luminance(vec3 c)\r\n{\r\n return dot(c, vec3(0.22, 0.707, 0.071));\r\n}\r\n\r\nvoid main(void) \r\n{\r\n vec3 colour = texture2D(textureSampler, vUV).rgb;\r\n\r\n#if defined(REINHARD_TONEMAPPING)\r\n\r\n float lum = Luminance(colour.rgb); \r\n float lumTm = lum * _ExposureAdjustment;\r\n float scale = lumTm / (1.0 + lumTm); \r\n\r\n colour *= scale / lum;\r\n\r\n#elif defined(HABLE_TONEMAPPING)\r\n\r\n colour *= _ExposureAdjustment;\r\n\r\n const float ExposureBias = 2.0;\r\n vec3 x = ExposureBias * colour;\r\n\r\n vec3 curr = ((x * (A * x + C * B) + D * E) / (x * (A * x + B) + D * F)) - E / F;\r\n \r\n x = vec3(W, W, W);\r\n vec3 whiteScale = 1.0 / (((x * (A * x + C * B) + D * E) / (x * (A * x + B) + D * F)) - E / F);\r\n colour = curr * whiteScale;\r\n\r\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\r\n\r\n colour *= _ExposureAdjustment;\r\n \r\n vec3 X = max(vec3(0.0, 0.0, 0.0), colour - 0.004);\r\n vec3 retColor = (X * (6.2 * X + 0.5)) / (X * (6.2 * X + 1.7) + 0.06);\r\n\r\n colour = retColor * retColor;\r\n\r\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\r\n\r\n colour = vec3(1.0, 1.0, 1.0) - exp2(-_ExposureAdjustment * colour);\r\n\r\n#endif\r\n\r\n\tgl_FragColor = vec4(colour.rgb, 1.0);\r\n}","volumetricLightScatteringPixelShader":"precision highp float;\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D lightScatteringSampler;\r\n\r\nuniform float decay;\r\nuniform float exposure;\r\nuniform float weight;\r\nuniform float density;\r\nuniform vec2 meshPositionOnScreen;\r\n\r\nvarying vec2 vUV;\r\n\r\nvoid main(void) {\r\n vec2 tc = vUV;\r\n\tvec2 deltaTexCoord = (tc - meshPositionOnScreen.xy);\r\n deltaTexCoord *= 1.0 / float(NUM_SAMPLES) * density;\r\n\r\n float illuminationDecay = 1.0;\r\n\r\n\tvec4 color = texture2D(lightScatteringSampler, tc) * 0.4;\r\n\r\n for(int i=0; i < NUM_SAMPLES; i++) {\r\n tc -= deltaTexCoord;\r\n\t\tvec4 sample = texture2D(lightScatteringSampler, tc) * 0.4;\r\n sample *= illuminationDecay * weight;\r\n color += sample;\r\n illuminationDecay *= decay;\r\n }\r\n\r\n vec4 realColor = texture2D(textureSampler, vUV);\r\n gl_FragColor = ((vec4((vec3(color.r, color.g, color.b) * exposure), 1)) + (realColor * (1.5 - 0.4)));\r\n}\r\n","volumetricLightScatteringPassPixelShader":"precision highp float;\r\n\r\n#if defined(ALPHATEST) || defined(NEED_UV)\r\nvarying vec2 vUV;\r\n#endif\r\n\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\n#if defined(DIFFUSE_COLOR_RENDER)\r\nuniform vec3 color;\r\n#endif\r\n\r\n#if defined(OPACITY)\r\nuniform sampler2D opacitySampler;\r\nuniform float opacityLevel;\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\n\tvec4 diffuseColor = texture2D(diffuseSampler, vUV);\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\n\tif (diffuseColor.a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityColor = texture2D(opacitySampler, vUV);\r\n\tfloat alpha = 1.0;\r\n\r\n\t#ifdef OPACITYRGB\r\n\topacityColor.rgb = opacityColor.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityColor.x + opacityColor.y + opacityColor.z) * opacityLevel;\r\n\t#else\r\n\talpha *= opacityColor.a * opacityLevel;\r\n\t#endif\r\n\r\n\t#if defined(BASIC_RENDER)\r\n\tgl_FragColor = vec4(diffuseColor.rgb, alpha);\r\n\t#elif defined(DIFFUSE_COLOR_RENDER)\r\n\tgl_FragColor = vec4(color.rgb, alpha);\r\n\t#else\r\n\tgl_FragColor = vec4(0.0, 0.0, 0.0, alpha);\r\n\t#endif\r\n\r\n\tgl_FragColor.a = alpha;\r\n#else\r\n\r\n\t#if defined(BASIC_RENDER)\r\n\tgl_FragColor = diffuseColor;\r\n\t#elif defined(DIFFUSE_COLOR_RENDER)\r\n\tgl_FragColor = vec4(color.rgb, 1.0);\r\n\t#else\r\n\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\t#endif\r\n#endif\r\n\r\n}\r\n","vrDistortionCorrectionPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 LensCenter;\r\nuniform vec2 Scale;\r\nuniform vec2 ScaleIn;\r\nuniform vec4 HmdWarpParam;\r\n\r\nvec2 HmdWarp(vec2 in01) {\r\n\r\n\tvec2 theta = (in01 - LensCenter) * ScaleIn; // Scales to [-1, 1]\r\n\tfloat rSq = theta.x * theta.x + theta.y * theta.y;\r\n\tvec2 rvector = theta * (HmdWarpParam.x + HmdWarpParam.y * rSq + HmdWarpParam.z * rSq * rSq + HmdWarpParam.w * rSq * rSq * rSq);\r\n\treturn LensCenter + Scale * rvector;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 tc = HmdWarp(vUV);\r\n\tif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\r\n\t\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\telse{\r\n\t\tgl_FragColor = vec4(texture2D(textureSampler, tc).rgb, 1.0);\r\n\t}\r\n}","woodPixelShader":"precision highp float;\r\n\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nuniform float ampScale;\r\nuniform vec3 woodColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main(void) {\r\n\tfloat ratioy = mod(vUV.x * ampScale, 2.0 + fbm(vUV * 0.8));\r\n\tvec3 wood = woodColor * ratioy;\r\n\tgl_FragColor = vec4(wood, 1.0);\r\n}"};
  35808. BABYLON.CollisionWorker="var BABYLON;!function(t){var e=function(t,e,o,i){return t.x>o.x+i?!1:o.x-i>e.x?!1:t.y>o.y+i?!1:o.y-i>e.y?!1:t.z>o.z+i?!1:o.z-i>e.z?!1:!0},o=function(t,e,o,i){var s=e*e-4*t*o,r={root:0,found:!1};if(0>s)return r;var n=Math.sqrt(s),c=(-e-n)/(2*t),h=(-e+n)/(2*t);if(c>h){var a=h;h=c,c=a}return c>0&&i>c?(r.root=c,r.found=!0,r):h>0&&i>h?(r.root=h,r.found=!0,r):r},i=function(){function i(){this.radius=new t.Vector3(1,1,1),this.retry=0,this.basePointWorld=t.Vector3.Zero(),this.velocityWorld=t.Vector3.Zero(),this.normalizedVelocity=t.Vector3.Zero(),this._collisionPoint=t.Vector3.Zero(),this._planeIntersectionPoint=t.Vector3.Zero(),this._tempVector=t.Vector3.Zero(),this._tempVector2=t.Vector3.Zero(),this._tempVector3=t.Vector3.Zero(),this._tempVector4=t.Vector3.Zero(),this._edge=t.Vector3.Zero(),this._baseToVertex=t.Vector3.Zero(),this._destinationPoint=t.Vector3.Zero(),this._slidePlaneNormal=t.Vector3.Zero(),this._displacementVector=t.Vector3.Zero()}return i.prototype._initialize=function(e,o,i){this.velocity=o,t.Vector3.NormalizeToRef(o,this.normalizedVelocity),this.basePoint=e,e.multiplyToRef(this.radius,this.basePointWorld),o.multiplyToRef(this.radius,this.velocityWorld),this.velocityWorldLength=this.velocityWorld.length(),this.epsilon=i,this.collisionFound=!1},i.prototype._checkPointInTriangle=function(e,o,i,s,r){o.subtractToRef(e,this._tempVector),i.subtractToRef(e,this._tempVector2),t.Vector3.CrossToRef(this._tempVector,this._tempVector2,this._tempVector4);var n=t.Vector3.Dot(this._tempVector4,r);return 0>n?!1:(s.subtractToRef(e,this._tempVector3),t.Vector3.CrossToRef(this._tempVector2,this._tempVector3,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),0>n?!1:(t.Vector3.CrossToRef(this._tempVector3,this._tempVector,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),n>=0))},i.prototype._canDoCollision=function(o,i,s,r){var n=t.Vector3.Distance(this.basePointWorld,o),c=Math.max(this.radius.x,this.radius.y,this.radius.z);return n>this.velocityWorldLength+c+i?!1:e(s,r,this.basePointWorld,this.velocityWorldLength+c)?!0:!1},i.prototype._testTriangle=function(e,i,s,r,n,c){var h,a=!1;i||(i=[]),i[e]||(i[e]=new t.Plane(0,0,0,0),i[e].copyFromPoints(s,r,n));var l=i[e];if(c||l.isFrontFacingTo(this.normalizedVelocity,0)){var _=l.signedDistanceTo(this.basePoint),d=t.Vector3.Dot(l.normal,this.velocity);if(0==d){if(Math.abs(_)>=1)return;a=!0,h=0}else{h=(-1-_)/d;var V=(1-_)/d;if(h>V){var u=V;V=h,h=u}if(h>1||0>V)return;0>h&&(h=0),h>1&&(h=1)}this._collisionPoint.copyFromFloats(0,0,0);var P=!1,p=1;if(a||(this.basePoint.subtractToRef(l.normal,this._planeIntersectionPoint),this.velocity.scaleToRef(h,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,s,r,n,l.normal)&&(P=!0,p=h,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!P){var m=this.velocity.lengthSquared(),f=m;this.basePoint.subtractToRef(s,this._tempVector);var T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p);y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(s)),this.basePoint.subtractToRef(r,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(r)),this.basePoint.subtractToRef(n,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(n)),r.subtractToRef(s,this._edge),s.subtractToRef(this.basePoint,this._baseToVertex);var g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex);if(f=g*-m+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found){var D=(v*y.root-R)/g;D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),s.addToRef(this._edge,this._collisionPoint))}n.subtractToRef(r,this._edge),r.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),f=g*-m+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),r.addToRef(this._edge,this._collisionPoint))),s.subtractToRef(n,this._edge),n.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),f=g*-m+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),n.addToRef(this._edge,this._collisionPoint)))}if(P){var x=p*this.velocity.length();(!this.collisionFound||x<this.nearestDistance)&&(this.intersectionPoint?this.intersectionPoint.copyFrom(this._collisionPoint):this.intersectionPoint=this._collisionPoint.clone(),this.nearestDistance=x,this.collisionFound=!0)}}},i.prototype._collide=function(t,e,o,i,s,r,n){for(var c=i;s>c;c+=3){var h=e[o[c]-r],a=e[o[c+1]-r],l=e[o[c+2]-r];this._testTriangle(c,t,l,a,h,n)}},i.prototype._getResponse=function(e,o){e.addToRef(o,this._destinationPoint),o.scaleInPlace(this.nearestDistance/o.length()),this.basePoint.addToRef(o,e),e.subtractToRef(this.intersectionPoint,this._slidePlaneNormal),this._slidePlaneNormal.normalize(),this._slidePlaneNormal.scaleToRef(this.epsilon,this._displacementVector),e.addInPlace(this._displacementVector),this.intersectionPoint.addInPlace(this._displacementVector),this._slidePlaneNormal.scaleInPlace(t.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint,this._slidePlaneNormal,this._destinationPoint)),this._destinationPoint.subtractInPlace(this._slidePlaneNormal),this._destinationPoint.subtractToRef(this.intersectionPoint,o)},i}();t.Collider=i}(BABYLON||(BABYLON={}));var BABYLON;!function(o){o.WorkerIncluded=!0;var e=function(){function o(){this._meshes={},this._geometries={}}return o.prototype.getMeshes=function(){return this._meshes},o.prototype.getGeometries=function(){return this._geometries},o.prototype.getMesh=function(o){return this._meshes[o]},o.prototype.addMesh=function(o){this._meshes[o.uniqueId]=o},o.prototype.removeMesh=function(o){delete this._meshes[o]},o.prototype.getGeometry=function(o){return this._geometries[o]},o.prototype.addGeometry=function(o){this._geometries[o.id]=o},o.prototype.removeGeometry=function(o){delete this._geometries[o]},o}();o.CollisionCache=e;var i=function(){function e(e,i,r){this.collider=e,this._collisionCache=i,this.finalPosition=r,this.collisionsScalingMatrix=o.Matrix.Zero(),this.collisionTranformationMatrix=o.Matrix.Zero()}return e.prototype.collideWithWorld=function(o,e,i,r){var t=.01;if(this.collider.retry>=i)return void this.finalPosition.copyFrom(o);this.collider._initialize(o,e,t);for(var s,l=this._collisionCache.getMeshes(),n=Object.keys(l),a=n.length,c=0;a>c;++c)if(s=n[c],parseInt(s)!=r){var d=l[s];d.checkCollisions&&this.checkCollision(d)}return this.collider.collisionFound?((0!==e.x||0!==e.y||0!==e.z)&&this.collider._getResponse(o,e),e.length()<=t?void this.finalPosition.copyFrom(o):(this.collider.retry++,void this.collideWithWorld(o,e,i,r))):void o.addToRef(e,this.finalPosition)},e.prototype.checkCollision=function(e){if(this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))){o.Matrix.ScalingToRef(1/this.collider.radius.x,1/this.collider.radius.y,1/this.collider.radius.z,this.collisionsScalingMatrix);var i=o.Matrix.FromArray(e.worldMatrixFromCache);i.multiplyToRef(this.collisionsScalingMatrix,this.collisionTranformationMatrix),this.processCollisionsForSubMeshes(this.collisionTranformationMatrix,e)}},e.prototype.processCollisionsForSubMeshes=function(o,e){var i=e.subMeshes,r=i.length;if(!e.geometryId)return void console.log(\"no mesh geometry id\");var t=this._collisionCache.getGeometry(e.geometryId);if(!t)return void console.log(\"couldn't find geometry\",e.geometryId);for(var s=0;r>s;s++){var l=i[s];r>1&&!this.checkSubmeshCollision(l)||(this.collideForSubMesh(l,o,t),this.collider.collisionFound&&(this.collider.collidedMesh=e.uniqueId))}},e.prototype.collideForSubMesh=function(e,i,r){if(!r.positionsArray){r.positionsArray=[];for(var t=0,s=r.positions.length;s>t;t+=3){var l=o.Vector3.FromArray([r.positions[t],r.positions[t+1],r.positions[t+2]]);r.positionsArray.push(l)}}if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(i)){e._lastColliderTransformMatrix=i.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];for(var n=e.verticesStart,a=e.verticesStart+e.verticesCount,t=n;a>t;t++)e._lastColliderWorldVertices.push(o.Vector3.TransformCoordinates(r.positionsArray[t],i))}this.collider._collide(e._trianglePlanes,e._lastColliderWorldVertices,r.indices,e.indexStart,e.indexStart+e.indexCount,e.verticesStart,e.hasMaterial)},e.prototype.checkSubmeshCollision=function(e){return this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))},e}();o.CollideWorker=i;var r=function(){function r(){}return r.prototype.onInit=function(i){this._collisionCache=new e;var r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.INIT};postMessage(r,void 0)},r.prototype.onUpdate=function(e){var i=this,r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.UPDATE};try{for(var t in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(t)&&this._collisionCache.addGeometry(e.updatedGeometries[t]);for(var s in e.updatedMeshes)e.updatedMeshes.hasOwnProperty(s)&&this._collisionCache.addMesh(e.updatedMeshes[s]);e.removedGeometries.forEach(function(o){i._collisionCache.removeGeometry(o)}),e.removedMeshes.forEach(function(o){i._collisionCache.removeMesh(o)})}catch(l){r.error=o.WorkerReplyType.UNKNOWN_ERROR}postMessage(r,void 0)},r.prototype.onCollision=function(e){var r=o.Vector3.Zero(),t=new o.Collider;t.radius=o.Vector3.FromArray(e.collider.radius);var s=new i(t,this._collisionCache,r);s.collideWithWorld(o.Vector3.FromArray(e.collider.position),o.Vector3.FromArray(e.collider.velocity),e.maximumRetry,e.excludedMeshUniqueId);var l={collidedMeshUniqueId:t.collidedMesh,collisionId:e.collisionId,newPosition:r.asArray()},n={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.COLLIDE,payload:l};postMessage(n,void 0)},r}();o.CollisionDetectorTransferable=r;try{if(self&&self instanceof WorkerGlobalScope){window={},o.Collider||(importScripts(\"./babylon.collisionCoordinator.js\"),importScripts(\"./babylon.collider.js\"),importScripts(\"../Math/babylon.math.js\"));var t=new r,s=function(e){var i=e.data;switch(i.taskType){case o.WorkerTaskType.INIT:t.onInit(i.payload);break;case o.WorkerTaskType.COLLIDE:t.onCollision(i.payload);break;case o.WorkerTaskType.UPDATE:t.onUpdate(i.payload)}};self.onmessage=s}}catch(l){console.log(\"single worker init\")}}(BABYLON||(BABYLON={}));var BABYLON;!function(e){e.CollisionWorker=\"\",function(e){e[e.INIT=0]=\"INIT\",e[e.UPDATE=1]=\"UPDATE\",e[e.COLLIDE=2]=\"COLLIDE\"}(e.WorkerTaskType||(e.WorkerTaskType={}));var o=e.WorkerTaskType;!function(e){e[e.SUCCESS=0]=\"SUCCESS\",e[e.UNKNOWN_ERROR=1]=\"UNKNOWN_ERROR\"}(e.WorkerReplyType||(e.WorkerReplyType={}));var i=e.WorkerReplyType,t=function(){function t(){var r=this;this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this.onMeshUpdated=function(e){r._addUpdateMeshesList[e.uniqueId]=t.SerializeMesh(e)},this.onGeometryUpdated=function(e){r._addUpdateGeometriesList[e.id]=t.SerializeGeometry(e)},this._afterRender=function(){if(r._init&&!(0==r._toRemoveGeometryArray.length&&0==r._toRemoveMeshesArray.length&&0==Object.keys(r._addUpdateGeometriesList).length&&0==Object.keys(r._addUpdateMeshesList).length||r._runningUpdated>4)){++r._runningUpdated;var e={updatedMeshes:r._addUpdateMeshesList,updatedGeometries:r._addUpdateGeometriesList,removedGeometries:r._toRemoveGeometryArray,removedMeshes:r._toRemoveMeshesArray},i={payload:e,taskType:o.UPDATE},t=[];for(var s in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(s)&&(t.push(i.payload.updatedGeometries[s].indices.buffer),t.push(i.payload.updatedGeometries[s].normals.buffer),t.push(i.payload.updatedGeometries[s].positions.buffer));r._worker.postMessage(i,t),r._addUpdateMeshesList={},r._addUpdateGeometriesList={},r._toRemoveGeometryArray=[],r._toRemoveMeshesArray=[]}},this._onMessageFromWorker=function(t){var s=t.data;if(s.error!=i.SUCCESS)return void e.Tools.Warn(\"error returned from worker!\");switch(s.taskType){case o.INIT:r._init=!0,r._scene.meshes.forEach(function(e){r.onMeshAdded(e)}),r._scene.getGeometries().forEach(function(e){r.onGeometryAdded(e)});break;case o.UPDATE:r._runningUpdated--;break;case o.COLLIDE:r._runningCollisionTask=!1;var n=s.payload;if(!r._collisionsCallbackArray[n.collisionId])return;r._collisionsCallbackArray[n.collisionId](n.collisionId,e.Vector3.FromArray(n.newPosition),r._scene.getMeshByUniqueID(n.collidedMeshUniqueId)),r._collisionsCallbackArray[n.collisionId]=void 0}},this._collisionsCallbackArray=[],this._init=!1,this._runningUpdated=0,this._runningCollisionTask=!1,this._addUpdateMeshesList={},this._addUpdateGeometriesList={},this._toRemoveGeometryArray=[],this._toRemoveMeshesArray=[]}return t.prototype.getNewPosition=function(e,i,t,r,s,n,a){if(this._init&&!this._collisionsCallbackArray[a]&&!this._collisionsCallbackArray[a+1e5]){e.divideToRef(t.radius,this._scaledPosition),i.divideToRef(t.radius,this._scaledVelocity),this._collisionsCallbackArray[a]=n;var d={collider:{position:this._scaledPosition.asArray(),velocity:this._scaledVelocity.asArray(),radius:t.radius.asArray()},collisionId:a,excludedMeshUniqueId:s?s.uniqueId:null,maximumRetry:r},l={payload:d,taskType:o.COLLIDE};this._worker.postMessage(l)}},t.prototype.init=function(i){this._scene=i,this._scene.registerAfterRender(this._afterRender);var t=e.WorkerIncluded?e.Engine.CodeRepository+\"Collisions/babylon.collisionWorker.js\":URL.createObjectURL(new Blob([e.CollisionWorker],{type:\"application/javascript\"}));this._worker=new Worker(t),this._worker.onmessage=this._onMessageFromWorker;var r={payload:{},taskType:o.INIT};this._worker.postMessage(r)},t.prototype.destroy=function(){this._scene.unregisterAfterRender(this._afterRender),this._worker.terminate()},t.prototype.onMeshAdded=function(e){e.registerAfterWorldMatrixUpdate(this.onMeshUpdated),this.onMeshUpdated(e)},t.prototype.onMeshRemoved=function(e){this._toRemoveMeshesArray.push(e.uniqueId)},t.prototype.onGeometryAdded=function(e){e.onGeometryUpdated=this.onGeometryUpdated,this.onGeometryUpdated(e)},t.prototype.onGeometryDeleted=function(e){this._toRemoveGeometryArray.push(e.id)},t.SerializeMesh=function(o){var i=[];o.subMeshes&&(i=o.subMeshes.map(function(e,o){return{position:o,verticesStart:e.verticesStart,verticesCount:e.verticesCount,indexStart:e.indexStart,indexCount:e.indexCount,hasMaterial:!!e.getMaterial(),sphereCenter:e.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:e.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:e.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:e.getBoundingInfo().boundingBox.maximumWorld.asArray()}}));var t=null;return o instanceof e.Mesh?t=o.geometry?o.geometry.id:null:o instanceof e.InstancedMesh&&(t=o.sourceMesh&&o.sourceMesh.geometry?o.sourceMesh.geometry.id:null),{uniqueId:o.uniqueId,id:o.id,name:o.name,geometryId:t,sphereCenter:o.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:o.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:o.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:o.getBoundingInfo().boundingBox.maximumWorld.asArray(),worldMatrixFromCache:o.worldMatrixFromCache.asArray(),subMeshes:i,checkCollisions:o.checkCollisions}},t.SerializeGeometry=function(o){return{id:o.id,positions:new Float32Array(o.getVerticesData(e.VertexBuffer.PositionKind)||[]),normals:new Float32Array(o.getVerticesData(e.VertexBuffer.NormalKind)||[]),indices:new Int32Array(o.getIndices()||[])}},t}();e.CollisionCoordinatorWorker=t;var r=function(){function o(){this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this._finalPosition=e.Vector3.Zero()}return o.prototype.getNewPosition=function(e,o,i,t,r,s,n){e.divideToRef(i.radius,this._scaledPosition),o.divideToRef(i.radius,this._scaledVelocity),i.collidedMesh=null,i.retry=0,i.initialVelocity=this._scaledVelocity,i.initialPosition=this._scaledPosition,this._collideWithWorld(this._scaledPosition,this._scaledVelocity,i,t,this._finalPosition,r),this._finalPosition.multiplyInPlace(i.radius),s(n,this._finalPosition,i.collidedMesh)},o.prototype.init=function(e){this._scene=e},o.prototype.destroy=function(){},o.prototype.onMeshAdded=function(e){},o.prototype.onMeshUpdated=function(e){},o.prototype.onMeshRemoved=function(e){},o.prototype.onGeometryAdded=function(e){},o.prototype.onGeometryUpdated=function(e){},o.prototype.onGeometryDeleted=function(e){},o.prototype._collideWithWorld=function(o,i,t,r,s,n){void 0===n&&(n=null);var a=10*e.Engine.CollisionsEpsilon;if(t.retry>=r)return void s.copyFrom(o);t._initialize(o,i,a);for(var d=0;d<this._scene.meshes.length;d++){var l=this._scene.meshes[d];l.isEnabled()&&l.checkCollisions&&l.subMeshes&&l!==n&&l._checkCollision(t)}return t.collisionFound?((0!==i.x||0!==i.y||0!==i.z)&&t._getResponse(o,i),i.length()<=a?void s.copyFrom(o):(t.retry++,void this._collideWithWorld(o,i,t,r,s,n))):void o.addToRef(i,s)},o}();e.CollisionCoordinatorLegacy=r}(BABYLON||(BABYLON={}));var BABYLON;!function(t){var i=function(){function i(t,i,n){void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=0),this.r=t,this.g=i,this.b=n}return i.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\"}\"},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,this},i.prototype.toColor4=function(t){return void 0===t&&(t=1),new n(this.r,this.g,this.b,t)},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toLuminance=function(){return.3*this.r+.59*this.g+.11*this.b},i.prototype.multiply=function(t){return new i(this.r*t.r,this.g*t.g,this.b*t.b)},i.prototype.multiplyToRef=function(t,i){return i.r=this.r*t.r,i.g=this.g*t.g,i.b=this.b*t.b,this},i.prototype.equals=function(t){return t&&this.r===t.r&&this.g===t.g&&this.b===t.b},i.prototype.equalsFloats=function(t,i,n){return this.r===t&&this.g===i&&this.b===n},i.prototype.scale=function(t){return new i(this.r*t,this.g*t,this.b*t)},i.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,this},i.prototype.add=function(t){return new i(this.r+t.r,this.g+t.g,this.b+t.b)},i.prototype.addToRef=function(t,i){return i.r=this.r+t.r,i.g=this.g+t.g,i.b=this.b+t.b,this},i.prototype.subtract=function(t){return new i(this.r-t.r,this.g-t.g,this.b-t.b)},i.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,this},i.prototype.clone=function(){return new i(this.r,this.g,this.b)},i.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this},i.prototype.copyFromFloats=function(t,i,n){return this.r=t,this.g=i,this.b=n,this},i.prototype.toHexString=function(){var i=255*this.r|0,n=255*this.g|0,r=255*this.b|0;return\"#\"+t.Tools.ToHex(i)+t.Tools.ToHex(n)+t.Tools.ToHex(r)},i.FromHexString=function(n){if(\"#\"!==n.substring(0,1)||7!==n.length)return t.Tools.Warn(\"Color3.FromHexString must be called with a string like #FFFFFF\"),new i(0,0,0);var r=parseInt(n.substring(1,3),16),o=parseInt(n.substring(3,5),16),s=parseInt(n.substring(5,7),16);return i.FromInts(r,o,s)},i.FromArray=function(t,n){return void 0===n&&(n=0),new i(t[n],t[n+1],t[n+2])},i.FromInts=function(t,n,r){return new i(t/255,n/255,r/255)},i.Lerp=function(t,n,r){var o=t.r+(n.r-t.r)*r,s=t.g+(n.g-t.g)*r,e=t.b+(n.b-t.b)*r;return new i(o,s,e)},i.Red=function(){return new i(1,0,0)},i.Green=function(){return new i(0,1,0)},i.Blue=function(){return new i(0,0,1)},i.Black=function(){return new i(0,0,0)},i.White=function(){return new i(1,1,1)},i.Purple=function(){return new i(.5,0,.5)},i.Magenta=function(){return new i(1,0,1)},i.Yellow=function(){return new i(1,1,0)},i.Gray=function(){return new i(.5,.5,.5)},i}();t.Color3=i;var n=function(){function i(t,i,n,r){this.r=t,this.g=i,this.b=n,this.a=r}return i.prototype.addInPlace=function(t){return this.r+=t.r,this.g+=t.g,this.b+=t.b,this.a+=t.a,this},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,t[i+3]=this.a,this},i.prototype.add=function(t){return new i(this.r+t.r,this.g+t.g,this.b+t.b,this.a+t.a)},i.prototype.subtract=function(t){return new i(this.r-t.r,this.g-t.g,this.b-t.b,this.a-t.a)},i.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,i.a=this.a-t.a,this},i.prototype.scale=function(t){return new i(this.r*t,this.g*t,this.b*t,this.a*t)},i.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,i.a=this.a*t,this},i.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\" A:\"+this.a+\"}\"},i.prototype.clone=function(){return new i(this.r,this.g,this.b,this.a)},i.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this.a=t.a,this},i.prototype.toHexString=function(){var i=255*this.r|0,n=255*this.g|0,r=255*this.b|0,o=255*this.a|0;return\"#\"+t.Tools.ToHex(i)+t.Tools.ToHex(n)+t.Tools.ToHex(r)+t.Tools.ToHex(o)},i.FromHexString=function(n){if(\"#\"!==n.substring(0,1)||9!==n.length)return t.Tools.Warn(\"Color4.FromHexString must be called with a string like #FFFFFFFF\"),new i(0,0,0,0);var r=parseInt(n.substring(1,3),16),o=parseInt(n.substring(3,5),16),s=parseInt(n.substring(5,7),16),e=parseInt(n.substring(7,9),16);return i.FromInts(r,o,s,e)},i.Lerp=function(t,n,r){var o=new i(0,0,0,0);return i.LerpToRef(t,n,r,o),o},i.LerpToRef=function(t,i,n,r){r.r=t.r+(i.r-t.r)*n,r.g=t.g+(i.g-t.g)*n,r.b=t.b+(i.b-t.b)*n,r.a=t.a+(i.a-t.a)*n},i.FromArray=function(t,n){return void 0===n&&(n=0),new i(t[n],t[n+1],t[n+2],t[n+3])},i.FromInts=function(t,n,r,o){return new i(t/255,n/255,r/255,o/255)},i}();t.Color4=n;var r=function(){function i(t,i){this.x=t,this.y=i}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\"}\"},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,this},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this},i.prototype.copyFromFloats=function(t,i){return this.x=t,this.y=i,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y)},i.prototype.addVector3=function(t){return new i(this.x+t.x,this.y+t.y)},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y)},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y)},i.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,this},i.prototype.multiplyByFloats=function(t,n){return new i(this.x*t,this.y*n)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,this},i.prototype.negate=function(){return new i(-this.x,-this.y)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t)},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y},i.prototype.equalsWithEpsilon=function(i,n){return void 0===n&&(n=t.Engine.Epsilon),i&&t.Tools.WithinEpsilon(this.x,i.x,n)&&t.Tools.WithinEpsilon(this.y,i.y,n)},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y},i.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this},i.prototype.clone=function(){return new i(this.x,this.y)},i.Zero=function(){return new i(0,0)},i.FromArray=function(t,n){return void 0===n&&(n=0),new i(t[n],t[n+1])},i.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1]},i.CatmullRom=function(t,n,r,o,s){var e=s*s,h=s*e,a=.5*(2*n.x+(-t.x+r.x)*s+(2*t.x-5*n.x+4*r.x-o.x)*e+(-t.x+3*n.x-3*r.x+o.x)*h),u=.5*(2*n.y+(-t.y+r.y)*s+(2*t.y-5*n.y+4*r.y-o.y)*e+(-t.y+3*n.y-3*r.y+o.y)*h);return new i(a,u)},i.Clamp=function(t,n,r){var o=t.x;o=o>r.x?r.x:o,o=o<n.x?n.x:o;var s=t.y;return s=s>r.y?r.y:s,s=s<n.y?n.y:s,new i(o,s)},i.Hermite=function(t,n,r,o,s){var e=s*s,h=s*e,a=2*h-3*e+1,u=-2*h+3*e,m=h-2*e+s,y=h-e,c=t.x*a+r.x*u+n.x*m+o.x*y,f=t.y*a+r.y*u+n.y*m+o.y*y;return new i(c,f)},i.Lerp=function(t,n,r){var o=t.x+(n.x-t.x)*r,s=t.y+(n.y-t.y)*r;return new i(o,s)},i.Dot=function(t,i){return t.x*i.x+t.y*i.y},i.Normalize=function(t){var i=t.clone();return i.normalize(),i},i.Minimize=function(t,n){var r=t.x<n.x?t.x:n.x,o=t.y<n.y?t.y:n.y;return new i(r,o)},i.Maximize=function(t,n){var r=t.x>n.x?t.x:n.x,o=t.y>n.y?t.y:n.y;return new i(r,o)},i.Transform=function(t,n){var r=t.x*n.m[0]+t.y*n.m[4],o=t.x*n.m[1]+t.y*n.m[5];return new i(r,o)},i.Distance=function(t,n){return Math.sqrt(i.DistanceSquared(t,n))},i.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y;return n*n+r*r},i}();t.Vector2=r;var o=function(){function i(t,i,n){this.x=t,this.y=i,this.z=n}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"}\"},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,this},i.prototype.toQuaternion=function(){var t=new e(0,0,0,1),i=Math.cos(.5*(this.x+this.z)),n=Math.sin(.5*(this.x+this.z)),r=Math.cos(.5*(this.z-this.x)),o=Math.sin(.5*(this.z-this.x)),s=Math.cos(.5*this.y),h=Math.sin(.5*this.y);return t.x=r*h,t.y=-o*h,t.z=n*s,t.w=i*s,t},i.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y,this.z+t.z)},i.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,this},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y,this.z-t.z)},i.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,this},i.prototype.subtractFromFloats=function(t,n,r){return new i(this.x-t,this.y-n,this.z-r)},i.prototype.subtractFromFloatsToRef=function(t,i,n,r){return r.x=this.x-t,r.y=this.y-i,r.z=this.z-n,this},i.prototype.negate=function(){return new i(-this.x,-this.y,-this.z)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t,this.z*t)},i.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z},i.prototype.equalsWithEpsilon=function(i,n){return void 0===n&&(n=t.Engine.Epsilon),i&&t.Tools.WithinEpsilon(this.x,i.x,n)&&t.Tools.WithinEpsilon(this.y,i.y,n)&&t.Tools.WithinEpsilon(this.z,i.z,n)},i.prototype.equalsToFloats=function(t,i,n){return this.x===t&&this.y===i&&this.z===n},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y,this.z*t.z)},i.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,this},i.prototype.multiplyByFloats=function(t,n,r){return new i(this.x*t,this.y*n,this.z*r)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y,this.z/t.z)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,this},i.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),this},i.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),this},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z},i.prototype.normalize=function(){var t=this.length();if(0===t||1===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this},i.prototype.clone=function(){return new i(this.x,this.y,this.z)},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this},i.prototype.copyFromFloats=function(t,i,n){return this.x=t,this.y=i,this.z=n,this},i.GetClipFactor=function(t,n,r,o){var s=i.Dot(t,r)-o,e=i.Dot(n,r)-o,h=s/(s-e);return h},i.FromArray=function(t,n){return n||(n=0),new i(t[n],t[n+1],t[n+2])},i.FromFloatArray=function(t,n){return n||(n=0),new i(t[n],t[n+1],t[n+2])},i.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2]},i.FromFloatArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2]},i.FromFloatsToRef=function(t,i,n,r){r.x=t,r.y=i,r.z=n},i.Zero=function(){return new i(0,0,0)},i.Up=function(){return new i(0,1,0)},i.TransformCoordinates=function(t,n){var r=i.Zero();return i.TransformCoordinatesToRef(t,n,r),r},i.TransformCoordinatesToRef=function(t,i,n){var r=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8]+i.m[12],o=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9]+i.m[13],s=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]+i.m[14],e=t.x*i.m[3]+t.y*i.m[7]+t.z*i.m[11]+i.m[15];n.x=r/e,n.y=o/e,n.z=s/e},i.TransformCoordinatesFromFloatsToRef=function(t,i,n,r,o){var s=t*r.m[0]+i*r.m[4]+n*r.m[8]+r.m[12],e=t*r.m[1]+i*r.m[5]+n*r.m[9]+r.m[13],h=t*r.m[2]+i*r.m[6]+n*r.m[10]+r.m[14],a=t*r.m[3]+i*r.m[7]+n*r.m[11]+r.m[15];o.x=s/a,o.y=e/a,o.z=h/a},i.TransformNormal=function(t,n){var r=i.Zero();return i.TransformNormalToRef(t,n,r),r},i.TransformNormalToRef=function(t,i,n){n.x=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8],n.y=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9],n.z=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]},i.TransformNormalFromFloatsToRef=function(t,i,n,r,o){o.x=t*r.m[0]+i*r.m[4]+n*r.m[8],o.y=t*r.m[1]+i*r.m[5]+n*r.m[9],o.z=t*r.m[2]+i*r.m[6]+n*r.m[10]},i.CatmullRom=function(t,n,r,o,s){var e=s*s,h=s*e,a=.5*(2*n.x+(-t.x+r.x)*s+(2*t.x-5*n.x+4*r.x-o.x)*e+(-t.x+3*n.x-3*r.x+o.x)*h),u=.5*(2*n.y+(-t.y+r.y)*s+(2*t.y-5*n.y+4*r.y-o.y)*e+(-t.y+3*n.y-3*r.y+o.y)*h),m=.5*(2*n.z+(-t.z+r.z)*s+(2*t.z-5*n.z+4*r.z-o.z)*e+(-t.z+3*n.z-3*r.z+o.z)*h);return new i(a,u,m)},i.Clamp=function(t,n,r){var o=t.x;o=o>r.x?r.x:o,o=o<n.x?n.x:o;var s=t.y;s=s>r.y?r.y:s,s=s<n.y?n.y:s;var e=t.z;return e=e>r.z?r.z:e,e=e<n.z?n.z:e,new i(o,s,e)},i.Hermite=function(t,n,r,o,s){var e=s*s,h=s*e,a=2*h-3*e+1,u=-2*h+3*e,m=h-2*e+s,y=h-e,c=t.x*a+r.x*u+n.x*m+o.x*y,f=t.y*a+r.y*u+n.y*m+o.y*y,p=t.z*a+r.z*u+n.z*m+o.z*y;return new i(c,f,p)},i.Lerp=function(t,n,r){var o=t.x+(n.x-t.x)*r,s=t.y+(n.y-t.y)*r,e=t.z+(n.z-t.z)*r;return new i(o,s,e)},i.Dot=function(t,i){return t.x*i.x+t.y*i.y+t.z*i.z},i.Cross=function(t,n){var r=i.Zero();return i.CrossToRef(t,n,r),r},i.CrossToRef=function(t,i,n){n.x=t.y*i.z-t.z*i.y,n.y=t.z*i.x-t.x*i.z,n.z=t.x*i.y-t.y*i.x},i.Normalize=function(t){var n=i.Zero();return i.NormalizeToRef(t,n),n},i.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},i.Project=function(t,n,r,o){var s=o.width,e=o.height,a=o.x,u=o.y,m=h.FromValues(s/2,0,0,0,0,-e/2,0,0,0,0,1,0,a+s/2,e/2+u,0,1),y=n.multiply(r).multiply(m);return i.TransformCoordinates(t,y)},i.UnprojectFromTransform=function(n,r,o,s,e){var h=s.multiply(e);h.invert(),n.x=n.x/r*2-1,n.y=-(n.y/o*2-1);var a=i.TransformCoordinates(n,h),u=n.x*h.m[3]+n.y*h.m[7]+n.z*h.m[11]+h.m[15];return t.Tools.WithinEpsilon(u,1)&&(a=a.scale(1/u)),a},i.Unproject=function(n,r,o,s,e,h){var a=s.multiply(e).multiply(h);a.invert();var u=new i(n.x/r*2-1,-(n.y/o*2-1),n.z),m=i.TransformCoordinates(u,a),y=u.x*a.m[3]+u.y*a.m[7]+u.z*a.m[11]+a.m[15];return t.Tools.WithinEpsilon(y,1)&&(m=m.scale(1/y)),m},i.Minimize=function(t,i){var n=t.clone();return n.MinimizeInPlace(i),n},i.Maximize=function(t,i){var n=t.clone();return n.MaximizeInPlace(i),n},i.Distance=function(t,n){return Math.sqrt(i.DistanceSquared(t,n))},i.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y,o=t.z-i.z;return n*n+r*r+o*o},i.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},i.RotationFromAxis=function(t,n,r){var o=i.Zero();return i.RotationFromAxisToRef(t,n,r,o),o},i.RotationFromAxisToRef=function(n,r,o,s){var e,h,a,u=i.Normalize(n),m=i.Normalize(o),y=c.X,f=c.Y,p=0,l=0,x=0,z=0,w=0,v=0,g=0,d=-1,T=0,R=0;t.Tools.WithinEpsilon(m.z,0,t.Engine.Epsilon)?v=1:t.Tools.WithinEpsilon(m.x,0,t.Engine.Epsilon)?z=1:(g=m.z/m.x,z=-g*Math.sqrt(1/(1+g*g)),v=Math.sqrt(1/(1+g*g))),h=new i(z,w,v),h.normalize(),a=i.Cross(m,h),a.normalize(),e=i.Cross(u,h),e.normalize(),i.Dot(m,e)<0&&(d=1),R=i.Dot(u,h),R=Math.min(1,Math.max(-1,R)),x=Math.acos(R)*d,i.Dot(h,y)<0&&(x=Math.PI+x,h=h.scaleInPlace(-1),a=a.scaleInPlace(-1),T++);var _,M;z=0,w=0,v=0,d=-1,t.Tools.WithinEpsilon(m.z,0,t.Engine.Epsilon)?z=1:(g=h.z/h.x,z=-g*Math.sqrt(1/(1+g*g)),v=Math.sqrt(1/(1+g*g))),_=new i(z,w,v),_.normalize(),M=i.Cross(_,h),M.normalize(),e=i.Cross(m,_),e.normalize(),i.Dot(h,e)<0&&(d=1),R=i.Dot(m,_),R=Math.min(1,Math.max(-1,R)),l=Math.acos(R)*d,i.Dot(M,f)<0&&(l=Math.PI+l,M=M.scaleInPlace(-1),_=_.scaleInPlace(-1),T++),d=-1,e=i.Cross(y,h),e.normalize(),i.Dot(e,f)<0&&(d=1),R=i.Dot(h,y),R=Math.min(1,Math.max(-1,R)),p=-Math.acos(R)*d,0>R&&2>T&&(p=Math.PI+p),s.x=l,s.y=p,s.z=x},i}();t.Vector3=o;var s=function(){function i(t,i,n,r){this.x=t,this.y=i,this.z=n,this.w=r}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"W:\"+this.w+\"}\"},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,t[i+3]=this.w,this},i.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)},i.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,i.w=this.w+t.w,this},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)},i.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,i.w=this.w-t.w,this},i.prototype.subtractFromFloats=function(t,n,r,o){return new i(this.x-t,this.y-n,this.z-r,this.w-o)},i.prototype.subtractFromFloatsToRef=function(t,i,n,r,o){return o.x=this.x-t,o.y=this.y-i,o.z=this.z-n,o.w=this.w-r,this},i.prototype.negate=function(){return new i(-this.x,-this.y,-this.z,-this.w)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t,this.z*t,this.w*t)},i.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t,i.w=this.w*t},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},i.prototype.equalsWithEpsilon=function(i,n){return void 0===n&&(n=t.Engine.Epsilon),i&&t.Tools.WithinEpsilon(this.x,i.x,n)&&t.Tools.WithinEpsilon(this.y,i.y,n)&&t.Tools.WithinEpsilon(this.z,i.z,n)&&t.Tools.WithinEpsilon(this.w,i.w,n)},i.prototype.equalsToFloats=function(t,i,n,r){return this.x===t&&this.y===i&&this.z===n&&this.w===r},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y,this.z*t.z,this.w*t.w)},i.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,i.w=this.w*t.w,this},i.prototype.multiplyByFloats=function(t,n,r,o){return new i(this.x*t,this.y*n,this.z*r,this.w*o)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y,this.z/t.z,this.w/t.w)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,i.w=this.w/t.w,this},i.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),t.w<this.w&&(this.w=t.w),this},i.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),t.w>this.w&&(this.w=t.w),this},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},i.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this.w*=i,this},i.prototype.clone=function(){return new i(this.x,this.y,this.z,this.w)},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},i.prototype.copyFromFloats=function(t,i,n,r){return this.x=t,this.y=i,this.z=n,this.w=r,this},i.FromArray=function(t,n){return n||(n=0),new i(t[n],t[n+1],t[n+2],t[n+3])},i.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2],n.w=t[i+3]},i.FromFloatArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2],n.w=t[i+3]},i.FromFloatsToRef=function(t,i,n,r,o){o.x=t,o.y=i,o.z=n,o.w=r},i.Zero=function(){return new i(0,0,0,0)},i.Normalize=function(t){var n=i.Zero();return i.NormalizeToRef(t,n),n},i.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},i.Minimize=function(t,i){var n=t.clone();return n.MinimizeInPlace(i),n},i.Maximize=function(t,i){var n=t.clone();return n.MaximizeInPlace(i),n},i.Distance=function(t,n){return Math.sqrt(i.DistanceSquared(t,n))},i.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y,o=t.z-i.z,s=t.w-i.w;return n*n+r*r+o*o+s*s},i.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},i}();t.Vector4=s;var e=function(){function t(t,i,n,r){void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=0),void 0===r&&(r=1),this.x=t,this.y=i,this.z=n,this.w=r}return t.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\" W:\"+this.w+\"}\"},t.prototype.asArray=function(){return[this.x,this.y,this.z,this.w]},t.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},t.prototype.clone=function(){return new t(this.x,this.y,this.z,this.w)},t.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},t.prototype.copyFromFloats=function(t,i,n,r){return this.x=t,this.y=i,this.z=n,this.w=r,this},t.prototype.add=function(i){return new t(this.x+i.x,this.y+i.y,this.z+i.z,this.w+i.w)},t.prototype.subtract=function(i){return new t(this.x-i.x,this.y-i.y,this.z-i.z,this.w-i.w)},t.prototype.scale=function(i){return new t(this.x*i,this.y*i,this.z*i,this.w*i)},t.prototype.multiply=function(i){var n=new t(0,0,0,1);return this.multiplyToRef(i,n),n},t.prototype.multiplyToRef=function(t,i){var n=this.x*t.w+this.y*t.z-this.z*t.y+this.w*t.x,r=-this.x*t.z+this.y*t.w+this.z*t.x+this.w*t.y,o=this.x*t.y-this.y*t.x+this.z*t.w+this.w*t.z,s=-this.x*t.x-this.y*t.y-this.z*t.z+this.w*t.w;return i.copyFromFloats(n,r,o,s),this},t.prototype.multiplyInPlace=function(t){return this.multiplyToRef(t,this),this},t.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},t.prototype.normalize=function(){var t=1/this.length();return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},t.prototype.toEulerAngles=function(){var t=o.Zero();return this.toEulerAnglesToRef(t),t},t.prototype.toEulerAnglesToRef=function(t){var i=this.x,n=this.y,r=this.z,o=this.w,s=i*n,e=i*r,h=o*n,a=o*r,u=o*i,m=n*r,y=i*i,c=n*n,f=y+c;return 0!==f&&1!==f?(t.x=Math.atan2(e+h,u-m),t.y=Math.acos(1-2*f),t.z=Math.atan2(e-h,u+m)):0===f?(t.x=0,t.y=0,t.z=Math.atan2(s-a,.5-c-r*r)):(t.x=Math.atan2(s-a,.5-c-r*r),t.y=Math.PI,t.z=0),this},t.prototype.toRotationMatrix=function(t){var i=this.x*this.x,n=this.y*this.y,r=this.z*this.z,o=this.x*this.y,s=this.z*this.w,e=this.z*this.x,h=this.y*this.w,a=this.y*this.z,u=this.x*this.w;return t.m[0]=1-2*(n+r),t.m[1]=2*(o+s),t.m[2]=2*(e-h),t.m[3]=0,t.m[4]=2*(o-s),t.m[5]=1-2*(r+i),t.m[6]=2*(a+u),t.m[7]=0,t.m[8]=2*(e+h),t.m[9]=2*(a-u),t.m[10]=1-2*(n+i),t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0,t.m[15]=1,this},t.prototype.fromRotationMatrix=function(i){return t.FromRotationMatrixToRef(i,this),this},t.FromRotationMatrix=function(i){var n=new t;return t.FromRotationMatrixToRef(i,n),n},t.FromRotationMatrixToRef=function(t,i){var n,r=t.m,o=r[0],s=r[4],e=r[8],h=r[1],a=r[5],u=r[9],m=r[2],y=r[6],c=r[10],f=o+a+c;f>0?(n=.5/Math.sqrt(f+1),i.w=.25/n,i.x=(y-u)*n,i.y=(e-m)*n,i.z=(h-s)*n):o>a&&o>c?(n=2*Math.sqrt(1+o-a-c),i.w=(y-u)/n,i.x=.25*n,i.y=(s+h)/n,i.z=(e+m)/n):a>c?(n=2*Math.sqrt(1+a-o-c),i.w=(e-m)/n,i.x=(s+h)/n,i.y=.25*n,i.z=(u+y)/n):(n=2*Math.sqrt(1+c-o-a),i.w=(h-s)/n,i.x=(e+m)/n,i.y=(u+y)/n,i.z=.25*n)},t.Inverse=function(i){return new t(-i.x,-i.y,-i.z,i.w)},t.Identity=function(){return new t(0,0,0,1)},t.RotationAxis=function(i,n){var r=new t,o=Math.sin(n/2);return i.normalize(),r.w=Math.cos(n/2),r.x=i.x*o,r.y=i.y*o,r.z=i.z*o,r},t.FromArray=function(i,n){return n||(n=0),new t(i[n],i[n+1],i[n+2],i[n+3])},t.RotationYawPitchRoll=function(i,n,r){var o=new t;return t.RotationYawPitchRollToRef(i,n,r,o),o},t.RotationYawPitchRollToRef=function(t,i,n,r){var o=.5*n,s=.5*i,e=.5*t,h=Math.sin(o),a=Math.cos(o),u=Math.sin(s),m=Math.cos(s),y=Math.sin(e),c=Math.cos(e);r.x=c*u*a+y*m*h,r.y=y*m*a-c*u*h,r.z=c*m*h-y*u*a,r.w=c*m*a+y*u*h},t.RotationAlphaBetaGamma=function(i,n,r){var o=new t;return t.RotationAlphaBetaGammaToRef(i,n,r,o),o},t.RotationAlphaBetaGammaToRef=function(t,i,n,r){var o=.5*(n+t),s=.5*(n-t),e=.5*i;r.x=Math.cos(s)*Math.sin(e),r.y=Math.sin(s)*Math.sin(e),r.z=Math.sin(o)*Math.cos(e),r.w=Math.cos(o)*Math.cos(e)},t.Slerp=function(i,n,r){var o,s,e=r,h=i.x*n.x+i.y*n.y+i.z*n.z+i.w*n.w,a=!1;if(0>h&&(a=!0,h=-h),h>.999999)s=1-e,o=a?-e:e;else{var u=Math.acos(h),m=1/Math.sin(u);s=Math.sin((1-e)*u)*m,o=a?-Math.sin(e*u)*m:Math.sin(e*u)*m}return new t(s*i.x+o*n.x,s*i.y+o*n.y,s*i.z+o*n.z,s*i.w+o*n.w)},t}();t.Quaternion=e;var h=function(){function i(){this.m=new Float32Array(16)}return i.prototype.isIdentity=function(){return 1!==this.m[0]||1!==this.m[5]||1!==this.m[10]||1!==this.m[15]?!1:0!==this.m[1]||0!==this.m[2]||0!==this.m[3]||0!==this.m[4]||0!==this.m[6]||0!==this.m[7]||0!==this.m[8]||0!==this.m[9]||0!==this.m[11]||0!==this.m[12]||0!==this.m[13]||0!==this.m[14]?!1:!0},i.prototype.determinant=function(){var t=this.m[10]*this.m[15]-this.m[11]*this.m[14],i=this.m[9]*this.m[15]-this.m[11]*this.m[13],n=this.m[9]*this.m[14]-this.m[10]*this.m[13],r=this.m[8]*this.m[15]-this.m[11]*this.m[12],o=this.m[8]*this.m[14]-this.m[10]*this.m[12],s=this.m[8]*this.m[13]-this.m[9]*this.m[12];return this.m[0]*(this.m[5]*t-this.m[6]*i+this.m[7]*n)-this.m[1]*(this.m[4]*t-this.m[6]*r+this.m[7]*o)+this.m[2]*(this.m[4]*i-this.m[5]*r+this.m[7]*s)-this.m[3]*(this.m[4]*n-this.m[5]*o+this.m[6]*s)},i.prototype.toArray=function(){return this.m},i.prototype.asArray=function(){return this.toArray()},i.prototype.invert=function(){return this.invertToRef(this),this},i.prototype.reset=function(){for(var t=0;16>t;t++)this.m[t]=0;return this},i.prototype.add=function(t){var n=new i;return this.addToRef(t,n),n},i.prototype.addToRef=function(t,i){for(var n=0;16>n;n++)i.m[n]=this.m[n]+t.m[n];return this},i.prototype.addToSelf=function(t){for(var i=0;16>i;i++)this.m[i]+=t.m[i];return this},i.prototype.invertToRef=function(t){var i=this.m[0],n=this.m[1],r=this.m[2],o=this.m[3],s=this.m[4],e=this.m[5],h=this.m[6],a=this.m[7],u=this.m[8],m=this.m[9],y=this.m[10],c=this.m[11],f=this.m[12],p=this.m[13],l=this.m[14],x=this.m[15],z=y*x-c*l,w=m*x-c*p,v=m*l-y*p,g=u*x-c*f,d=u*l-y*f,T=u*p-m*f,R=e*z-h*w+a*v,_=-(s*z-h*g+a*d),M=s*w-e*g+a*T,F=-(s*v-e*d+h*T),A=1/(i*R+n*_+r*M+o*F),b=h*x-a*l,P=e*x-a*p,C=e*l-h*p,I=s*x-a*f,E=s*l-h*f,q=s*p-e*f,L=h*c-a*y,D=e*c-a*m,S=e*y-h*m,Z=s*c-a*u,N=s*y-h*u,W=s*m-e*u;return t.m[0]=R*A,t.m[4]=_*A,t.m[8]=M*A,t.m[12]=F*A,t.m[1]=-(n*z-r*w+o*v)*A,t.m[5]=(i*z-r*g+o*d)*A,t.m[9]=-(i*w-n*g+o*T)*A,t.m[13]=(i*v-n*d+r*T)*A,t.m[2]=(n*b-r*P+o*C)*A,t.m[6]=-(i*b-r*I+o*E)*A,t.m[10]=(i*P-n*I+o*q)*A,t.m[14]=-(i*C-n*E+r*q)*A,t.m[3]=-(n*L-r*D+o*S)*A,t.m[7]=(i*L-r*Z+o*N)*A,t.m[11]=-(i*D-n*Z+o*W)*A,t.m[15]=(i*S-n*N+r*W)*A,this},i.prototype.setTranslation=function(t){return this.m[12]=t.x,this.m[13]=t.y,this.m[14]=t.z,this},i.prototype.multiply=function(t){var n=new i;return this.multiplyToRef(t,n),n},i.prototype.copyFrom=function(t){for(var i=0;16>i;i++)this.m[i]=t.m[i];return this},i.prototype.copyToArray=function(t,i){void 0===i&&(i=0);for(var n=0;16>n;n++)t[i+n]=this.m[n];return this},i.prototype.multiplyToRef=function(t,i){return this.multiplyToArray(t,i.m,0),this},i.prototype.multiplyToArray=function(t,i,n){var r=this.m[0],o=this.m[1],s=this.m[2],e=this.m[3],h=this.m[4],a=this.m[5],u=this.m[6],m=this.m[7],y=this.m[8],c=this.m[9],f=this.m[10],p=this.m[11],l=this.m[12],x=this.m[13],z=this.m[14],w=this.m[15],v=t.m[0],g=t.m[1],d=t.m[2],T=t.m[3],R=t.m[4],_=t.m[5],M=t.m[6],F=t.m[7],A=t.m[8],b=t.m[9],P=t.m[10],C=t.m[11],I=t.m[12],E=t.m[13],q=t.m[14],L=t.m[15];return i[n]=r*v+o*R+s*A+e*I,i[n+1]=r*g+o*_+s*b+e*E,i[n+2]=r*d+o*M+s*P+e*q,i[n+3]=r*T+o*F+s*C+e*L,i[n+4]=h*v+a*R+u*A+m*I,i[n+5]=h*g+a*_+u*b+m*E,i[n+6]=h*d+a*M+u*P+m*q,i[n+7]=h*T+a*F+u*C+m*L,i[n+8]=y*v+c*R+f*A+p*I,i[n+9]=y*g+c*_+f*b+p*E,i[n+10]=y*d+c*M+f*P+p*q,i[n+11]=y*T+c*F+f*C+p*L,i[n+12]=l*v+x*R+z*A+w*I,i[n+13]=l*g+x*_+z*b+w*E,i[n+14]=l*d+x*M+z*P+w*q,i[n+15]=l*T+x*F+z*C+w*L,this},i.prototype.equals=function(t){return t&&this.m[0]===t.m[0]&&this.m[1]===t.m[1]&&this.m[2]===t.m[2]&&this.m[3]===t.m[3]&&this.m[4]===t.m[4]&&this.m[5]===t.m[5]&&this.m[6]===t.m[6]&&this.m[7]===t.m[7]&&this.m[8]===t.m[8]&&this.m[9]===t.m[9]&&this.m[10]===t.m[10]&&this.m[11]===t.m[11]&&this.m[12]===t.m[12]&&this.m[13]===t.m[13]&&this.m[14]===t.m[14]&&this.m[15]===t.m[15]},i.prototype.clone=function(){return i.FromValues(this.m[0],this.m[1],this.m[2],this.m[3],this.m[4],this.m[5],this.m[6],this.m[7],this.m[8],this.m[9],this.m[10],this.m[11],this.m[12],this.m[13],this.m[14],this.m[15])},i.prototype.decompose=function(n,r,o){o.x=this.m[12],o.y=this.m[13],o.z=this.m[14];var s=t.Tools.Sign(this.m[0]*this.m[1]*this.m[2]*this.m[3])<0?-1:1,h=t.Tools.Sign(this.m[4]*this.m[5]*this.m[6]*this.m[7])<0?-1:1,a=t.Tools.Sign(this.m[8]*this.m[9]*this.m[10]*this.m[11])<0?-1:1;if(n.x=s*Math.sqrt(this.m[0]*this.m[0]+this.m[1]*this.m[1]+this.m[2]*this.m[2]),n.y=h*Math.sqrt(this.m[4]*this.m[4]+this.m[5]*this.m[5]+this.m[6]*this.m[6]),n.z=a*Math.sqrt(this.m[8]*this.m[8]+this.m[9]*this.m[9]+this.m[10]*this.m[10]),0===n.x||0===n.y||0===n.z)return r.x=0,r.y=0,r.z=0,r.w=1,!1;var u=i.FromValues(this.m[0]/n.x,this.m[1]/n.x,this.m[2]/n.x,0,this.m[4]/n.y,this.m[5]/n.y,this.m[6]/n.y,0,this.m[8]/n.z,this.m[9]/n.z,this.m[10]/n.z,0,0,0,0,1);return e.FromRotationMatrixToRef(u,r),!0},i.FromArray=function(t,n){var r=new i;return n||(n=0),i.FromArrayToRef(t,n,r),r},i.FromArrayToRef=function(t,i,n){for(var r=0;16>r;r++)n.m[r]=t[r+i]},i.FromFloat32ArrayToRefScaled=function(t,i,n,r){for(var o=0;16>o;o++)r.m[o]=t[o+i]*n},i.FromValuesToRef=function(t,i,n,r,o,s,e,h,a,u,m,y,c,f,p,l,x){x.m[0]=t,x.m[1]=i,x.m[2]=n,x.m[3]=r,x.m[4]=o,x.m[5]=s,x.m[6]=e,x.m[7]=h,x.m[8]=a,x.m[9]=u,x.m[10]=m,x.m[11]=y,x.m[12]=c,x.m[13]=f,x.m[14]=p,x.m[15]=l},i.FromValues=function(t,n,r,o,s,e,h,a,u,m,y,c,f,p,l,x){var z=new i;return z.m[0]=t,z.m[1]=n,z.m[2]=r,z.m[3]=o,z.m[4]=s,z.m[5]=e,z.m[6]=h,z.m[7]=a,z.m[8]=u,z.m[9]=m,z.m[10]=y,z.m[11]=c,z.m[12]=f,z.m[13]=p,z.m[14]=l,z.m[15]=x,z},i.Compose=function(t,n,r){var o=i.FromValues(t.x,0,0,0,0,t.y,0,0,0,0,t.z,0,0,0,0,1),s=i.Identity();return n.toRotationMatrix(s),o=o.multiply(s),o.setTranslation(r),o},i.Identity=function(){return i.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},i.IdentityToRef=function(t){i.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,t)},i.Zero=function(){return i.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)},i.RotationX=function(t){var n=new i;return i.RotationXToRef(t,n),n},i.Invert=function(t){var n=new i;return t.invertToRef(n),n},i.RotationXToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[0]=1,i.m[15]=1,i.m[5]=r,i.m[10]=r,i.m[9]=-n,i.m[6]=n,i.m[1]=0,i.m[2]=0,i.m[3]=0,i.m[4]=0,i.m[7]=0,i.m[8]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationY=function(t){var n=new i;return i.RotationYToRef(t,n),n},i.RotationYToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[5]=1,i.m[15]=1,i.m[0]=r,i.m[2]=-n,i.m[8]=n,i.m[10]=r,i.m[1]=0,i.m[3]=0,i.m[4]=0,i.m[6]=0,i.m[7]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationZ=function(t){var n=new i;return i.RotationZToRef(t,n),n},i.RotationZToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[10]=1,i.m[15]=1,i.m[0]=r,i.m[1]=n,i.m[4]=-n,i.m[5]=r,i.m[2]=0,i.m[3]=0,i.m[6]=0,i.m[7]=0,i.m[8]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationAxis=function(t,n){var r=i.Zero();return i.RotationAxisToRef(t,n,r),r},i.RotationAxisToRef=function(t,i,n){var r=Math.sin(-i),o=Math.cos(-i),s=1-o;t.normalize(),n.m[0]=t.x*t.x*s+o,n.m[1]=t.x*t.y*s-t.z*r,n.m[2]=t.x*t.z*s+t.y*r,n.m[3]=0,n.m[4]=t.y*t.x*s+t.z*r,n.m[5]=t.y*t.y*s+o,n.m[6]=t.y*t.z*s-t.x*r,n.m[7]=0,n.m[8]=t.z*t.x*s-t.y*r,n.m[9]=t.z*t.y*s+t.x*r,n.m[10]=t.z*t.z*s+o,n.m[11]=0,n.m[15]=1},i.RotationYawPitchRoll=function(t,n,r){var o=new i;return i.RotationYawPitchRollToRef(t,n,r,o),o},i.RotationYawPitchRollToRef=function(t,i,n,r){e.RotationYawPitchRollToRef(t,i,n,this._tempQuaternion),this._tempQuaternion.toRotationMatrix(r)},i.Scaling=function(t,n,r){var o=i.Zero();return i.ScalingToRef(t,n,r,o),o},i.ScalingToRef=function(t,i,n,r){\nr.m[0]=t,r.m[1]=0,r.m[2]=0,r.m[3]=0,r.m[4]=0,r.m[5]=i,r.m[6]=0,r.m[7]=0,r.m[8]=0,r.m[9]=0,r.m[10]=n,r.m[11]=0,r.m[12]=0,r.m[13]=0,r.m[14]=0,r.m[15]=1},i.Translation=function(t,n,r){var o=i.Identity();return i.TranslationToRef(t,n,r,o),o},i.TranslationToRef=function(t,n,r,o){i.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,t,n,r,1,o)},i.LookAtLH=function(t,n,r){var o=i.Zero();return i.LookAtLHToRef(t,n,r,o),o},i.LookAtLHToRef=function(t,n,r,s){n.subtractToRef(t,this._zAxis),this._zAxis.normalize(),o.CrossToRef(r,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),o.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var e=-o.Dot(this._xAxis,t),h=-o.Dot(this._yAxis,t),a=-o.Dot(this._zAxis,t);return i.FromValuesToRef(this._xAxis.x,this._yAxis.x,this._zAxis.x,0,this._xAxis.y,this._yAxis.y,this._zAxis.y,0,this._xAxis.z,this._yAxis.z,this._zAxis.z,0,e,h,a,1,s)},i.OrthoLH=function(t,n,r,o){var s=i.Zero();return i.OrthoLHToRef(t,n,r,o,s),s},i.OrthoLHToRef=function(t,n,r,o,s){var e=2/t,h=2/n,a=1/(o-r),u=r/(r-o);i.FromValuesToRef(e,0,0,0,0,h,0,0,0,0,a,0,0,0,u,1,s)},i.OrthoOffCenterLH=function(t,n,r,o,s,e){var h=i.Zero();return i.OrthoOffCenterLHToRef(t,n,r,o,s,e,h),h},i.OrthoOffCenterLHToRef=function(t,i,n,r,o,s,e){e.m[0]=2/(i-t),e.m[1]=e.m[2]=e.m[3]=0,e.m[5]=2/(r-n),e.m[4]=e.m[6]=e.m[7]=0,e.m[10]=-1/(o-s),e.m[8]=e.m[9]=e.m[11]=0,e.m[12]=(t+i)/(t-i),e.m[13]=(r+n)/(n-r),e.m[14]=o/(o-s),e.m[15]=1},i.PerspectiveLH=function(t,n,r,o){var s=i.Zero();return s.m[0]=2*r/t,s.m[1]=s.m[2]=s.m[3]=0,s.m[5]=2*r/n,s.m[4]=s.m[6]=s.m[7]=0,s.m[10]=-o/(r-o),s.m[8]=s.m[9]=0,s.m[11]=1,s.m[12]=s.m[13]=s.m[15]=0,s.m[14]=r*o/(r-o),s},i.PerspectiveFovLH=function(t,n,r,o){var s=i.Zero();return i.PerspectiveFovLHToRef(t,n,r,o,s),s},i.PerspectiveFovLHToRef=function(i,n,r,o,s,e){void 0===e&&(e=t.Camera.FOVMODE_VERTICAL_FIXED);var h=1/Math.tan(.5*i),a=e===t.Camera.FOVMODE_VERTICAL_FIXED;a?s.m[0]=h/n:s.m[0]=h,s.m[1]=s.m[2]=s.m[3]=0,a?s.m[5]=h:s.m[5]=h*n,s.m[4]=s.m[6]=s.m[7]=0,s.m[8]=s.m[9]=0,s.m[10]=-o/(r-o),s.m[11]=1,s.m[12]=s.m[13]=s.m[15]=0,s.m[14]=r*o/(r-o)},i.GetFinalMatrix=function(t,n,r,o,s,e){var h=t.width,a=t.height,u=t.x,m=t.y,y=i.FromValues(h/2,0,0,0,0,-a/2,0,0,0,0,e-s,0,u+h/2,a/2+m,s,1);return n.multiply(r).multiply(o).multiply(y)},i.GetAsMatrix2x2=function(t){return new Float32Array([t.m[0],t.m[1],t.m[4],t.m[5]])},i.GetAsMatrix3x3=function(t){return new Float32Array([t.m[0],t.m[1],t.m[2],t.m[4],t.m[5],t.m[6],t.m[8],t.m[9],t.m[10]])},i.Transpose=function(t){var n=new i;return n.m[0]=t.m[0],n.m[1]=t.m[4],n.m[2]=t.m[8],n.m[3]=t.m[12],n.m[4]=t.m[1],n.m[5]=t.m[5],n.m[6]=t.m[9],n.m[7]=t.m[13],n.m[8]=t.m[2],n.m[9]=t.m[6],n.m[10]=t.m[10],n.m[11]=t.m[14],n.m[12]=t.m[3],n.m[13]=t.m[7],n.m[14]=t.m[11],n.m[15]=t.m[15],n},i.Reflection=function(t){var n=new i;return i.ReflectionToRef(t,n),n},i.ReflectionToRef=function(t,i){t.normalize();var n=t.normal.x,r=t.normal.y,o=t.normal.z,s=-2*n,e=-2*r,h=-2*o;i.m[0]=s*n+1,i.m[1]=e*n,i.m[2]=h*n,i.m[3]=0,i.m[4]=s*r,i.m[5]=e*r+1,i.m[6]=h*r,i.m[7]=0,i.m[8]=s*o,i.m[9]=e*o,i.m[10]=h*o+1,i.m[11]=0,i.m[12]=s*t.d,i.m[13]=e*t.d,i.m[14]=h*t.d,i.m[15]=1},i._tempQuaternion=new e,i._xAxis=o.Zero(),i._yAxis=o.Zero(),i._zAxis=o.Zero(),i}();t.Matrix=h;var a=function(){function t(t,i,n,r){this.normal=new o(t,i,n),this.d=r}return t.prototype.asArray=function(){return[this.normal.x,this.normal.y,this.normal.z,this.d]},t.prototype.clone=function(){return new t(this.normal.x,this.normal.y,this.normal.z,this.d)},t.prototype.normalize=function(){var t=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z),i=0;return 0!==t&&(i=1/t),this.normal.x*=i,this.normal.y*=i,this.normal.z*=i,this.d*=i,this},t.prototype.transform=function(i){var n=h.Transpose(i),r=this.normal.x,o=this.normal.y,s=this.normal.z,e=this.d,a=r*n.m[0]+o*n.m[1]+s*n.m[2]+e*n.m[3],u=r*n.m[4]+o*n.m[5]+s*n.m[6]+e*n.m[7],m=r*n.m[8]+o*n.m[9]+s*n.m[10]+e*n.m[11],y=r*n.m[12]+o*n.m[13]+s*n.m[14]+e*n.m[15];return new t(a,u,m,y)},t.prototype.dotCoordinate=function(t){return this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z+this.d},t.prototype.copyFromPoints=function(t,i,n){var r,o=i.x-t.x,s=i.y-t.y,e=i.z-t.z,h=n.x-t.x,a=n.y-t.y,u=n.z-t.z,m=s*u-e*a,y=e*h-o*u,c=o*a-s*h,f=Math.sqrt(m*m+y*y+c*c);return r=0!==f?1/f:0,this.normal.x=m*r,this.normal.y=y*r,this.normal.z=c*r,this.d=-(this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z),this},t.prototype.isFrontFacingTo=function(t,i){var n=o.Dot(this.normal,t);return i>=n},t.prototype.signedDistanceTo=function(t){return o.Dot(t,this.normal)+this.d},t.FromArray=function(i){return new t(i[0],i[1],i[2],i[3])},t.FromPoints=function(i,n,r){var o=new t(0,0,0,0);return o.copyFromPoints(i,n,r),o},t.FromPositionAndNormal=function(i,n){var r=new t(0,0,0,0);return n.normalize(),r.normal=n,r.d=-(n.x*i.x+n.y*i.y+n.z*i.z),r},t.SignedDistanceToPlaneFromPositionAndNormal=function(t,i,n){var r=-(i.x*t.x+i.y*t.y+i.z*t.z);return o.Dot(n,i)+r},t}();t.Plane=a;var u=function(){function t(t,i,n,r){this.x=t,this.y=i,this.width=n,this.height=r}return t.prototype.toGlobal=function(i){var n=i.getRenderWidth(),r=i.getRenderHeight();return new t(this.x*n,this.y*r,this.width*n,this.height*r)},t}();t.Viewport=u;var m=function(){function t(){}return t.GetPlanes=function(i){for(var n=[],r=0;6>r;r++)n.push(new a(0,0,0,0));return t.GetPlanesToRef(i,n),n},t.GetPlanesToRef=function(t,i){i[0].normal.x=t.m[3]+t.m[2],i[0].normal.y=t.m[7]+t.m[6],i[0].normal.z=t.m[11]+t.m[10],i[0].d=t.m[15]+t.m[14],i[0].normalize(),i[1].normal.x=t.m[3]-t.m[2],i[1].normal.y=t.m[7]-t.m[6],i[1].normal.z=t.m[11]-t.m[10],i[1].d=t.m[15]-t.m[14],i[1].normalize(),i[2].normal.x=t.m[3]+t.m[0],i[2].normal.y=t.m[7]+t.m[4],i[2].normal.z=t.m[11]+t.m[8],i[2].d=t.m[15]+t.m[12],i[2].normalize(),i[3].normal.x=t.m[3]-t.m[0],i[3].normal.y=t.m[7]-t.m[4],i[3].normal.z=t.m[11]-t.m[8],i[3].d=t.m[15]-t.m[12],i[3].normalize(),i[4].normal.x=t.m[3]-t.m[1],i[4].normal.y=t.m[7]-t.m[5],i[4].normal.z=t.m[11]-t.m[9],i[4].d=t.m[15]-t.m[13],i[4].normalize(),i[5].normal.x=t.m[3]+t.m[1],i[5].normal.y=t.m[7]+t.m[5],i[5].normal.z=t.m[11]+t.m[9],i[5].d=t.m[15]+t.m[13],i[5].normalize()},t}();t.Frustum=m;var y=function(){function i(t,i,n){void 0===n&&(n=Number.MAX_VALUE),this.origin=t,this.direction=i,this.length=n}return i.prototype.intersectsBoxMinMax=function(t,i){var n,r,o,s,e=0,h=Number.MAX_VALUE;if(Math.abs(this.direction.x)<1e-7){if(this.origin.x<t.x||this.origin.x>i.x)return!1}else if(n=1/this.direction.x,r=(t.x-this.origin.x)*n,o=(i.x-this.origin.x)*n,o===-(1/0)&&(o=1/0),r>o&&(s=r,r=o,o=s),e=Math.max(r,e),h=Math.min(o,h),e>h)return!1;if(Math.abs(this.direction.y)<1e-7){if(this.origin.y<t.y||this.origin.y>i.y)return!1}else if(n=1/this.direction.y,r=(t.y-this.origin.y)*n,o=(i.y-this.origin.y)*n,o===-(1/0)&&(o=1/0),r>o&&(s=r,r=o,o=s),e=Math.max(r,e),h=Math.min(o,h),e>h)return!1;if(Math.abs(this.direction.z)<1e-7){if(this.origin.z<t.z||this.origin.z>i.z)return!1}else if(n=1/this.direction.z,r=(t.z-this.origin.z)*n,o=(i.z-this.origin.z)*n,o===-(1/0)&&(o=1/0),r>o&&(s=r,r=o,o=s),e=Math.max(r,e),h=Math.min(o,h),e>h)return!1;return!0},i.prototype.intersectsBox=function(t){return this.intersectsBoxMinMax(t.minimum,t.maximum)},i.prototype.intersectsSphere=function(t){var i=t.center.x-this.origin.x,n=t.center.y-this.origin.y,r=t.center.z-this.origin.z,o=i*i+n*n+r*r,s=t.radius*t.radius;if(s>=o)return!0;var e=i*this.direction.x+n*this.direction.y+r*this.direction.z;if(0>e)return!1;var h=o-e*e;return s>=h},i.prototype.intersectsTriangle=function(i,n,r){this._edge1||(this._edge1=o.Zero(),this._edge2=o.Zero(),this._pvec=o.Zero(),this._tvec=o.Zero(),this._qvec=o.Zero()),n.subtractToRef(i,this._edge1),r.subtractToRef(i,this._edge2),o.CrossToRef(this.direction,this._edge2,this._pvec);var s=o.Dot(this._edge1,this._pvec);if(0===s)return null;var e=1/s;this.origin.subtractToRef(i,this._tvec);var h=o.Dot(this._tvec,this._pvec)*e;if(0>h||h>1)return null;o.CrossToRef(this._tvec,this._edge1,this._qvec);var a=o.Dot(this.direction,this._qvec)*e;if(0>a||h+a>1)return null;var u=o.Dot(this._edge2,this._qvec)*e;return u>this.length?null:new t.IntersectionInfo(h,a,u)},i.CreateNew=function(t,n,r,s,e,h,a){var u=o.Unproject(new o(t,n,0),r,s,e,h,a),m=o.Unproject(new o(t,n,1),r,s,e,h,a),y=m.subtract(u);return y.normalize(),new i(u,y)},i.CreateNewFromTo=function(t,n,r){void 0===r&&(r=h.Identity());var o=n.subtract(t),s=Math.sqrt(o.x*o.x+o.y*o.y+o.z*o.z);return o.normalize(),i.Transform(new i(t,o,s),r)},i.Transform=function(t,n){var r=o.TransformCoordinates(t.origin,n),s=o.TransformNormal(t.direction,n);return new i(r,s,t.length)},i}();t.Ray=y,function(t){t[t.LOCAL=0]=\"LOCAL\",t[t.WORLD=1]=\"WORLD\"}(t.Space||(t.Space={}));var c=(t.Space,function(){function t(){}return t.X=new o(1,0,0),t.Y=new o(0,1,0),t.Z=new o(0,0,1),t}());t.Axis=c;var f=function(){function t(){}return t.interpolate=function(t,i,n,r,o){for(var s=1-3*r+3*i,e=3*r-6*i,h=3*i,a=t,u=0;5>u;u++){var m=a*a,y=m*a,c=s*y+e*m+h*a,f=1/(3*s*m+2*e*a+h);a-=(c-t)*f,a=Math.min(1,Math.max(0,a))}return 3*Math.pow(1-a,2)*a*n+3*(1-a)*Math.pow(a,2)*o+Math.pow(a,3)},t}();t.BezierCurve=f,function(t){t[t.CW=0]=\"CW\",t[t.CCW=1]=\"CCW\"}(t.Orientation||(t.Orientation={}));var p=t.Orientation,l=function(){function t(t){var i=this;this.degrees=function(){return 180*i._radians/Math.PI},this.radians=function(){return i._radians},this._radians=t,this._radians<0&&(this._radians+=2*Math.PI)}return t.BetweenTwoPoints=function(i,n){var r=n.subtract(i),o=Math.atan2(r.y,r.x);return new t(o)},t.FromRadians=function(i){return new t(i)},t.FromDegrees=function(i){return new t(i*Math.PI/180)},t}();t.Angle=l;var x=function(){function t(t,i,n){this.startPoint=t,this.midPoint=i,this.endPoint=n;var o=Math.pow(i.x,2)+Math.pow(i.y,2),s=(Math.pow(t.x,2)+Math.pow(t.y,2)-o)/2,e=(o-Math.pow(n.x,2)-Math.pow(n.y,2))/2,h=(t.x-i.x)*(i.y-n.y)-(i.x-n.x)*(t.y-i.y);this.centerPoint=new r((s*(i.y-n.y)-e*(t.y-i.y))/h,((t.x-i.x)*e-(i.x-n.x)*s)/h),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=l.BetweenTwoPoints(this.centerPoint,this.startPoint);var a=this.startAngle.degrees(),u=l.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),m=l.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();u-a>180&&(u-=360),-180>u-a&&(u+=360),m-u>180&&(m-=360),-180>m-u&&(m+=360),this.orientation=0>u-a?p.CW:p.CCW,this.angle=l.FromDegrees(this.orientation===p.CW?a-m:m-a)}return t}();t.Arc2=x;var z=function(){function t(t){this.path=t,this._onchange=new Array,this.value=0,this.animations=new Array}return t.prototype.getPoint=function(){var t=this.path.getPointAtLengthPosition(this.value);return new o(t.x,0,t.y)},t.prototype.moveAhead=function(t){return void 0===t&&(t=.002),this.move(t),this},t.prototype.moveBack=function(t){return void 0===t&&(t=.002),this.move(-t),this},t.prototype.move=function(t){if(Math.abs(t)>1)throw\"step size should be less than 1.\";return this.value+=t,this.ensureLimits(),this.raiseOnChange(),this},t.prototype.ensureLimits=function(){for(;this.value>1;)this.value-=1;for(;this.value<0;)this.value+=1;return this},t.prototype.markAsDirty=function(t){return this.ensureLimits(),this.raiseOnChange(),this},t.prototype.raiseOnChange=function(){var t=this;return this._onchange.forEach(function(i){return i(t)}),this},t.prototype.onchange=function(t){return this._onchange.push(t),this},t}();t.PathCursor=z;var w=function(){function i(t,i){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new r(t,i))}return i.prototype.addLineTo=function(i,n){if(closed)return t.Tools.Error(\"cannot add lines to closed paths\"),this;var o=new r(i,n),s=this._points[this._points.length-1];return this._points.push(o),this._length+=o.subtract(s).length(),this},i.prototype.addArcTo=function(i,n,o,s,e){if(void 0===e&&(e=36),closed)return t.Tools.Error(\"cannot add arcs to closed paths\"),this;var h=this._points[this._points.length-1],a=new r(i,n),u=new r(o,s),m=new x(h,a,u),y=m.angle.radians()/e;m.orientation===p.CW&&(y*=-1);for(var c=m.startAngle.radians()+y,f=0;e>f;f++){var l=Math.cos(c)*m.radius+m.centerPoint.x,z=Math.sin(c)*m.radius+m.centerPoint.y;this.addLineTo(l,z),c+=y}return this},i.prototype.close=function(){return this.closed=!0,this},i.prototype.length=function(){var t=this._length;if(!this.closed){var i=this._points[this._points.length-1],n=this._points[0];t+=n.subtract(i).length()}return t},i.prototype.getPoints=function(){return this._points},i.prototype.getPointAtLengthPosition=function(i){if(0>i||i>1)return t.Tools.Error(\"normalized length position should be between 0 and 1.\"),r.Zero();for(var n=i*this.length(),o=0,s=0;s<this._points.length;s++){var e=(s+1)%this._points.length,h=this._points[s],a=this._points[e],u=a.subtract(h),m=u.length()+o;if(n>=o&&m>=n){var y=u.normalize(),c=n-o;return new r(h.x+y.x*c,h.y+y.y*c)}o=m}return t.Tools.Error(\"internal error\"),r.Zero()},i.StartingAt=function(t,n){return new i(t,n)},i}();t.Path2=w;var v=function(){function i(t,i,n){this.path=t,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array;for(var r=0;r<t.length;r++)this._curve[r]=t[r].clone();this._raw=n||!1,this._compute(i)}return i.prototype.getCurve=function(){return this._curve},i.prototype.getTangents=function(){return this._tangents},i.prototype.getNormals=function(){return this._normals},i.prototype.getBinormals=function(){return this._binormals},i.prototype.getDistances=function(){return this._distances},i.prototype.update=function(t,i){for(var n=0;n<t.length;n++)this._curve[n].x=t[n].x,this._curve[n].y=t[n].y,this._curve[n].z=t[n].z;return this._compute(i),this},i.prototype._compute=function(t){var i=this._curve.length;this._tangents[0]=this._getFirstNonNullVector(0),this._raw||this._tangents[0].normalize(),this._tangents[i-1]=this._curve[i-1].subtract(this._curve[i-2]),this._raw||this._tangents[i-1].normalize();var n=this._tangents[0],r=this._normalVector(this._curve[0],n,t);this._normals[0]=r,this._raw||this._normals[0].normalize(),this._binormals[0]=o.Cross(n,this._normals[0]),this._raw||this._binormals[0].normalize(),this._distances[0]=0;for(var s,e,h,a,u=1;i>u;u++)s=this._getLastNonNullVector(u),i-1>u&&(e=this._getFirstNonNullVector(u),this._tangents[u]=s.add(e),this._tangents[u].normalize()),this._distances[u]=this._distances[u-1]+s.length(),h=this._tangents[u],a=this._binormals[u-1],this._normals[u]=o.Cross(a,h),this._raw||this._normals[u].normalize(),this._binormals[u]=o.Cross(h,this._normals[u]),this._raw||this._binormals[u].normalize()},i.prototype._getFirstNonNullVector=function(t){for(var i=1,n=this._curve[t+i].subtract(this._curve[t]);0===n.length()&&t+i+1<this._curve.length;)i++,n=this._curve[t+i].subtract(this._curve[t]);return n},i.prototype._getLastNonNullVector=function(t){for(var i=1,n=this._curve[t].subtract(this._curve[t-i]);0===n.length()&&t>i+1;)i++,n=this._curve[t].subtract(this._curve[t-i]);return n},i.prototype._normalVector=function(i,n,r){var s;if(void 0===r||null===r){var e;t.Tools.WithinEpsilon(n.y,1,t.Engine.Epsilon)?t.Tools.WithinEpsilon(n.x,1,t.Engine.Epsilon)?t.Tools.WithinEpsilon(n.z,1,t.Engine.Epsilon)||(e=new o(0,0,1)):e=new o(1,0,0):e=new o(0,-1,0),s=o.Cross(n,e)}else s=o.Cross(n,r),o.CrossToRef(s,n,s);return s.normalize(),s},i}();t.Path3D=v;var g=function(){function t(t){this._length=0,this._points=t,this._length=this._computeLength(t)}return t.CreateQuadraticBezier=function(i,n,r,s){s=s>2?s:3;for(var e=new Array,h=function(t,i,n,r){var o=(1-t)*(1-t)*i+2*t*(1-t)*n+t*t*r;return o},a=0;s>=a;a++)e.push(new o(h(a/s,i.x,n.x,r.x),h(a/s,i.y,n.y,r.y),h(a/s,i.z,n.z,r.z)));return new t(e)},t.CreateCubicBezier=function(i,n,r,s,e){e=e>3?e:4;for(var h=new Array,a=function(t,i,n,r,o){var s=(1-t)*(1-t)*(1-t)*i+3*t*(1-t)*(1-t)*n+3*t*t*(1-t)*r+t*t*t*o;return s},u=0;e>=u;u++)h.push(new o(a(u/e,i.x,n.x,r.x,s.x),a(u/e,i.y,n.y,r.y,s.y),a(u/e,i.z,n.z,r.z,s.z)));return new t(h)},t.CreateHermiteSpline=function(i,n,r,s,e){for(var h=new Array,a=1/e,u=0;e>=u;u++)h.push(o.Hermite(i,n,r,s,u*a));return new t(h)},t.prototype.getPoints=function(){return this._points},t.prototype.length=function(){return this._length},t.prototype[\"continue\"]=function(i){for(var n=this._points[this._points.length-1],r=this._points.slice(),o=i.getPoints(),s=1;s<o.length;s++)r.push(o[s].subtract(o[0]).add(n));var e=new t(r);return e},t.prototype._computeLength=function(t){for(var i=0,n=1;n<t.length;n++)i+=t[n].subtract(t[n-1]).length();return i},t}();t.Curve3=g;var d=function(){function t(t,i){void 0===t&&(t=o.Zero()),void 0===i&&(i=o.Up()),this.position=t,this.normal=i}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone())},t}();t.PositionNormalVertex=d;var T=function(){function t(t,i,n){void 0===t&&(t=o.Zero()),void 0===i&&(i=o.Up()),void 0===n&&(n=r.Zero()),this.position=t,this.normal=i,this.uv=n}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone(),this.uv.clone())},t}();t.PositionNormalTextureVertex=T}(BABYLON||(BABYLON={}));";
  35809. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  35810. module.exports = BABYLON;
  35811. };