babylon.max.js 2.0 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190
  1. var __extends = (this && this.__extends) || function (d, b) {
  2. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  3. function __() { this.constructor = d; }
  4. __.prototype = b.prototype;
  5. d.prototype = new __();
  6. };
  7. var BABYLON;
  8. (function (BABYLON) {
  9. var ToGammaSpace = 1 / 2.2;
  10. var ToLinearSpace = 2.2;
  11. var Color3 = (function () {
  12. function Color3(r, g, b) {
  13. if (r === void 0) { r = 0; }
  14. if (g === void 0) { g = 0; }
  15. if (b === void 0) { b = 0; }
  16. this.r = r;
  17. this.g = g;
  18. this.b = b;
  19. }
  20. Color3.prototype.toString = function () {
  21. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  22. };
  23. // Operators
  24. Color3.prototype.toArray = function (array, index) {
  25. if (index === undefined) {
  26. index = 0;
  27. }
  28. array[index] = this.r;
  29. array[index + 1] = this.g;
  30. array[index + 2] = this.b;
  31. return this;
  32. };
  33. Color3.prototype.toColor4 = function (alpha) {
  34. if (alpha === void 0) { alpha = 1; }
  35. return new Color4(this.r, this.g, this.b, alpha);
  36. };
  37. Color3.prototype.asArray = function () {
  38. var result = [];
  39. this.toArray(result, 0);
  40. return result;
  41. };
  42. Color3.prototype.toLuminance = function () {
  43. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  44. };
  45. Color3.prototype.multiply = function (otherColor) {
  46. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  47. };
  48. Color3.prototype.multiplyToRef = function (otherColor, result) {
  49. result.r = this.r * otherColor.r;
  50. result.g = this.g * otherColor.g;
  51. result.b = this.b * otherColor.b;
  52. return this;
  53. };
  54. Color3.prototype.equals = function (otherColor) {
  55. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  56. };
  57. Color3.prototype.equalsFloats = function (r, g, b) {
  58. return this.r === r && this.g === g && this.b === b;
  59. };
  60. Color3.prototype.scale = function (scale) {
  61. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  62. };
  63. Color3.prototype.scaleToRef = function (scale, result) {
  64. result.r = this.r * scale;
  65. result.g = this.g * scale;
  66. result.b = this.b * scale;
  67. return this;
  68. };
  69. Color3.prototype.add = function (otherColor) {
  70. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  71. };
  72. Color3.prototype.addToRef = function (otherColor, result) {
  73. result.r = this.r + otherColor.r;
  74. result.g = this.g + otherColor.g;
  75. result.b = this.b + otherColor.b;
  76. return this;
  77. };
  78. Color3.prototype.subtract = function (otherColor) {
  79. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  80. };
  81. Color3.prototype.subtractToRef = function (otherColor, result) {
  82. result.r = this.r - otherColor.r;
  83. result.g = this.g - otherColor.g;
  84. result.b = this.b - otherColor.b;
  85. return this;
  86. };
  87. Color3.prototype.clone = function () {
  88. return new Color3(this.r, this.g, this.b);
  89. };
  90. Color3.prototype.copyFrom = function (source) {
  91. this.r = source.r;
  92. this.g = source.g;
  93. this.b = source.b;
  94. return this;
  95. };
  96. Color3.prototype.copyFromFloats = function (r, g, b) {
  97. this.r = r;
  98. this.g = g;
  99. this.b = b;
  100. return this;
  101. };
  102. Color3.prototype.toHexString = function () {
  103. var intR = (this.r * 255) | 0;
  104. var intG = (this.g * 255) | 0;
  105. var intB = (this.b * 255) | 0;
  106. return "#" + BABYLON.Tools.ToHex(intR) + BABYLON.Tools.ToHex(intG) + BABYLON.Tools.ToHex(intB);
  107. };
  108. Color3.prototype.toLinearSpace = function () {
  109. var convertedColor = new Color3();
  110. this.toLinearSpaceToRef(convertedColor);
  111. return convertedColor;
  112. };
  113. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  114. convertedColor.r = Math.pow(this.r, ToLinearSpace);
  115. convertedColor.g = Math.pow(this.g, ToLinearSpace);
  116. convertedColor.b = Math.pow(this.b, ToLinearSpace);
  117. return this;
  118. };
  119. Color3.prototype.toGammaSpace = function () {
  120. var convertedColor = new Color3();
  121. this.toGammaSpaceToRef(convertedColor);
  122. return convertedColor;
  123. };
  124. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  125. convertedColor.r = Math.pow(this.r, ToGammaSpace);
  126. convertedColor.g = Math.pow(this.g, ToGammaSpace);
  127. convertedColor.b = Math.pow(this.b, ToGammaSpace);
  128. return this;
  129. };
  130. // Statics
  131. Color3.FromHexString = function (hex) {
  132. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  133. BABYLON.Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  134. return new Color3(0, 0, 0);
  135. }
  136. var r = parseInt(hex.substring(1, 3), 16);
  137. var g = parseInt(hex.substring(3, 5), 16);
  138. var b = parseInt(hex.substring(5, 7), 16);
  139. return Color3.FromInts(r, g, b);
  140. };
  141. Color3.FromArray = function (array, offset) {
  142. if (offset === void 0) { offset = 0; }
  143. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  144. };
  145. Color3.FromInts = function (r, g, b) {
  146. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  147. };
  148. Color3.Lerp = function (start, end, amount) {
  149. var r = start.r + ((end.r - start.r) * amount);
  150. var g = start.g + ((end.g - start.g) * amount);
  151. var b = start.b + ((end.b - start.b) * amount);
  152. return new Color3(r, g, b);
  153. };
  154. Color3.Red = function () { return new Color3(1, 0, 0); };
  155. Color3.Green = function () { return new Color3(0, 1, 0); };
  156. Color3.Blue = function () { return new Color3(0, 0, 1); };
  157. Color3.Black = function () { return new Color3(0, 0, 0); };
  158. Color3.White = function () { return new Color3(1, 1, 1); };
  159. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  160. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  161. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  162. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  163. return Color3;
  164. })();
  165. BABYLON.Color3 = Color3;
  166. var Color4 = (function () {
  167. function Color4(r, g, b, a) {
  168. this.r = r;
  169. this.g = g;
  170. this.b = b;
  171. this.a = a;
  172. }
  173. // Operators
  174. Color4.prototype.addInPlace = function (right) {
  175. this.r += right.r;
  176. this.g += right.g;
  177. this.b += right.b;
  178. this.a += right.a;
  179. return this;
  180. };
  181. Color4.prototype.asArray = function () {
  182. var result = [];
  183. this.toArray(result, 0);
  184. return result;
  185. };
  186. Color4.prototype.toArray = function (array, index) {
  187. if (index === undefined) {
  188. index = 0;
  189. }
  190. array[index] = this.r;
  191. array[index + 1] = this.g;
  192. array[index + 2] = this.b;
  193. array[index + 3] = this.a;
  194. return this;
  195. };
  196. Color4.prototype.add = function (right) {
  197. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  198. };
  199. Color4.prototype.subtract = function (right) {
  200. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  201. };
  202. Color4.prototype.subtractToRef = function (right, result) {
  203. result.r = this.r - right.r;
  204. result.g = this.g - right.g;
  205. result.b = this.b - right.b;
  206. result.a = this.a - right.a;
  207. return this;
  208. };
  209. Color4.prototype.scale = function (scale) {
  210. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  211. };
  212. Color4.prototype.scaleToRef = function (scale, result) {
  213. result.r = this.r * scale;
  214. result.g = this.g * scale;
  215. result.b = this.b * scale;
  216. result.a = this.a * scale;
  217. return this;
  218. };
  219. Color4.prototype.toString = function () {
  220. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  221. };
  222. Color4.prototype.clone = function () {
  223. return new Color4(this.r, this.g, this.b, this.a);
  224. };
  225. Color4.prototype.copyFrom = function (source) {
  226. this.r = source.r;
  227. this.g = source.g;
  228. this.b = source.b;
  229. this.a = source.a;
  230. return this;
  231. };
  232. Color4.prototype.toHexString = function () {
  233. var intR = (this.r * 255) | 0;
  234. var intG = (this.g * 255) | 0;
  235. var intB = (this.b * 255) | 0;
  236. var intA = (this.a * 255) | 0;
  237. return "#" + BABYLON.Tools.ToHex(intR) + BABYLON.Tools.ToHex(intG) + BABYLON.Tools.ToHex(intB) + BABYLON.Tools.ToHex(intA);
  238. };
  239. // Statics
  240. Color4.FromHexString = function (hex) {
  241. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  242. BABYLON.Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  243. return new Color4(0, 0, 0, 0);
  244. }
  245. var r = parseInt(hex.substring(1, 3), 16);
  246. var g = parseInt(hex.substring(3, 5), 16);
  247. var b = parseInt(hex.substring(5, 7), 16);
  248. var a = parseInt(hex.substring(7, 9), 16);
  249. return Color4.FromInts(r, g, b, a);
  250. };
  251. Color4.Lerp = function (left, right, amount) {
  252. var result = new Color4(0, 0, 0, 0);
  253. Color4.LerpToRef(left, right, amount, result);
  254. return result;
  255. };
  256. Color4.LerpToRef = function (left, right, amount, result) {
  257. result.r = left.r + (right.r - left.r) * amount;
  258. result.g = left.g + (right.g - left.g) * amount;
  259. result.b = left.b + (right.b - left.b) * amount;
  260. result.a = left.a + (right.a - left.a) * amount;
  261. };
  262. Color4.FromArray = function (array, offset) {
  263. if (offset === void 0) { offset = 0; }
  264. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  265. };
  266. Color4.FromInts = function (r, g, b, a) {
  267. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  268. };
  269. Color4.CheckColors4 = function (colors, count) {
  270. // Check if color3 was used
  271. if (colors.length === count * 3) {
  272. var colors4 = [];
  273. for (var index = 0; index < colors.length; index += 3) {
  274. var newIndex = (index / 3) * 4;
  275. colors4[newIndex] = colors[index];
  276. colors4[newIndex + 1] = colors[index + 1];
  277. colors4[newIndex + 2] = colors[index + 2];
  278. colors4[newIndex + 3] = 1.0;
  279. }
  280. return colors4;
  281. }
  282. return colors;
  283. };
  284. return Color4;
  285. })();
  286. BABYLON.Color4 = Color4;
  287. var Vector2 = (function () {
  288. function Vector2(x, y) {
  289. this.x = x;
  290. this.y = y;
  291. }
  292. Vector2.prototype.toString = function () {
  293. return "{X: " + this.x + " Y:" + this.y + "}";
  294. };
  295. // Operators
  296. Vector2.prototype.toArray = function (array, index) {
  297. if (index === void 0) { index = 0; }
  298. array[index] = this.x;
  299. array[index + 1] = this.y;
  300. return this;
  301. };
  302. Vector2.prototype.asArray = function () {
  303. var result = [];
  304. this.toArray(result, 0);
  305. return result;
  306. };
  307. Vector2.prototype.copyFrom = function (source) {
  308. this.x = source.x;
  309. this.y = source.y;
  310. return this;
  311. };
  312. Vector2.prototype.copyFromFloats = function (x, y) {
  313. this.x = x;
  314. this.y = y;
  315. return this;
  316. };
  317. Vector2.prototype.add = function (otherVector) {
  318. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  319. };
  320. Vector2.prototype.addVector3 = function (otherVector) {
  321. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  322. };
  323. Vector2.prototype.subtract = function (otherVector) {
  324. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  325. };
  326. Vector2.prototype.subtractInPlace = function (otherVector) {
  327. this.x -= otherVector.x;
  328. this.y -= otherVector.y;
  329. return this;
  330. };
  331. Vector2.prototype.multiplyInPlace = function (otherVector) {
  332. this.x *= otherVector.x;
  333. this.y *= otherVector.y;
  334. return this;
  335. };
  336. Vector2.prototype.multiply = function (otherVector) {
  337. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  338. };
  339. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  340. result.x = this.x * otherVector.x;
  341. result.y = this.y * otherVector.y;
  342. return this;
  343. };
  344. Vector2.prototype.multiplyByFloats = function (x, y) {
  345. return new Vector2(this.x * x, this.y * y);
  346. };
  347. Vector2.prototype.divide = function (otherVector) {
  348. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  349. };
  350. Vector2.prototype.divideToRef = function (otherVector, result) {
  351. result.x = this.x / otherVector.x;
  352. result.y = this.y / otherVector.y;
  353. return this;
  354. };
  355. Vector2.prototype.negate = function () {
  356. return new Vector2(-this.x, -this.y);
  357. };
  358. Vector2.prototype.scaleInPlace = function (scale) {
  359. this.x *= scale;
  360. this.y *= scale;
  361. return this;
  362. };
  363. Vector2.prototype.scale = function (scale) {
  364. return new Vector2(this.x * scale, this.y * scale);
  365. };
  366. Vector2.prototype.equals = function (otherVector) {
  367. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  368. };
  369. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  370. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  371. return otherVector && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon);
  372. };
  373. // Properties
  374. Vector2.prototype.length = function () {
  375. return Math.sqrt(this.x * this.x + this.y * this.y);
  376. };
  377. Vector2.prototype.lengthSquared = function () {
  378. return (this.x * this.x + this.y * this.y);
  379. };
  380. // Methods
  381. Vector2.prototype.normalize = function () {
  382. var len = this.length();
  383. if (len === 0)
  384. return this;
  385. var num = 1.0 / len;
  386. this.x *= num;
  387. this.y *= num;
  388. return this;
  389. };
  390. Vector2.prototype.clone = function () {
  391. return new Vector2(this.x, this.y);
  392. };
  393. // Statics
  394. Vector2.Zero = function () {
  395. return new Vector2(0, 0);
  396. };
  397. Vector2.FromArray = function (array, offset) {
  398. if (offset === void 0) { offset = 0; }
  399. return new Vector2(array[offset], array[offset + 1]);
  400. };
  401. Vector2.FromArrayToRef = function (array, offset, result) {
  402. result.x = array[offset];
  403. result.y = array[offset + 1];
  404. };
  405. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  406. var squared = amount * amount;
  407. var cubed = amount * squared;
  408. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  409. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  410. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  411. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  412. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  413. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  414. return new Vector2(x, y);
  415. };
  416. Vector2.Clamp = function (value, min, max) {
  417. var x = value.x;
  418. x = (x > max.x) ? max.x : x;
  419. x = (x < min.x) ? min.x : x;
  420. var y = value.y;
  421. y = (y > max.y) ? max.y : y;
  422. y = (y < min.y) ? min.y : y;
  423. return new Vector2(x, y);
  424. };
  425. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  426. var squared = amount * amount;
  427. var cubed = amount * squared;
  428. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  429. var part2 = (-2.0 * cubed) + (3.0 * squared);
  430. var part3 = (cubed - (2.0 * squared)) + amount;
  431. var part4 = cubed - squared;
  432. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  433. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  434. return new Vector2(x, y);
  435. };
  436. Vector2.Lerp = function (start, end, amount) {
  437. var x = start.x + ((end.x - start.x) * amount);
  438. var y = start.y + ((end.y - start.y) * amount);
  439. return new Vector2(x, y);
  440. };
  441. Vector2.Dot = function (left, right) {
  442. return left.x * right.x + left.y * right.y;
  443. };
  444. Vector2.Normalize = function (vector) {
  445. var newVector = vector.clone();
  446. newVector.normalize();
  447. return newVector;
  448. };
  449. Vector2.Minimize = function (left, right) {
  450. var x = (left.x < right.x) ? left.x : right.x;
  451. var y = (left.y < right.y) ? left.y : right.y;
  452. return new Vector2(x, y);
  453. };
  454. Vector2.Maximize = function (left, right) {
  455. var x = (left.x > right.x) ? left.x : right.x;
  456. var y = (left.y > right.y) ? left.y : right.y;
  457. return new Vector2(x, y);
  458. };
  459. Vector2.Transform = function (vector, transformation) {
  460. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  461. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  462. return new Vector2(x, y);
  463. };
  464. Vector2.Distance = function (value1, value2) {
  465. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  466. };
  467. Vector2.DistanceSquared = function (value1, value2) {
  468. var x = value1.x - value2.x;
  469. var y = value1.y - value2.y;
  470. return (x * x) + (y * y);
  471. };
  472. return Vector2;
  473. })();
  474. BABYLON.Vector2 = Vector2;
  475. var Vector3 = (function () {
  476. function Vector3(x, y, z) {
  477. this.x = x;
  478. this.y = y;
  479. this.z = z;
  480. }
  481. Vector3.prototype.toString = function () {
  482. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  483. };
  484. // Operators
  485. Vector3.prototype.asArray = function () {
  486. var result = [];
  487. this.toArray(result, 0);
  488. return result;
  489. };
  490. Vector3.prototype.toArray = function (array, index) {
  491. if (index === void 0) { index = 0; }
  492. array[index] = this.x;
  493. array[index + 1] = this.y;
  494. array[index + 2] = this.z;
  495. return this;
  496. };
  497. Vector3.prototype.toQuaternion = function () {
  498. var result = new Quaternion(0, 0, 0, 1);
  499. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  500. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  501. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  502. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  503. var cosy = Math.cos(this.y * 0.5);
  504. var siny = Math.sin(this.y * 0.5);
  505. result.x = coszMinusx * siny;
  506. result.y = -sinzMinusx * siny;
  507. result.z = sinxPlusz * cosy;
  508. result.w = cosxPlusz * cosy;
  509. return result;
  510. };
  511. Vector3.prototype.addInPlace = function (otherVector) {
  512. this.x += otherVector.x;
  513. this.y += otherVector.y;
  514. this.z += otherVector.z;
  515. return this;
  516. };
  517. Vector3.prototype.add = function (otherVector) {
  518. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  519. };
  520. Vector3.prototype.addToRef = function (otherVector, result) {
  521. result.x = this.x + otherVector.x;
  522. result.y = this.y + otherVector.y;
  523. result.z = this.z + otherVector.z;
  524. return this;
  525. };
  526. Vector3.prototype.subtractInPlace = function (otherVector) {
  527. this.x -= otherVector.x;
  528. this.y -= otherVector.y;
  529. this.z -= otherVector.z;
  530. return this;
  531. };
  532. Vector3.prototype.subtract = function (otherVector) {
  533. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  534. };
  535. Vector3.prototype.subtractToRef = function (otherVector, result) {
  536. result.x = this.x - otherVector.x;
  537. result.y = this.y - otherVector.y;
  538. result.z = this.z - otherVector.z;
  539. return this;
  540. };
  541. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  542. return new Vector3(this.x - x, this.y - y, this.z - z);
  543. };
  544. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  545. result.x = this.x - x;
  546. result.y = this.y - y;
  547. result.z = this.z - z;
  548. return this;
  549. };
  550. Vector3.prototype.negate = function () {
  551. return new Vector3(-this.x, -this.y, -this.z);
  552. };
  553. Vector3.prototype.scaleInPlace = function (scale) {
  554. this.x *= scale;
  555. this.y *= scale;
  556. this.z *= scale;
  557. return this;
  558. };
  559. Vector3.prototype.scale = function (scale) {
  560. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  561. };
  562. Vector3.prototype.scaleToRef = function (scale, result) {
  563. result.x = this.x * scale;
  564. result.y = this.y * scale;
  565. result.z = this.z * scale;
  566. };
  567. Vector3.prototype.equals = function (otherVector) {
  568. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  569. };
  570. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  571. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  572. return otherVector && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Tools.WithinEpsilon(this.z, otherVector.z, epsilon);
  573. };
  574. Vector3.prototype.equalsToFloats = function (x, y, z) {
  575. return this.x === x && this.y === y && this.z === z;
  576. };
  577. Vector3.prototype.multiplyInPlace = function (otherVector) {
  578. this.x *= otherVector.x;
  579. this.y *= otherVector.y;
  580. this.z *= otherVector.z;
  581. return this;
  582. };
  583. Vector3.prototype.multiply = function (otherVector) {
  584. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  585. };
  586. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  587. result.x = this.x * otherVector.x;
  588. result.y = this.y * otherVector.y;
  589. result.z = this.z * otherVector.z;
  590. return this;
  591. };
  592. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  593. return new Vector3(this.x * x, this.y * y, this.z * z);
  594. };
  595. Vector3.prototype.divide = function (otherVector) {
  596. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  597. };
  598. Vector3.prototype.divideToRef = function (otherVector, result) {
  599. result.x = this.x / otherVector.x;
  600. result.y = this.y / otherVector.y;
  601. result.z = this.z / otherVector.z;
  602. return this;
  603. };
  604. Vector3.prototype.MinimizeInPlace = function (other) {
  605. if (other.x < this.x)
  606. this.x = other.x;
  607. if (other.y < this.y)
  608. this.y = other.y;
  609. if (other.z < this.z)
  610. this.z = other.z;
  611. return this;
  612. };
  613. Vector3.prototype.MaximizeInPlace = function (other) {
  614. if (other.x > this.x)
  615. this.x = other.x;
  616. if (other.y > this.y)
  617. this.y = other.y;
  618. if (other.z > this.z)
  619. this.z = other.z;
  620. return this;
  621. };
  622. // Properties
  623. Vector3.prototype.length = function () {
  624. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  625. };
  626. Vector3.prototype.lengthSquared = function () {
  627. return (this.x * this.x + this.y * this.y + this.z * this.z);
  628. };
  629. // Methods
  630. Vector3.prototype.normalize = function () {
  631. var len = this.length();
  632. if (len === 0 || len === 1.0)
  633. return this;
  634. var num = 1.0 / len;
  635. this.x *= num;
  636. this.y *= num;
  637. this.z *= num;
  638. return this;
  639. };
  640. Vector3.prototype.clone = function () {
  641. return new Vector3(this.x, this.y, this.z);
  642. };
  643. Vector3.prototype.copyFrom = function (source) {
  644. this.x = source.x;
  645. this.y = source.y;
  646. this.z = source.z;
  647. return this;
  648. };
  649. Vector3.prototype.copyFromFloats = function (x, y, z) {
  650. this.x = x;
  651. this.y = y;
  652. this.z = z;
  653. return this;
  654. };
  655. // Statics
  656. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  657. var d0 = Vector3.Dot(vector0, axis) - size;
  658. var d1 = Vector3.Dot(vector1, axis) - size;
  659. var s = d0 / (d0 - d1);
  660. return s;
  661. };
  662. Vector3.FromArray = function (array, offset) {
  663. if (!offset) {
  664. offset = 0;
  665. }
  666. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  667. };
  668. Vector3.FromFloatArray = function (array, offset) {
  669. if (!offset) {
  670. offset = 0;
  671. }
  672. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  673. };
  674. Vector3.FromArrayToRef = function (array, offset, result) {
  675. result.x = array[offset];
  676. result.y = array[offset + 1];
  677. result.z = array[offset + 2];
  678. };
  679. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  680. result.x = array[offset];
  681. result.y = array[offset + 1];
  682. result.z = array[offset + 2];
  683. };
  684. Vector3.FromFloatsToRef = function (x, y, z, result) {
  685. result.x = x;
  686. result.y = y;
  687. result.z = z;
  688. };
  689. Vector3.Zero = function () {
  690. return new Vector3(0, 0, 0);
  691. };
  692. Vector3.Up = function () {
  693. return new Vector3(0, 1.0, 0);
  694. };
  695. Vector3.TransformCoordinates = function (vector, transformation) {
  696. var result = Vector3.Zero();
  697. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  698. return result;
  699. };
  700. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  701. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  702. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  703. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  704. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  705. result.x = x / w;
  706. result.y = y / w;
  707. result.z = z / w;
  708. };
  709. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  710. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  711. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  712. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  713. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  714. result.x = rx / rw;
  715. result.y = ry / rw;
  716. result.z = rz / rw;
  717. };
  718. Vector3.TransformNormal = function (vector, transformation) {
  719. var result = Vector3.Zero();
  720. Vector3.TransformNormalToRef(vector, transformation, result);
  721. return result;
  722. };
  723. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  724. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  725. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  726. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  727. };
  728. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  729. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  730. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  731. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  732. };
  733. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  734. var squared = amount * amount;
  735. var cubed = amount * squared;
  736. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  737. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  738. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  739. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  740. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  741. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  742. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  743. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  744. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  745. return new Vector3(x, y, z);
  746. };
  747. Vector3.Clamp = function (value, min, max) {
  748. var x = value.x;
  749. x = (x > max.x) ? max.x : x;
  750. x = (x < min.x) ? min.x : x;
  751. var y = value.y;
  752. y = (y > max.y) ? max.y : y;
  753. y = (y < min.y) ? min.y : y;
  754. var z = value.z;
  755. z = (z > max.z) ? max.z : z;
  756. z = (z < min.z) ? min.z : z;
  757. return new Vector3(x, y, z);
  758. };
  759. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  760. var squared = amount * amount;
  761. var cubed = amount * squared;
  762. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  763. var part2 = (-2.0 * cubed) + (3.0 * squared);
  764. var part3 = (cubed - (2.0 * squared)) + amount;
  765. var part4 = cubed - squared;
  766. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  767. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  768. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  769. return new Vector3(x, y, z);
  770. };
  771. Vector3.Lerp = function (start, end, amount) {
  772. var x = start.x + ((end.x - start.x) * amount);
  773. var y = start.y + ((end.y - start.y) * amount);
  774. var z = start.z + ((end.z - start.z) * amount);
  775. return new Vector3(x, y, z);
  776. };
  777. Vector3.Dot = function (left, right) {
  778. return (left.x * right.x + left.y * right.y + left.z * right.z);
  779. };
  780. Vector3.Cross = function (left, right) {
  781. var result = Vector3.Zero();
  782. Vector3.CrossToRef(left, right, result);
  783. return result;
  784. };
  785. Vector3.CrossToRef = function (left, right, result) {
  786. result.x = left.y * right.z - left.z * right.y;
  787. result.y = left.z * right.x - left.x * right.z;
  788. result.z = left.x * right.y - left.y * right.x;
  789. };
  790. Vector3.Normalize = function (vector) {
  791. var result = Vector3.Zero();
  792. Vector3.NormalizeToRef(vector, result);
  793. return result;
  794. };
  795. Vector3.NormalizeToRef = function (vector, result) {
  796. result.copyFrom(vector);
  797. result.normalize();
  798. };
  799. Vector3.Project = function (vector, world, transform, viewport) {
  800. var cw = viewport.width;
  801. var ch = viewport.height;
  802. var cx = viewport.x;
  803. var cy = viewport.y;
  804. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 1, 0, cx + cw / 2.0, ch / 2.0 + cy, 0, 1);
  805. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  806. return Vector3.TransformCoordinates(vector, finalMatrix);
  807. };
  808. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  809. var matrix = world.multiply(transform);
  810. matrix.invert();
  811. source.x = source.x / viewportWidth * 2 - 1;
  812. source.y = -(source.y / viewportHeight * 2 - 1);
  813. var vector = Vector3.TransformCoordinates(source, matrix);
  814. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  815. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  816. vector = vector.scale(1.0 / num);
  817. }
  818. return vector;
  819. };
  820. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  821. var matrix = world.multiply(view).multiply(projection);
  822. matrix.invert();
  823. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), source.z);
  824. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  825. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  826. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  827. vector = vector.scale(1.0 / num);
  828. }
  829. return vector;
  830. };
  831. Vector3.Minimize = function (left, right) {
  832. var min = left.clone();
  833. min.MinimizeInPlace(right);
  834. return min;
  835. };
  836. Vector3.Maximize = function (left, right) {
  837. var max = left.clone();
  838. max.MaximizeInPlace(right);
  839. return max;
  840. };
  841. Vector3.Distance = function (value1, value2) {
  842. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  843. };
  844. Vector3.DistanceSquared = function (value1, value2) {
  845. var x = value1.x - value2.x;
  846. var y = value1.y - value2.y;
  847. var z = value1.z - value2.z;
  848. return (x * x) + (y * y) + (z * z);
  849. };
  850. Vector3.Center = function (value1, value2) {
  851. var center = value1.add(value2);
  852. center.scaleInPlace(0.5);
  853. return center;
  854. };
  855. /**
  856. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  857. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  858. * to something in order to rotate it from its local system to the given target system.
  859. */
  860. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  861. var rotation = Vector3.Zero();
  862. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  863. return rotation;
  864. };
  865. /**
  866. * The same than RotationFromAxis but updates the passed ref Vector3 parameter.
  867. */
  868. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  869. var u = axis1.normalize();
  870. var w = axis3.normalize();
  871. // world axis
  872. var X = Axis.X;
  873. var Y = Axis.Y;
  874. // equation unknowns and vars
  875. var yaw = 0.0;
  876. var pitch = 0.0;
  877. var roll = 0.0;
  878. var x = 0.0;
  879. var y = 0.0;
  880. var z = 0.0;
  881. var t = 0.0;
  882. var sign = -1.0;
  883. var nbRevert = 0;
  884. var cross = Tmp.Vector3[0];
  885. var dot = 0.0;
  886. // step 1 : rotation around w
  887. // Rv3(u) = u1, and u1 belongs to plane xOz
  888. // Rv3(w) = w1 = w invariant
  889. var u1 = Tmp.Vector3[1];
  890. if (BABYLON.Tools.WithinEpsilon(w.z, 0, BABYLON.Engine.Epsilon)) {
  891. z = 1.0;
  892. }
  893. else if (BABYLON.Tools.WithinEpsilon(w.x, 0, BABYLON.Engine.Epsilon)) {
  894. x = 1.0;
  895. }
  896. else {
  897. t = w.z / w.x;
  898. x = -t * Math.sqrt(1 / (1 + t * t));
  899. z = Math.sqrt(1 / (1 + t * t));
  900. }
  901. u1.x = x;
  902. u1.y = y;
  903. u1.z = z;
  904. u1.normalize();
  905. Vector3.CrossToRef(u, u1, cross); // returns same direction as w (=local z) if positive angle : cross(source, image)
  906. cross.normalize();
  907. if (Vector3.Dot(w, cross) < 0) {
  908. sign = 1.0;
  909. }
  910. dot = Vector3.Dot(u, u1);
  911. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  912. roll = Math.acos(dot) * sign;
  913. if (Vector3.Dot(u1, X) < 0) {
  914. roll = Math.PI + roll;
  915. u1 = u1.scaleInPlace(-1);
  916. nbRevert++;
  917. }
  918. // step 2 : rotate around u1
  919. // Ru1(w1) = Ru1(w) = w2, and w2 belongs to plane xOz
  920. // u1 is yet in xOz and invariant by Ru1, so after this step u1 and w2 will be in xOz
  921. var w2 = Tmp.Vector3[2];
  922. var v2 = Tmp.Vector3[3];
  923. x = 0.0;
  924. y = 0.0;
  925. z = 0.0;
  926. sign = -1.0;
  927. if (BABYLON.Tools.WithinEpsilon(w.z, 0, BABYLON.Engine.Epsilon)) {
  928. x = 1.0;
  929. }
  930. else {
  931. t = u1.z / u1.x;
  932. x = -t * Math.sqrt(1 / (1 + t * t));
  933. z = Math.sqrt(1 / (1 + t * t));
  934. }
  935. w2.x = x;
  936. w2.y = y;
  937. w2.z = z;
  938. w2.normalize();
  939. Vector3.CrossToRef(w2, u1, v2); // v2 image of v1 through rotation around u1
  940. v2.normalize();
  941. Vector3.CrossToRef(w, w2, cross); // returns same direction as u1 (=local x) if positive angle : cross(source, image)
  942. cross.normalize();
  943. if (Vector3.Dot(u1, cross) < 0) {
  944. sign = 1.0;
  945. }
  946. dot = Vector3.Dot(w, w2);
  947. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  948. pitch = Math.acos(dot) * sign;
  949. if (Vector3.Dot(v2, Y) < 0) {
  950. pitch = Math.PI + pitch;
  951. nbRevert++;
  952. }
  953. // step 3 : rotate around v2
  954. // Rv2(u1) = X, same as Rv2(w2) = Z, with X=(1,0,0) and Z=(0,0,1)
  955. sign = -1.0;
  956. Vector3.CrossToRef(X, u1, cross); // returns same direction as Y if positive angle : cross(source, image)
  957. cross.normalize();
  958. if (Vector3.Dot(cross, Y) < 0) {
  959. sign = 1.0;
  960. }
  961. dot = Vector3.Dot(u1, X);
  962. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  963. yaw = -Math.acos(dot) * sign; // negative : plane zOx oriented clockwise
  964. if (dot < 0 && nbRevert < 2) {
  965. yaw = Math.PI + yaw;
  966. }
  967. ref.x = pitch;
  968. ref.y = yaw;
  969. ref.z = roll;
  970. };
  971. return Vector3;
  972. })();
  973. BABYLON.Vector3 = Vector3;
  974. //Vector4 class created for EulerAngle class conversion to Quaternion
  975. var Vector4 = (function () {
  976. function Vector4(x, y, z, w) {
  977. this.x = x;
  978. this.y = y;
  979. this.z = z;
  980. this.w = w;
  981. }
  982. Vector4.prototype.toString = function () {
  983. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  984. };
  985. // Operators
  986. Vector4.prototype.asArray = function () {
  987. var result = [];
  988. this.toArray(result, 0);
  989. return result;
  990. };
  991. Vector4.prototype.toArray = function (array, index) {
  992. if (index === undefined) {
  993. index = 0;
  994. }
  995. array[index] = this.x;
  996. array[index + 1] = this.y;
  997. array[index + 2] = this.z;
  998. array[index + 3] = this.w;
  999. return this;
  1000. };
  1001. Vector4.prototype.addInPlace = function (otherVector) {
  1002. this.x += otherVector.x;
  1003. this.y += otherVector.y;
  1004. this.z += otherVector.z;
  1005. this.w += otherVector.w;
  1006. return this;
  1007. };
  1008. Vector4.prototype.add = function (otherVector) {
  1009. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1010. };
  1011. Vector4.prototype.addToRef = function (otherVector, result) {
  1012. result.x = this.x + otherVector.x;
  1013. result.y = this.y + otherVector.y;
  1014. result.z = this.z + otherVector.z;
  1015. result.w = this.w + otherVector.w;
  1016. return this;
  1017. };
  1018. Vector4.prototype.subtractInPlace = function (otherVector) {
  1019. this.x -= otherVector.x;
  1020. this.y -= otherVector.y;
  1021. this.z -= otherVector.z;
  1022. this.w -= otherVector.w;
  1023. return this;
  1024. };
  1025. Vector4.prototype.subtract = function (otherVector) {
  1026. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1027. };
  1028. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1029. result.x = this.x - otherVector.x;
  1030. result.y = this.y - otherVector.y;
  1031. result.z = this.z - otherVector.z;
  1032. result.w = this.w - otherVector.w;
  1033. return this;
  1034. };
  1035. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1036. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1037. };
  1038. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1039. result.x = this.x - x;
  1040. result.y = this.y - y;
  1041. result.z = this.z - z;
  1042. result.w = this.w - w;
  1043. return this;
  1044. };
  1045. Vector4.prototype.negate = function () {
  1046. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1047. };
  1048. Vector4.prototype.scaleInPlace = function (scale) {
  1049. this.x *= scale;
  1050. this.y *= scale;
  1051. this.z *= scale;
  1052. this.w *= scale;
  1053. return this;
  1054. };
  1055. Vector4.prototype.scale = function (scale) {
  1056. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1057. };
  1058. Vector4.prototype.scaleToRef = function (scale, result) {
  1059. result.x = this.x * scale;
  1060. result.y = this.y * scale;
  1061. result.z = this.z * scale;
  1062. result.w = this.w * scale;
  1063. };
  1064. Vector4.prototype.equals = function (otherVector) {
  1065. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1066. };
  1067. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1068. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  1069. return otherVector
  1070. && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1071. && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1072. && BABYLON.Tools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1073. && BABYLON.Tools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1074. };
  1075. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1076. return this.x === x && this.y === y && this.z === z && this.w === w;
  1077. };
  1078. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1079. this.x *= otherVector.x;
  1080. this.y *= otherVector.y;
  1081. this.z *= otherVector.z;
  1082. this.w *= otherVector.w;
  1083. return this;
  1084. };
  1085. Vector4.prototype.multiply = function (otherVector) {
  1086. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1087. };
  1088. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1089. result.x = this.x * otherVector.x;
  1090. result.y = this.y * otherVector.y;
  1091. result.z = this.z * otherVector.z;
  1092. result.w = this.w * otherVector.w;
  1093. return this;
  1094. };
  1095. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1096. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1097. };
  1098. Vector4.prototype.divide = function (otherVector) {
  1099. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1100. };
  1101. Vector4.prototype.divideToRef = function (otherVector, result) {
  1102. result.x = this.x / otherVector.x;
  1103. result.y = this.y / otherVector.y;
  1104. result.z = this.z / otherVector.z;
  1105. result.w = this.w / otherVector.w;
  1106. return this;
  1107. };
  1108. Vector4.prototype.MinimizeInPlace = function (other) {
  1109. if (other.x < this.x)
  1110. this.x = other.x;
  1111. if (other.y < this.y)
  1112. this.y = other.y;
  1113. if (other.z < this.z)
  1114. this.z = other.z;
  1115. if (other.w < this.w)
  1116. this.w = other.w;
  1117. return this;
  1118. };
  1119. Vector4.prototype.MaximizeInPlace = function (other) {
  1120. if (other.x > this.x)
  1121. this.x = other.x;
  1122. if (other.y > this.y)
  1123. this.y = other.y;
  1124. if (other.z > this.z)
  1125. this.z = other.z;
  1126. if (other.w > this.w)
  1127. this.w = other.w;
  1128. return this;
  1129. };
  1130. // Properties
  1131. Vector4.prototype.length = function () {
  1132. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1133. };
  1134. Vector4.prototype.lengthSquared = function () {
  1135. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1136. };
  1137. // Methods
  1138. Vector4.prototype.normalize = function () {
  1139. var len = this.length();
  1140. if (len === 0)
  1141. return this;
  1142. var num = 1.0 / len;
  1143. this.x *= num;
  1144. this.y *= num;
  1145. this.z *= num;
  1146. this.w *= num;
  1147. return this;
  1148. };
  1149. Vector4.prototype.clone = function () {
  1150. return new Vector4(this.x, this.y, this.z, this.w);
  1151. };
  1152. Vector4.prototype.copyFrom = function (source) {
  1153. this.x = source.x;
  1154. this.y = source.y;
  1155. this.z = source.z;
  1156. this.w = source.w;
  1157. return this;
  1158. };
  1159. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1160. this.x = x;
  1161. this.y = y;
  1162. this.z = z;
  1163. this.w = w;
  1164. return this;
  1165. };
  1166. // Statics
  1167. Vector4.FromArray = function (array, offset) {
  1168. if (!offset) {
  1169. offset = 0;
  1170. }
  1171. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1172. };
  1173. Vector4.FromArrayToRef = function (array, offset, result) {
  1174. result.x = array[offset];
  1175. result.y = array[offset + 1];
  1176. result.z = array[offset + 2];
  1177. result.w = array[offset + 3];
  1178. };
  1179. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1180. result.x = array[offset];
  1181. result.y = array[offset + 1];
  1182. result.z = array[offset + 2];
  1183. result.w = array[offset + 3];
  1184. };
  1185. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1186. result.x = x;
  1187. result.y = y;
  1188. result.z = z;
  1189. result.w = w;
  1190. };
  1191. Vector4.Zero = function () {
  1192. return new Vector4(0, 0, 0, 0);
  1193. };
  1194. Vector4.Normalize = function (vector) {
  1195. var result = Vector4.Zero();
  1196. Vector4.NormalizeToRef(vector, result);
  1197. return result;
  1198. };
  1199. Vector4.NormalizeToRef = function (vector, result) {
  1200. result.copyFrom(vector);
  1201. result.normalize();
  1202. };
  1203. Vector4.Minimize = function (left, right) {
  1204. var min = left.clone();
  1205. min.MinimizeInPlace(right);
  1206. return min;
  1207. };
  1208. Vector4.Maximize = function (left, right) {
  1209. var max = left.clone();
  1210. max.MaximizeInPlace(right);
  1211. return max;
  1212. };
  1213. Vector4.Distance = function (value1, value2) {
  1214. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1215. };
  1216. Vector4.DistanceSquared = function (value1, value2) {
  1217. var x = value1.x - value2.x;
  1218. var y = value1.y - value2.y;
  1219. var z = value1.z - value2.z;
  1220. var w = value1.w - value2.w;
  1221. return (x * x) + (y * y) + (z * z) + (w * w);
  1222. };
  1223. Vector4.Center = function (value1, value2) {
  1224. var center = value1.add(value2);
  1225. center.scaleInPlace(0.5);
  1226. return center;
  1227. };
  1228. return Vector4;
  1229. })();
  1230. BABYLON.Vector4 = Vector4;
  1231. var Quaternion = (function () {
  1232. function Quaternion(x, y, z, w) {
  1233. if (x === void 0) { x = 0; }
  1234. if (y === void 0) { y = 0; }
  1235. if (z === void 0) { z = 0; }
  1236. if (w === void 0) { w = 1; }
  1237. this.x = x;
  1238. this.y = y;
  1239. this.z = z;
  1240. this.w = w;
  1241. }
  1242. Quaternion.prototype.toString = function () {
  1243. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1244. };
  1245. Quaternion.prototype.asArray = function () {
  1246. return [this.x, this.y, this.z, this.w];
  1247. };
  1248. Quaternion.prototype.equals = function (otherQuaternion) {
  1249. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1250. };
  1251. Quaternion.prototype.clone = function () {
  1252. return new Quaternion(this.x, this.y, this.z, this.w);
  1253. };
  1254. Quaternion.prototype.copyFrom = function (other) {
  1255. this.x = other.x;
  1256. this.y = other.y;
  1257. this.z = other.z;
  1258. this.w = other.w;
  1259. return this;
  1260. };
  1261. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1262. this.x = x;
  1263. this.y = y;
  1264. this.z = z;
  1265. this.w = w;
  1266. return this;
  1267. };
  1268. Quaternion.prototype.add = function (other) {
  1269. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1270. };
  1271. Quaternion.prototype.subtract = function (other) {
  1272. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1273. };
  1274. Quaternion.prototype.scale = function (value) {
  1275. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1276. };
  1277. Quaternion.prototype.multiply = function (q1) {
  1278. var result = new Quaternion(0, 0, 0, 1.0);
  1279. this.multiplyToRef(q1, result);
  1280. return result;
  1281. };
  1282. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1283. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1284. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1285. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1286. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1287. result.copyFromFloats(x, y, z, w);
  1288. return this;
  1289. };
  1290. Quaternion.prototype.multiplyInPlace = function (q1) {
  1291. this.multiplyToRef(q1, this);
  1292. return this;
  1293. };
  1294. Quaternion.prototype.length = function () {
  1295. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1296. };
  1297. Quaternion.prototype.normalize = function () {
  1298. var length = 1.0 / this.length();
  1299. this.x *= length;
  1300. this.y *= length;
  1301. this.z *= length;
  1302. this.w *= length;
  1303. return this;
  1304. };
  1305. Quaternion.prototype.toEulerAngles = function (order) {
  1306. if (order === void 0) { order = "YZX"; }
  1307. var result = Vector3.Zero();
  1308. this.toEulerAnglesToRef(result, order);
  1309. return result;
  1310. };
  1311. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  1312. if (order === void 0) { order = "YZX"; }
  1313. var heading, attitude, bank;
  1314. var x = this.x, y = this.y, z = this.z, w = this.w;
  1315. switch (order) {
  1316. case "YZX":
  1317. var test = x * y + z * w;
  1318. if (test > 0.499) {
  1319. heading = 2 * Math.atan2(x, w);
  1320. attitude = Math.PI / 2;
  1321. bank = 0;
  1322. }
  1323. if (test < -0.499) {
  1324. heading = -2 * Math.atan2(x, w);
  1325. attitude = -Math.PI / 2;
  1326. bank = 0;
  1327. }
  1328. if (isNaN(heading)) {
  1329. var sqx = x * x;
  1330. var sqy = y * y;
  1331. var sqz = z * z;
  1332. heading = Math.atan2(2 * y * w - 2 * x * z, 1 - 2 * sqy - 2 * sqz); // Heading
  1333. attitude = Math.asin(2 * test); // attitude
  1334. bank = Math.atan2(2 * x * w - 2 * y * z, 1 - 2 * sqx - 2 * sqz); // bank
  1335. }
  1336. break;
  1337. default:
  1338. throw new Error("Euler order " + order + " not supported yet.");
  1339. }
  1340. result.y = heading;
  1341. result.z = attitude;
  1342. result.x = bank;
  1343. return this;
  1344. };
  1345. ;
  1346. Quaternion.prototype.toRotationMatrix = function (result) {
  1347. var xx = this.x * this.x;
  1348. var yy = this.y * this.y;
  1349. var zz = this.z * this.z;
  1350. var xy = this.x * this.y;
  1351. var zw = this.z * this.w;
  1352. var zx = this.z * this.x;
  1353. var yw = this.y * this.w;
  1354. var yz = this.y * this.z;
  1355. var xw = this.x * this.w;
  1356. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1357. result.m[1] = 2.0 * (xy + zw);
  1358. result.m[2] = 2.0 * (zx - yw);
  1359. result.m[3] = 0;
  1360. result.m[4] = 2.0 * (xy - zw);
  1361. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1362. result.m[6] = 2.0 * (yz + xw);
  1363. result.m[7] = 0;
  1364. result.m[8] = 2.0 * (zx + yw);
  1365. result.m[9] = 2.0 * (yz - xw);
  1366. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1367. result.m[11] = 0;
  1368. result.m[12] = 0;
  1369. result.m[13] = 0;
  1370. result.m[14] = 0;
  1371. result.m[15] = 1.0;
  1372. return this;
  1373. };
  1374. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1375. Quaternion.FromRotationMatrixToRef(matrix, this);
  1376. return this;
  1377. };
  1378. // Statics
  1379. Quaternion.FromRotationMatrix = function (matrix) {
  1380. var result = new Quaternion();
  1381. Quaternion.FromRotationMatrixToRef(matrix, result);
  1382. return result;
  1383. };
  1384. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1385. var data = matrix.m;
  1386. var m11 = data[0], m12 = data[4], m13 = data[8];
  1387. var m21 = data[1], m22 = data[5], m23 = data[9];
  1388. var m31 = data[2], m32 = data[6], m33 = data[10];
  1389. var trace = m11 + m22 + m33;
  1390. var s;
  1391. if (trace > 0) {
  1392. s = 0.5 / Math.sqrt(trace + 1.0);
  1393. result.w = 0.25 / s;
  1394. result.x = (m32 - m23) * s;
  1395. result.y = (m13 - m31) * s;
  1396. result.z = (m21 - m12) * s;
  1397. }
  1398. else if (m11 > m22 && m11 > m33) {
  1399. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1400. result.w = (m32 - m23) / s;
  1401. result.x = 0.25 * s;
  1402. result.y = (m12 + m21) / s;
  1403. result.z = (m13 + m31) / s;
  1404. }
  1405. else if (m22 > m33) {
  1406. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1407. result.w = (m13 - m31) / s;
  1408. result.x = (m12 + m21) / s;
  1409. result.y = 0.25 * s;
  1410. result.z = (m23 + m32) / s;
  1411. }
  1412. else {
  1413. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1414. result.w = (m21 - m12) / s;
  1415. result.x = (m13 + m31) / s;
  1416. result.y = (m23 + m32) / s;
  1417. result.z = 0.25 * s;
  1418. }
  1419. };
  1420. Quaternion.Inverse = function (q) {
  1421. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1422. };
  1423. Quaternion.Identity = function () {
  1424. return new Quaternion(0, 0, 0, 1);
  1425. };
  1426. Quaternion.RotationAxis = function (axis, angle) {
  1427. var result = new Quaternion();
  1428. var sin = Math.sin(angle / 2);
  1429. axis.normalize();
  1430. result.w = Math.cos(angle / 2);
  1431. result.x = axis.x * sin;
  1432. result.y = axis.y * sin;
  1433. result.z = axis.z * sin;
  1434. return result;
  1435. };
  1436. Quaternion.FromArray = function (array, offset) {
  1437. if (!offset) {
  1438. offset = 0;
  1439. }
  1440. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1441. };
  1442. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1443. var result = new Quaternion();
  1444. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1445. return result;
  1446. };
  1447. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1448. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1449. var halfRoll = roll * 0.5;
  1450. var halfPitch = pitch * 0.5;
  1451. var halfYaw = yaw * 0.5;
  1452. var sinRoll = Math.sin(halfRoll);
  1453. var cosRoll = Math.cos(halfRoll);
  1454. var sinPitch = Math.sin(halfPitch);
  1455. var cosPitch = Math.cos(halfPitch);
  1456. var sinYaw = Math.sin(halfYaw);
  1457. var cosYaw = Math.cos(halfYaw);
  1458. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1459. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1460. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1461. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1462. };
  1463. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1464. var result = new Quaternion();
  1465. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1466. return result;
  1467. };
  1468. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1469. // Produces a quaternion from Euler angles in the z-x-z orientation
  1470. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1471. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1472. var halfBeta = beta * 0.5;
  1473. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1474. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1475. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1476. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1477. };
  1478. Quaternion.Slerp = function (left, right, amount) {
  1479. var num2;
  1480. var num3;
  1481. var num = amount;
  1482. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1483. var flag = false;
  1484. if (num4 < 0) {
  1485. flag = true;
  1486. num4 = -num4;
  1487. }
  1488. if (num4 > 0.999999) {
  1489. num3 = 1 - num;
  1490. num2 = flag ? -num : num;
  1491. }
  1492. else {
  1493. var num5 = Math.acos(num4);
  1494. var num6 = (1.0 / Math.sin(num5));
  1495. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1496. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1497. }
  1498. return new Quaternion((num3 * left.x) + (num2 * right.x), (num3 * left.y) + (num2 * right.y), (num3 * left.z) + (num2 * right.z), (num3 * left.w) + (num2 * right.w));
  1499. };
  1500. return Quaternion;
  1501. })();
  1502. BABYLON.Quaternion = Quaternion;
  1503. var Matrix = (function () {
  1504. function Matrix() {
  1505. this.m = new Float32Array(16);
  1506. }
  1507. // Properties
  1508. Matrix.prototype.isIdentity = function () {
  1509. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1510. return false;
  1511. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  1512. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  1513. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  1514. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1515. return false;
  1516. return true;
  1517. };
  1518. Matrix.prototype.determinant = function () {
  1519. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1520. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1521. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1522. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1523. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1524. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1525. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  1526. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  1527. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1528. };
  1529. // Methods
  1530. Matrix.prototype.toArray = function () {
  1531. return this.m;
  1532. };
  1533. Matrix.prototype.asArray = function () {
  1534. return this.toArray();
  1535. };
  1536. Matrix.prototype.invert = function () {
  1537. this.invertToRef(this);
  1538. return this;
  1539. };
  1540. Matrix.prototype.reset = function () {
  1541. for (var index = 0; index < 16; index++) {
  1542. this.m[index] = 0;
  1543. }
  1544. return this;
  1545. };
  1546. Matrix.prototype.add = function (other) {
  1547. var result = new Matrix();
  1548. this.addToRef(other, result);
  1549. return result;
  1550. };
  1551. Matrix.prototype.addToRef = function (other, result) {
  1552. for (var index = 0; index < 16; index++) {
  1553. result.m[index] = this.m[index] + other.m[index];
  1554. }
  1555. return this;
  1556. };
  1557. Matrix.prototype.addToSelf = function (other) {
  1558. for (var index = 0; index < 16; index++) {
  1559. this.m[index] += other.m[index];
  1560. }
  1561. return this;
  1562. };
  1563. Matrix.prototype.invertToRef = function (other) {
  1564. var l1 = this.m[0];
  1565. var l2 = this.m[1];
  1566. var l3 = this.m[2];
  1567. var l4 = this.m[3];
  1568. var l5 = this.m[4];
  1569. var l6 = this.m[5];
  1570. var l7 = this.m[6];
  1571. var l8 = this.m[7];
  1572. var l9 = this.m[8];
  1573. var l10 = this.m[9];
  1574. var l11 = this.m[10];
  1575. var l12 = this.m[11];
  1576. var l13 = this.m[12];
  1577. var l14 = this.m[13];
  1578. var l15 = this.m[14];
  1579. var l16 = this.m[15];
  1580. var l17 = (l11 * l16) - (l12 * l15);
  1581. var l18 = (l10 * l16) - (l12 * l14);
  1582. var l19 = (l10 * l15) - (l11 * l14);
  1583. var l20 = (l9 * l16) - (l12 * l13);
  1584. var l21 = (l9 * l15) - (l11 * l13);
  1585. var l22 = (l9 * l14) - (l10 * l13);
  1586. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1587. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1588. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1589. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1590. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1591. var l28 = (l7 * l16) - (l8 * l15);
  1592. var l29 = (l6 * l16) - (l8 * l14);
  1593. var l30 = (l6 * l15) - (l7 * l14);
  1594. var l31 = (l5 * l16) - (l8 * l13);
  1595. var l32 = (l5 * l15) - (l7 * l13);
  1596. var l33 = (l5 * l14) - (l6 * l13);
  1597. var l34 = (l7 * l12) - (l8 * l11);
  1598. var l35 = (l6 * l12) - (l8 * l10);
  1599. var l36 = (l6 * l11) - (l7 * l10);
  1600. var l37 = (l5 * l12) - (l8 * l9);
  1601. var l38 = (l5 * l11) - (l7 * l9);
  1602. var l39 = (l5 * l10) - (l6 * l9);
  1603. other.m[0] = l23 * l27;
  1604. other.m[4] = l24 * l27;
  1605. other.m[8] = l25 * l27;
  1606. other.m[12] = l26 * l27;
  1607. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1608. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1609. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1610. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1611. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1612. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1613. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1614. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1615. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1616. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1617. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1618. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1619. return this;
  1620. };
  1621. Matrix.prototype.setTranslation = function (vector3) {
  1622. this.m[12] = vector3.x;
  1623. this.m[13] = vector3.y;
  1624. this.m[14] = vector3.z;
  1625. return this;
  1626. };
  1627. Matrix.prototype.multiply = function (other) {
  1628. var result = new Matrix();
  1629. this.multiplyToRef(other, result);
  1630. return result;
  1631. };
  1632. Matrix.prototype.copyFrom = function (other) {
  1633. for (var index = 0; index < 16; index++) {
  1634. this.m[index] = other.m[index];
  1635. }
  1636. return this;
  1637. };
  1638. Matrix.prototype.copyToArray = function (array, offset) {
  1639. if (offset === void 0) { offset = 0; }
  1640. for (var index = 0; index < 16; index++) {
  1641. array[offset + index] = this.m[index];
  1642. }
  1643. return this;
  1644. };
  1645. Matrix.prototype.multiplyToRef = function (other, result) {
  1646. this.multiplyToArray(other, result.m, 0);
  1647. return this;
  1648. };
  1649. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1650. var tm0 = this.m[0];
  1651. var tm1 = this.m[1];
  1652. var tm2 = this.m[2];
  1653. var tm3 = this.m[3];
  1654. var tm4 = this.m[4];
  1655. var tm5 = this.m[5];
  1656. var tm6 = this.m[6];
  1657. var tm7 = this.m[7];
  1658. var tm8 = this.m[8];
  1659. var tm9 = this.m[9];
  1660. var tm10 = this.m[10];
  1661. var tm11 = this.m[11];
  1662. var tm12 = this.m[12];
  1663. var tm13 = this.m[13];
  1664. var tm14 = this.m[14];
  1665. var tm15 = this.m[15];
  1666. var om0 = other.m[0];
  1667. var om1 = other.m[1];
  1668. var om2 = other.m[2];
  1669. var om3 = other.m[3];
  1670. var om4 = other.m[4];
  1671. var om5 = other.m[5];
  1672. var om6 = other.m[6];
  1673. var om7 = other.m[7];
  1674. var om8 = other.m[8];
  1675. var om9 = other.m[9];
  1676. var om10 = other.m[10];
  1677. var om11 = other.m[11];
  1678. var om12 = other.m[12];
  1679. var om13 = other.m[13];
  1680. var om14 = other.m[14];
  1681. var om15 = other.m[15];
  1682. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1683. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1684. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1685. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1686. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1687. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1688. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1689. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1690. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1691. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1692. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1693. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1694. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1695. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1696. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1697. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1698. return this;
  1699. };
  1700. Matrix.prototype.equals = function (value) {
  1701. return value &&
  1702. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  1703. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  1704. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  1705. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1706. };
  1707. Matrix.prototype.clone = function () {
  1708. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  1709. };
  1710. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1711. translation.x = this.m[12];
  1712. translation.y = this.m[13];
  1713. translation.z = this.m[14];
  1714. var xs = BABYLON.Tools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1715. var ys = BABYLON.Tools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1716. var zs = BABYLON.Tools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1717. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1718. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1719. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1720. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1721. rotation.x = 0;
  1722. rotation.y = 0;
  1723. rotation.z = 0;
  1724. rotation.w = 1;
  1725. return false;
  1726. }
  1727. var rotationMatrix = Matrix.FromValues(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1);
  1728. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1729. return true;
  1730. };
  1731. // Statics
  1732. Matrix.FromArray = function (array, offset) {
  1733. var result = new Matrix();
  1734. if (!offset) {
  1735. offset = 0;
  1736. }
  1737. Matrix.FromArrayToRef(array, offset, result);
  1738. return result;
  1739. };
  1740. Matrix.FromArrayToRef = function (array, offset, result) {
  1741. for (var index = 0; index < 16; index++) {
  1742. result.m[index] = array[index + offset];
  1743. }
  1744. };
  1745. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  1746. for (var index = 0; index < 16; index++) {
  1747. result.m[index] = array[index + offset] * scale;
  1748. }
  1749. };
  1750. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1751. result.m[0] = initialM11;
  1752. result.m[1] = initialM12;
  1753. result.m[2] = initialM13;
  1754. result.m[3] = initialM14;
  1755. result.m[4] = initialM21;
  1756. result.m[5] = initialM22;
  1757. result.m[6] = initialM23;
  1758. result.m[7] = initialM24;
  1759. result.m[8] = initialM31;
  1760. result.m[9] = initialM32;
  1761. result.m[10] = initialM33;
  1762. result.m[11] = initialM34;
  1763. result.m[12] = initialM41;
  1764. result.m[13] = initialM42;
  1765. result.m[14] = initialM43;
  1766. result.m[15] = initialM44;
  1767. };
  1768. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1769. var result = new Matrix();
  1770. result.m[0] = initialM11;
  1771. result.m[1] = initialM12;
  1772. result.m[2] = initialM13;
  1773. result.m[3] = initialM14;
  1774. result.m[4] = initialM21;
  1775. result.m[5] = initialM22;
  1776. result.m[6] = initialM23;
  1777. result.m[7] = initialM24;
  1778. result.m[8] = initialM31;
  1779. result.m[9] = initialM32;
  1780. result.m[10] = initialM33;
  1781. result.m[11] = initialM34;
  1782. result.m[12] = initialM41;
  1783. result.m[13] = initialM42;
  1784. result.m[14] = initialM43;
  1785. result.m[15] = initialM44;
  1786. return result;
  1787. };
  1788. Matrix.Compose = function (scale, rotation, translation) {
  1789. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1790. var rotationMatrix = Matrix.Identity();
  1791. rotation.toRotationMatrix(rotationMatrix);
  1792. result = result.multiply(rotationMatrix);
  1793. result.setTranslation(translation);
  1794. return result;
  1795. };
  1796. Matrix.Identity = function () {
  1797. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1798. };
  1799. Matrix.IdentityToRef = function (result) {
  1800. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1801. };
  1802. Matrix.Zero = function () {
  1803. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1804. };
  1805. Matrix.RotationX = function (angle) {
  1806. var result = new Matrix();
  1807. Matrix.RotationXToRef(angle, result);
  1808. return result;
  1809. };
  1810. Matrix.Invert = function (source) {
  1811. var result = new Matrix();
  1812. source.invertToRef(result);
  1813. return result;
  1814. };
  1815. Matrix.RotationXToRef = function (angle, result) {
  1816. var s = Math.sin(angle);
  1817. var c = Math.cos(angle);
  1818. result.m[0] = 1.0;
  1819. result.m[15] = 1.0;
  1820. result.m[5] = c;
  1821. result.m[10] = c;
  1822. result.m[9] = -s;
  1823. result.m[6] = s;
  1824. result.m[1] = 0;
  1825. result.m[2] = 0;
  1826. result.m[3] = 0;
  1827. result.m[4] = 0;
  1828. result.m[7] = 0;
  1829. result.m[8] = 0;
  1830. result.m[11] = 0;
  1831. result.m[12] = 0;
  1832. result.m[13] = 0;
  1833. result.m[14] = 0;
  1834. };
  1835. Matrix.RotationY = function (angle) {
  1836. var result = new Matrix();
  1837. Matrix.RotationYToRef(angle, result);
  1838. return result;
  1839. };
  1840. Matrix.RotationYToRef = function (angle, result) {
  1841. var s = Math.sin(angle);
  1842. var c = Math.cos(angle);
  1843. result.m[5] = 1.0;
  1844. result.m[15] = 1.0;
  1845. result.m[0] = c;
  1846. result.m[2] = -s;
  1847. result.m[8] = s;
  1848. result.m[10] = c;
  1849. result.m[1] = 0;
  1850. result.m[3] = 0;
  1851. result.m[4] = 0;
  1852. result.m[6] = 0;
  1853. result.m[7] = 0;
  1854. result.m[9] = 0;
  1855. result.m[11] = 0;
  1856. result.m[12] = 0;
  1857. result.m[13] = 0;
  1858. result.m[14] = 0;
  1859. };
  1860. Matrix.RotationZ = function (angle) {
  1861. var result = new Matrix();
  1862. Matrix.RotationZToRef(angle, result);
  1863. return result;
  1864. };
  1865. Matrix.RotationZToRef = function (angle, result) {
  1866. var s = Math.sin(angle);
  1867. var c = Math.cos(angle);
  1868. result.m[10] = 1.0;
  1869. result.m[15] = 1.0;
  1870. result.m[0] = c;
  1871. result.m[1] = s;
  1872. result.m[4] = -s;
  1873. result.m[5] = c;
  1874. result.m[2] = 0;
  1875. result.m[3] = 0;
  1876. result.m[6] = 0;
  1877. result.m[7] = 0;
  1878. result.m[8] = 0;
  1879. result.m[9] = 0;
  1880. result.m[11] = 0;
  1881. result.m[12] = 0;
  1882. result.m[13] = 0;
  1883. result.m[14] = 0;
  1884. };
  1885. Matrix.RotationAxis = function (axis, angle) {
  1886. var result = Matrix.Zero();
  1887. Matrix.RotationAxisToRef(axis, angle, result);
  1888. return result;
  1889. };
  1890. Matrix.RotationAxisToRef = function (axis, angle, result) {
  1891. var s = Math.sin(-angle);
  1892. var c = Math.cos(-angle);
  1893. var c1 = 1 - c;
  1894. axis.normalize();
  1895. result.m[0] = (axis.x * axis.x) * c1 + c;
  1896. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1897. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1898. result.m[3] = 0.0;
  1899. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1900. result.m[5] = (axis.y * axis.y) * c1 + c;
  1901. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1902. result.m[7] = 0.0;
  1903. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1904. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1905. result.m[10] = (axis.z * axis.z) * c1 + c;
  1906. result.m[11] = 0.0;
  1907. result.m[15] = 1.0;
  1908. };
  1909. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1910. var result = new Matrix();
  1911. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1912. return result;
  1913. };
  1914. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1915. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1916. this._tempQuaternion.toRotationMatrix(result);
  1917. };
  1918. Matrix.Scaling = function (x, y, z) {
  1919. var result = Matrix.Zero();
  1920. Matrix.ScalingToRef(x, y, z, result);
  1921. return result;
  1922. };
  1923. Matrix.ScalingToRef = function (x, y, z, result) {
  1924. result.m[0] = x;
  1925. result.m[1] = 0;
  1926. result.m[2] = 0;
  1927. result.m[3] = 0;
  1928. result.m[4] = 0;
  1929. result.m[5] = y;
  1930. result.m[6] = 0;
  1931. result.m[7] = 0;
  1932. result.m[8] = 0;
  1933. result.m[9] = 0;
  1934. result.m[10] = z;
  1935. result.m[11] = 0;
  1936. result.m[12] = 0;
  1937. result.m[13] = 0;
  1938. result.m[14] = 0;
  1939. result.m[15] = 1.0;
  1940. };
  1941. Matrix.Translation = function (x, y, z) {
  1942. var result = Matrix.Identity();
  1943. Matrix.TranslationToRef(x, y, z, result);
  1944. return result;
  1945. };
  1946. Matrix.TranslationToRef = function (x, y, z, result) {
  1947. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1948. };
  1949. Matrix.Lerp = function (startValue, endValue, gradient) {
  1950. var startScale = new Vector3(0, 0, 0);
  1951. var startRotation = new Quaternion();
  1952. var startTranslation = new Vector3(0, 0, 0);
  1953. startValue.decompose(startScale, startRotation, startTranslation);
  1954. var endScale = new Vector3(0, 0, 0);
  1955. var endRotation = new Quaternion();
  1956. var endTranslation = new Vector3(0, 0, 0);
  1957. endValue.decompose(endScale, endRotation, endTranslation);
  1958. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  1959. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  1960. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  1961. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  1962. };
  1963. Matrix.LookAtLH = function (eye, target, up) {
  1964. var result = Matrix.Zero();
  1965. Matrix.LookAtLHToRef(eye, target, up, result);
  1966. return result;
  1967. };
  1968. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1969. // Z axis
  1970. target.subtractToRef(eye, this._zAxis);
  1971. this._zAxis.normalize();
  1972. // X axis
  1973. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1974. if (this._xAxis.lengthSquared() === 0) {
  1975. this._xAxis.x = 1.0;
  1976. }
  1977. else {
  1978. this._xAxis.normalize();
  1979. }
  1980. // Y axis
  1981. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1982. this._yAxis.normalize();
  1983. // Eye angles
  1984. var ex = -Vector3.Dot(this._xAxis, eye);
  1985. var ey = -Vector3.Dot(this._yAxis, eye);
  1986. var ez = -Vector3.Dot(this._zAxis, eye);
  1987. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  1988. };
  1989. Matrix.OrthoLH = function (width, height, znear, zfar) {
  1990. var matrix = Matrix.Zero();
  1991. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  1992. return matrix;
  1993. };
  1994. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  1995. var hw = 2.0 / width;
  1996. var hh = 2.0 / height;
  1997. var id = 1.0 / (zfar - znear);
  1998. var nid = znear / (znear - zfar);
  1999. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  2000. };
  2001. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  2002. var matrix = Matrix.Zero();
  2003. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  2004. return matrix;
  2005. };
  2006. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2007. result.m[0] = 2.0 / (right - left);
  2008. result.m[1] = result.m[2] = result.m[3] = 0;
  2009. result.m[5] = 2.0 / (top - bottom);
  2010. result.m[4] = result.m[6] = result.m[7] = 0;
  2011. result.m[10] = -1.0 / (znear - zfar);
  2012. result.m[8] = result.m[9] = result.m[11] = 0;
  2013. result.m[12] = (left + right) / (left - right);
  2014. result.m[13] = (top + bottom) / (bottom - top);
  2015. result.m[14] = znear / (znear - zfar);
  2016. result.m[15] = 1.0;
  2017. };
  2018. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  2019. var matrix = Matrix.Zero();
  2020. matrix.m[0] = (2.0 * znear) / width;
  2021. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  2022. matrix.m[5] = (2.0 * znear) / height;
  2023. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  2024. matrix.m[10] = -zfar / (znear - zfar);
  2025. matrix.m[8] = matrix.m[9] = 0.0;
  2026. matrix.m[11] = 1.0;
  2027. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  2028. matrix.m[14] = (znear * zfar) / (znear - zfar);
  2029. return matrix;
  2030. };
  2031. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  2032. var matrix = Matrix.Zero();
  2033. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  2034. return matrix;
  2035. };
  2036. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, fovMode) {
  2037. if (fovMode === void 0) { fovMode = BABYLON.Camera.FOVMODE_VERTICAL_FIXED; }
  2038. var tan = 1.0 / (Math.tan(fov * 0.5));
  2039. var v_fixed = (fovMode === BABYLON.Camera.FOVMODE_VERTICAL_FIXED);
  2040. if (v_fixed) {
  2041. result.m[0] = tan / aspect;
  2042. }
  2043. else {
  2044. result.m[0] = tan;
  2045. }
  2046. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2047. if (v_fixed) {
  2048. result.m[5] = tan;
  2049. }
  2050. else {
  2051. result.m[5] = tan * aspect;
  2052. }
  2053. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2054. result.m[8] = result.m[9] = 0.0;
  2055. result.m[10] = -zfar / (znear - zfar);
  2056. result.m[11] = 1.0;
  2057. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2058. result.m[14] = (znear * zfar) / (znear - zfar);
  2059. };
  2060. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2061. var cw = viewport.width;
  2062. var ch = viewport.height;
  2063. var cx = viewport.x;
  2064. var cy = viewport.y;
  2065. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, zmax - zmin, 0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  2066. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2067. };
  2068. Matrix.GetAsMatrix2x2 = function (matrix) {
  2069. return new Float32Array([
  2070. matrix.m[0], matrix.m[1],
  2071. matrix.m[4], matrix.m[5]
  2072. ]);
  2073. };
  2074. Matrix.GetAsMatrix3x3 = function (matrix) {
  2075. return new Float32Array([
  2076. matrix.m[0], matrix.m[1], matrix.m[2],
  2077. matrix.m[4], matrix.m[5], matrix.m[6],
  2078. matrix.m[8], matrix.m[9], matrix.m[10]
  2079. ]);
  2080. };
  2081. Matrix.Transpose = function (matrix) {
  2082. var result = new Matrix();
  2083. result.m[0] = matrix.m[0];
  2084. result.m[1] = matrix.m[4];
  2085. result.m[2] = matrix.m[8];
  2086. result.m[3] = matrix.m[12];
  2087. result.m[4] = matrix.m[1];
  2088. result.m[5] = matrix.m[5];
  2089. result.m[6] = matrix.m[9];
  2090. result.m[7] = matrix.m[13];
  2091. result.m[8] = matrix.m[2];
  2092. result.m[9] = matrix.m[6];
  2093. result.m[10] = matrix.m[10];
  2094. result.m[11] = matrix.m[14];
  2095. result.m[12] = matrix.m[3];
  2096. result.m[13] = matrix.m[7];
  2097. result.m[14] = matrix.m[11];
  2098. result.m[15] = matrix.m[15];
  2099. return result;
  2100. };
  2101. Matrix.Reflection = function (plane) {
  2102. var matrix = new Matrix();
  2103. Matrix.ReflectionToRef(plane, matrix);
  2104. return matrix;
  2105. };
  2106. Matrix.ReflectionToRef = function (plane, result) {
  2107. plane.normalize();
  2108. var x = plane.normal.x;
  2109. var y = plane.normal.y;
  2110. var z = plane.normal.z;
  2111. var temp = -2 * x;
  2112. var temp2 = -2 * y;
  2113. var temp3 = -2 * z;
  2114. result.m[0] = (temp * x) + 1;
  2115. result.m[1] = temp2 * x;
  2116. result.m[2] = temp3 * x;
  2117. result.m[3] = 0.0;
  2118. result.m[4] = temp * y;
  2119. result.m[5] = (temp2 * y) + 1;
  2120. result.m[6] = temp3 * y;
  2121. result.m[7] = 0.0;
  2122. result.m[8] = temp * z;
  2123. result.m[9] = temp2 * z;
  2124. result.m[10] = (temp3 * z) + 1;
  2125. result.m[11] = 0.0;
  2126. result.m[12] = temp * plane.d;
  2127. result.m[13] = temp2 * plane.d;
  2128. result.m[14] = temp3 * plane.d;
  2129. result.m[15] = 1.0;
  2130. };
  2131. Matrix._tempQuaternion = new Quaternion();
  2132. Matrix._xAxis = Vector3.Zero();
  2133. Matrix._yAxis = Vector3.Zero();
  2134. Matrix._zAxis = Vector3.Zero();
  2135. return Matrix;
  2136. })();
  2137. BABYLON.Matrix = Matrix;
  2138. var Plane = (function () {
  2139. function Plane(a, b, c, d) {
  2140. this.normal = new Vector3(a, b, c);
  2141. this.d = d;
  2142. }
  2143. Plane.prototype.asArray = function () {
  2144. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2145. };
  2146. // Methods
  2147. Plane.prototype.clone = function () {
  2148. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2149. };
  2150. Plane.prototype.normalize = function () {
  2151. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2152. var magnitude = 0;
  2153. if (norm !== 0) {
  2154. magnitude = 1.0 / norm;
  2155. }
  2156. this.normal.x *= magnitude;
  2157. this.normal.y *= magnitude;
  2158. this.normal.z *= magnitude;
  2159. this.d *= magnitude;
  2160. return this;
  2161. };
  2162. Plane.prototype.transform = function (transformation) {
  2163. var transposedMatrix = Matrix.Transpose(transformation);
  2164. var x = this.normal.x;
  2165. var y = this.normal.y;
  2166. var z = this.normal.z;
  2167. var d = this.d;
  2168. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2169. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2170. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2171. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2172. return new Plane(normalX, normalY, normalZ, finalD);
  2173. };
  2174. Plane.prototype.dotCoordinate = function (point) {
  2175. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2176. };
  2177. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2178. var x1 = point2.x - point1.x;
  2179. var y1 = point2.y - point1.y;
  2180. var z1 = point2.z - point1.z;
  2181. var x2 = point3.x - point1.x;
  2182. var y2 = point3.y - point1.y;
  2183. var z2 = point3.z - point1.z;
  2184. var yz = (y1 * z2) - (z1 * y2);
  2185. var xz = (z1 * x2) - (x1 * z2);
  2186. var xy = (x1 * y2) - (y1 * x2);
  2187. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2188. var invPyth;
  2189. if (pyth !== 0) {
  2190. invPyth = 1.0 / pyth;
  2191. }
  2192. else {
  2193. invPyth = 0;
  2194. }
  2195. this.normal.x = yz * invPyth;
  2196. this.normal.y = xz * invPyth;
  2197. this.normal.z = xy * invPyth;
  2198. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2199. return this;
  2200. };
  2201. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2202. var dot = Vector3.Dot(this.normal, direction);
  2203. return (dot <= epsilon);
  2204. };
  2205. Plane.prototype.signedDistanceTo = function (point) {
  2206. return Vector3.Dot(point, this.normal) + this.d;
  2207. };
  2208. // Statics
  2209. Plane.FromArray = function (array) {
  2210. return new Plane(array[0], array[1], array[2], array[3]);
  2211. };
  2212. Plane.FromPoints = function (point1, point2, point3) {
  2213. var result = new Plane(0, 0, 0, 0);
  2214. result.copyFromPoints(point1, point2, point3);
  2215. return result;
  2216. };
  2217. Plane.FromPositionAndNormal = function (origin, normal) {
  2218. var result = new Plane(0, 0, 0, 0);
  2219. normal.normalize();
  2220. result.normal = normal;
  2221. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2222. return result;
  2223. };
  2224. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2225. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2226. return Vector3.Dot(point, normal) + d;
  2227. };
  2228. return Plane;
  2229. })();
  2230. BABYLON.Plane = Plane;
  2231. var Viewport = (function () {
  2232. function Viewport(x, y, width, height) {
  2233. this.x = x;
  2234. this.y = y;
  2235. this.width = width;
  2236. this.height = height;
  2237. }
  2238. Viewport.prototype.toGlobal = function (engine) {
  2239. var width = engine.getRenderWidth();
  2240. var height = engine.getRenderHeight();
  2241. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  2242. };
  2243. Viewport.prototype.toScreenGlobal = function (engine) {
  2244. var width = engine.getRenderWidth(true);
  2245. var height = engine.getRenderHeight(true);
  2246. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  2247. };
  2248. return Viewport;
  2249. })();
  2250. BABYLON.Viewport = Viewport;
  2251. var Frustum = (function () {
  2252. function Frustum() {
  2253. }
  2254. Frustum.GetPlanes = function (transform) {
  2255. var frustumPlanes = [];
  2256. for (var index = 0; index < 6; index++) {
  2257. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2258. }
  2259. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2260. return frustumPlanes;
  2261. };
  2262. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2263. // Near
  2264. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2265. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2266. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  2267. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2268. frustumPlanes[0].normalize();
  2269. // Far
  2270. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2271. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2272. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2273. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2274. frustumPlanes[1].normalize();
  2275. // Left
  2276. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2277. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2278. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2279. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2280. frustumPlanes[2].normalize();
  2281. // Right
  2282. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2283. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2284. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2285. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2286. frustumPlanes[3].normalize();
  2287. // Top
  2288. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2289. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2290. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2291. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2292. frustumPlanes[4].normalize();
  2293. // Bottom
  2294. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2295. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2296. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2297. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2298. frustumPlanes[5].normalize();
  2299. };
  2300. return Frustum;
  2301. })();
  2302. BABYLON.Frustum = Frustum;
  2303. var Ray = (function () {
  2304. function Ray(origin, direction, length) {
  2305. if (length === void 0) { length = Number.MAX_VALUE; }
  2306. this.origin = origin;
  2307. this.direction = direction;
  2308. this.length = length;
  2309. }
  2310. // Methods
  2311. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  2312. var d = 0.0;
  2313. var maxValue = Number.MAX_VALUE;
  2314. var inv;
  2315. var min;
  2316. var max;
  2317. var temp;
  2318. if (Math.abs(this.direction.x) < 0.0000001) {
  2319. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  2320. return false;
  2321. }
  2322. }
  2323. else {
  2324. inv = 1.0 / this.direction.x;
  2325. min = (minimum.x - this.origin.x) * inv;
  2326. max = (maximum.x - this.origin.x) * inv;
  2327. if (max === -Infinity) {
  2328. max = Infinity;
  2329. }
  2330. if (min > max) {
  2331. temp = min;
  2332. min = max;
  2333. max = temp;
  2334. }
  2335. d = Math.max(min, d);
  2336. maxValue = Math.min(max, maxValue);
  2337. if (d > maxValue) {
  2338. return false;
  2339. }
  2340. }
  2341. if (Math.abs(this.direction.y) < 0.0000001) {
  2342. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  2343. return false;
  2344. }
  2345. }
  2346. else {
  2347. inv = 1.0 / this.direction.y;
  2348. min = (minimum.y - this.origin.y) * inv;
  2349. max = (maximum.y - this.origin.y) * inv;
  2350. if (max === -Infinity) {
  2351. max = Infinity;
  2352. }
  2353. if (min > max) {
  2354. temp = min;
  2355. min = max;
  2356. max = temp;
  2357. }
  2358. d = Math.max(min, d);
  2359. maxValue = Math.min(max, maxValue);
  2360. if (d > maxValue) {
  2361. return false;
  2362. }
  2363. }
  2364. if (Math.abs(this.direction.z) < 0.0000001) {
  2365. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  2366. return false;
  2367. }
  2368. }
  2369. else {
  2370. inv = 1.0 / this.direction.z;
  2371. min = (minimum.z - this.origin.z) * inv;
  2372. max = (maximum.z - this.origin.z) * inv;
  2373. if (max === -Infinity) {
  2374. max = Infinity;
  2375. }
  2376. if (min > max) {
  2377. temp = min;
  2378. min = max;
  2379. max = temp;
  2380. }
  2381. d = Math.max(min, d);
  2382. maxValue = Math.min(max, maxValue);
  2383. if (d > maxValue) {
  2384. return false;
  2385. }
  2386. }
  2387. return true;
  2388. };
  2389. Ray.prototype.intersectsBox = function (box) {
  2390. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  2391. };
  2392. Ray.prototype.intersectsSphere = function (sphere) {
  2393. var x = sphere.center.x - this.origin.x;
  2394. var y = sphere.center.y - this.origin.y;
  2395. var z = sphere.center.z - this.origin.z;
  2396. var pyth = (x * x) + (y * y) + (z * z);
  2397. var rr = sphere.radius * sphere.radius;
  2398. if (pyth <= rr) {
  2399. return true;
  2400. }
  2401. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  2402. if (dot < 0.0) {
  2403. return false;
  2404. }
  2405. var temp = pyth - (dot * dot);
  2406. return temp <= rr;
  2407. };
  2408. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  2409. if (!this._edge1) {
  2410. this._edge1 = Vector3.Zero();
  2411. this._edge2 = Vector3.Zero();
  2412. this._pvec = Vector3.Zero();
  2413. this._tvec = Vector3.Zero();
  2414. this._qvec = Vector3.Zero();
  2415. }
  2416. vertex1.subtractToRef(vertex0, this._edge1);
  2417. vertex2.subtractToRef(vertex0, this._edge2);
  2418. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  2419. var det = Vector3.Dot(this._edge1, this._pvec);
  2420. if (det === 0) {
  2421. return null;
  2422. }
  2423. var invdet = 1 / det;
  2424. this.origin.subtractToRef(vertex0, this._tvec);
  2425. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  2426. if (bu < 0 || bu > 1.0) {
  2427. return null;
  2428. }
  2429. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  2430. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  2431. if (bv < 0 || bu + bv > 1.0) {
  2432. return null;
  2433. }
  2434. //check if the distance is longer than the predefined length.
  2435. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  2436. if (distance > this.length) {
  2437. return null;
  2438. }
  2439. return new BABYLON.IntersectionInfo(bu, bv, distance);
  2440. };
  2441. // Statics
  2442. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  2443. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2444. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2445. var direction = end.subtract(start);
  2446. direction.normalize();
  2447. return new Ray(start, direction);
  2448. };
  2449. /**
  2450. * Function will create a new transformed ray starting from origin and ending at the end point. Ray's length will be set, and ray will be
  2451. * transformed to the given world matrix.
  2452. * @param origin The origin point
  2453. * @param end The end point
  2454. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2455. */
  2456. Ray.CreateNewFromTo = function (origin, end, world) {
  2457. if (world === void 0) { world = Matrix.Identity(); }
  2458. var direction = end.subtract(origin);
  2459. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2460. direction.normalize();
  2461. return Ray.Transform(new Ray(origin, direction, length), world);
  2462. };
  2463. Ray.Transform = function (ray, matrix) {
  2464. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2465. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2466. return new Ray(newOrigin, newDirection, ray.length);
  2467. };
  2468. return Ray;
  2469. })();
  2470. BABYLON.Ray = Ray;
  2471. (function (Space) {
  2472. Space[Space["LOCAL"] = 0] = "LOCAL";
  2473. Space[Space["WORLD"] = 1] = "WORLD";
  2474. })(BABYLON.Space || (BABYLON.Space = {}));
  2475. var Space = BABYLON.Space;
  2476. var Axis = (function () {
  2477. function Axis() {
  2478. }
  2479. Axis.X = new Vector3(1, 0, 0);
  2480. Axis.Y = new Vector3(0, 1, 0);
  2481. Axis.Z = new Vector3(0, 0, 1);
  2482. return Axis;
  2483. })();
  2484. BABYLON.Axis = Axis;
  2485. ;
  2486. var BezierCurve = (function () {
  2487. function BezierCurve() {
  2488. }
  2489. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2490. // Extract X (which is equal to time here)
  2491. var f0 = 1 - 3 * x2 + 3 * x1;
  2492. var f1 = 3 * x2 - 6 * x1;
  2493. var f2 = 3 * x1;
  2494. var refinedT = t;
  2495. for (var i = 0; i < 5; i++) {
  2496. var refinedT2 = refinedT * refinedT;
  2497. var refinedT3 = refinedT2 * refinedT;
  2498. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2499. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2500. refinedT -= (x - t) * slope;
  2501. refinedT = Math.min(1, Math.max(0, refinedT));
  2502. }
  2503. // Resolve cubic bezier for the given x
  2504. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2505. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2506. Math.pow(refinedT, 3);
  2507. };
  2508. return BezierCurve;
  2509. })();
  2510. BABYLON.BezierCurve = BezierCurve;
  2511. (function (Orientation) {
  2512. Orientation[Orientation["CW"] = 0] = "CW";
  2513. Orientation[Orientation["CCW"] = 1] = "CCW";
  2514. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2515. var Orientation = BABYLON.Orientation;
  2516. var Angle = (function () {
  2517. function Angle(radians) {
  2518. var _this = this;
  2519. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2520. this.radians = function () { return _this._radians; };
  2521. this._radians = radians;
  2522. if (this._radians < 0)
  2523. this._radians += (2 * Math.PI);
  2524. }
  2525. Angle.BetweenTwoPoints = function (a, b) {
  2526. var delta = b.subtract(a);
  2527. var theta = Math.atan2(delta.y, delta.x);
  2528. return new Angle(theta);
  2529. };
  2530. Angle.FromRadians = function (radians) {
  2531. return new Angle(radians);
  2532. };
  2533. Angle.FromDegrees = function (degrees) {
  2534. return new Angle(degrees * Math.PI / 180);
  2535. };
  2536. return Angle;
  2537. })();
  2538. BABYLON.Angle = Angle;
  2539. var Arc2 = (function () {
  2540. function Arc2(startPoint, midPoint, endPoint) {
  2541. this.startPoint = startPoint;
  2542. this.midPoint = midPoint;
  2543. this.endPoint = endPoint;
  2544. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2545. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2546. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2547. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2548. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  2549. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2550. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2551. var a1 = this.startAngle.degrees();
  2552. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2553. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2554. // angles correction
  2555. if (a2 - a1 > +180.0)
  2556. a2 -= 360.0;
  2557. if (a2 - a1 < -180.0)
  2558. a2 += 360.0;
  2559. if (a3 - a2 > +180.0)
  2560. a3 -= 360.0;
  2561. if (a3 - a2 < -180.0)
  2562. a3 += 360.0;
  2563. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2564. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2565. }
  2566. return Arc2;
  2567. })();
  2568. BABYLON.Arc2 = Arc2;
  2569. var PathCursor = (function () {
  2570. function PathCursor(path) {
  2571. this.path = path;
  2572. this._onchange = new Array();
  2573. this.value = 0;
  2574. this.animations = new Array();
  2575. }
  2576. PathCursor.prototype.getPoint = function () {
  2577. var point = this.path.getPointAtLengthPosition(this.value);
  2578. return new Vector3(point.x, 0, point.y);
  2579. };
  2580. PathCursor.prototype.moveAhead = function (step) {
  2581. if (step === void 0) { step = 0.002; }
  2582. this.move(step);
  2583. return this;
  2584. };
  2585. PathCursor.prototype.moveBack = function (step) {
  2586. if (step === void 0) { step = 0.002; }
  2587. this.move(-step);
  2588. return this;
  2589. };
  2590. PathCursor.prototype.move = function (step) {
  2591. if (Math.abs(step) > 1) {
  2592. throw "step size should be less than 1.";
  2593. }
  2594. this.value += step;
  2595. this.ensureLimits();
  2596. this.raiseOnChange();
  2597. return this;
  2598. };
  2599. PathCursor.prototype.ensureLimits = function () {
  2600. while (this.value > 1) {
  2601. this.value -= 1;
  2602. }
  2603. while (this.value < 0) {
  2604. this.value += 1;
  2605. }
  2606. return this;
  2607. };
  2608. // used by animation engine
  2609. PathCursor.prototype.markAsDirty = function (propertyName) {
  2610. this.ensureLimits();
  2611. this.raiseOnChange();
  2612. return this;
  2613. };
  2614. PathCursor.prototype.raiseOnChange = function () {
  2615. var _this = this;
  2616. this._onchange.forEach(function (f) { return f(_this); });
  2617. return this;
  2618. };
  2619. PathCursor.prototype.onchange = function (f) {
  2620. this._onchange.push(f);
  2621. return this;
  2622. };
  2623. return PathCursor;
  2624. })();
  2625. BABYLON.PathCursor = PathCursor;
  2626. var Path2 = (function () {
  2627. function Path2(x, y) {
  2628. this._points = new Array();
  2629. this._length = 0;
  2630. this.closed = false;
  2631. this._points.push(new Vector2(x, y));
  2632. }
  2633. Path2.prototype.addLineTo = function (x, y) {
  2634. if (closed) {
  2635. BABYLON.Tools.Error("cannot add lines to closed paths");
  2636. return this;
  2637. }
  2638. var newPoint = new Vector2(x, y);
  2639. var previousPoint = this._points[this._points.length - 1];
  2640. this._points.push(newPoint);
  2641. this._length += newPoint.subtract(previousPoint).length();
  2642. return this;
  2643. };
  2644. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2645. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2646. if (closed) {
  2647. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2648. return this;
  2649. }
  2650. var startPoint = this._points[this._points.length - 1];
  2651. var midPoint = new Vector2(midX, midY);
  2652. var endPoint = new Vector2(endX, endY);
  2653. var arc = new Arc2(startPoint, midPoint, endPoint);
  2654. var increment = arc.angle.radians() / numberOfSegments;
  2655. if (arc.orientation === Orientation.CW)
  2656. increment *= -1;
  2657. var currentAngle = arc.startAngle.radians() + increment;
  2658. for (var i = 0; i < numberOfSegments; i++) {
  2659. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2660. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2661. this.addLineTo(x, y);
  2662. currentAngle += increment;
  2663. }
  2664. return this;
  2665. };
  2666. Path2.prototype.close = function () {
  2667. this.closed = true;
  2668. return this;
  2669. };
  2670. Path2.prototype.length = function () {
  2671. var result = this._length;
  2672. if (!this.closed) {
  2673. var lastPoint = this._points[this._points.length - 1];
  2674. var firstPoint = this._points[0];
  2675. result += (firstPoint.subtract(lastPoint).length());
  2676. }
  2677. return result;
  2678. };
  2679. Path2.prototype.getPoints = function () {
  2680. return this._points;
  2681. };
  2682. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2683. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2684. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2685. return Vector2.Zero();
  2686. }
  2687. var lengthPosition = normalizedLengthPosition * this.length();
  2688. var previousOffset = 0;
  2689. for (var i = 0; i < this._points.length; i++) {
  2690. var j = (i + 1) % this._points.length;
  2691. var a = this._points[i];
  2692. var b = this._points[j];
  2693. var bToA = b.subtract(a);
  2694. var nextOffset = (bToA.length() + previousOffset);
  2695. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2696. var dir = bToA.normalize();
  2697. var localOffset = lengthPosition - previousOffset;
  2698. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2699. }
  2700. previousOffset = nextOffset;
  2701. }
  2702. BABYLON.Tools.Error("internal error");
  2703. return Vector2.Zero();
  2704. };
  2705. Path2.StartingAt = function (x, y) {
  2706. return new Path2(x, y);
  2707. };
  2708. return Path2;
  2709. })();
  2710. BABYLON.Path2 = Path2;
  2711. var Path3D = (function () {
  2712. /**
  2713. * new Path3D(path, normal, raw)
  2714. * path : an array of Vector3, the curve axis of the Path3D
  2715. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  2716. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  2717. */
  2718. function Path3D(path, firstNormal, raw) {
  2719. this.path = path;
  2720. this._curve = new Array();
  2721. this._distances = new Array();
  2722. this._tangents = new Array();
  2723. this._normals = new Array();
  2724. this._binormals = new Array();
  2725. for (var p = 0; p < path.length; p++) {
  2726. this._curve[p] = path[p].clone(); // hard copy
  2727. }
  2728. this._raw = raw || false;
  2729. this._compute(firstNormal);
  2730. }
  2731. Path3D.prototype.getCurve = function () {
  2732. return this._curve;
  2733. };
  2734. Path3D.prototype.getTangents = function () {
  2735. return this._tangents;
  2736. };
  2737. Path3D.prototype.getNormals = function () {
  2738. return this._normals;
  2739. };
  2740. Path3D.prototype.getBinormals = function () {
  2741. return this._binormals;
  2742. };
  2743. Path3D.prototype.getDistances = function () {
  2744. return this._distances;
  2745. };
  2746. Path3D.prototype.update = function (path, firstNormal) {
  2747. for (var p = 0; p < path.length; p++) {
  2748. this._curve[p].x = path[p].x;
  2749. this._curve[p].y = path[p].y;
  2750. this._curve[p].z = path[p].z;
  2751. }
  2752. this._compute(firstNormal);
  2753. return this;
  2754. };
  2755. // private function compute() : computes tangents, normals and binormals
  2756. Path3D.prototype._compute = function (firstNormal) {
  2757. var l = this._curve.length;
  2758. // first and last tangents
  2759. this._tangents[0] = this._getFirstNonNullVector(0);
  2760. if (!this._raw) {
  2761. this._tangents[0].normalize();
  2762. }
  2763. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2764. if (!this._raw) {
  2765. this._tangents[l - 1].normalize();
  2766. }
  2767. // normals and binormals at first point : arbitrary vector with _normalVector()
  2768. var tg0 = this._tangents[0];
  2769. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2770. this._normals[0] = pp0;
  2771. if (!this._raw) {
  2772. this._normals[0].normalize();
  2773. }
  2774. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2775. if (!this._raw) {
  2776. this._binormals[0].normalize();
  2777. }
  2778. this._distances[0] = 0;
  2779. // normals and binormals : next points
  2780. var prev; // previous vector (segment)
  2781. var cur; // current vector (segment)
  2782. var curTang; // current tangent
  2783. // previous normal
  2784. var prevBinor; // previous binormal
  2785. for (var i = 1; i < l; i++) {
  2786. // tangents
  2787. prev = this._getLastNonNullVector(i);
  2788. if (i < l - 1) {
  2789. cur = this._getFirstNonNullVector(i);
  2790. this._tangents[i] = prev.add(cur);
  2791. this._tangents[i].normalize();
  2792. }
  2793. this._distances[i] = this._distances[i - 1] + prev.length();
  2794. // normals and binormals
  2795. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2796. curTang = this._tangents[i];
  2797. prevBinor = this._binormals[i - 1];
  2798. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2799. if (!this._raw) {
  2800. this._normals[i].normalize();
  2801. }
  2802. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2803. if (!this._raw) {
  2804. this._binormals[i].normalize();
  2805. }
  2806. }
  2807. };
  2808. // private function getFirstNonNullVector(index)
  2809. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  2810. Path3D.prototype._getFirstNonNullVector = function (index) {
  2811. var i = 1;
  2812. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  2813. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  2814. i++;
  2815. nNVector = this._curve[index + i].subtract(this._curve[index]);
  2816. }
  2817. return nNVector;
  2818. };
  2819. // private function getLastNonNullVector(index)
  2820. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  2821. Path3D.prototype._getLastNonNullVector = function (index) {
  2822. var i = 1;
  2823. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  2824. while (nLVector.length() === 0 && index > i + 1) {
  2825. i++;
  2826. nLVector = this._curve[index].subtract(this._curve[index - i]);
  2827. }
  2828. return nLVector;
  2829. };
  2830. // private function normalVector(v0, vt, va) :
  2831. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2832. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  2833. Path3D.prototype._normalVector = function (v0, vt, va) {
  2834. var normal0;
  2835. if (va === undefined || va === null) {
  2836. var point;
  2837. if (!BABYLON.Tools.WithinEpsilon(vt.y, 1, BABYLON.Engine.Epsilon)) {
  2838. point = new Vector3(0, -1, 0);
  2839. }
  2840. else if (!BABYLON.Tools.WithinEpsilon(vt.x, 1, BABYLON.Engine.Epsilon)) {
  2841. point = new Vector3(1, 0, 0);
  2842. }
  2843. else if (!BABYLON.Tools.WithinEpsilon(vt.z, 1, BABYLON.Engine.Epsilon)) {
  2844. point = new Vector3(0, 0, 1);
  2845. }
  2846. normal0 = Vector3.Cross(vt, point);
  2847. }
  2848. else {
  2849. normal0 = Vector3.Cross(vt, va);
  2850. Vector3.CrossToRef(normal0, vt, normal0);
  2851. }
  2852. normal0.normalize();
  2853. return normal0;
  2854. };
  2855. return Path3D;
  2856. })();
  2857. BABYLON.Path3D = Path3D;
  2858. var Curve3 = (function () {
  2859. function Curve3(points) {
  2860. this._length = 0;
  2861. this._points = points;
  2862. this._length = this._computeLength(points);
  2863. }
  2864. // QuadraticBezier(origin_V3, control_V3, destination_V3, nbPoints)
  2865. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2866. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2867. var bez = new Array();
  2868. var equation = function (t, val0, val1, val2) {
  2869. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  2870. return res;
  2871. };
  2872. for (var i = 0; i <= nbPoints; i++) {
  2873. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));
  2874. }
  2875. return new Curve3(bez);
  2876. };
  2877. // CubicBezier(origin_V3, control1_V3, control2_V3, destination_V3, nbPoints)
  2878. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  2879. nbPoints = nbPoints > 3 ? nbPoints : 4;
  2880. var bez = new Array();
  2881. var equation = function (t, val0, val1, val2, val3) {
  2882. var res = (1 - t) * (1 - t) * (1 - t) * val0 + 3 * t * (1 - t) * (1 - t) * val1 + 3 * t * t * (1 - t) * val2 + t * t * t * val3;
  2883. return res;
  2884. };
  2885. for (var i = 0; i <= nbPoints; i++) {
  2886. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));
  2887. }
  2888. return new Curve3(bez);
  2889. };
  2890. // HermiteSpline(origin_V3, originTangent_V3, destination_V3, destinationTangent_V3, nbPoints)
  2891. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  2892. var hermite = new Array();
  2893. var step = 1 / nbPoints;
  2894. for (var i = 0; i <= nbPoints; i++) {
  2895. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  2896. }
  2897. return new Curve3(hermite);
  2898. };
  2899. Curve3.prototype.getPoints = function () {
  2900. return this._points;
  2901. };
  2902. Curve3.prototype.length = function () {
  2903. return this._length;
  2904. };
  2905. Curve3.prototype.continue = function (curve) {
  2906. var lastPoint = this._points[this._points.length - 1];
  2907. var continuedPoints = this._points.slice();
  2908. var curvePoints = curve.getPoints();
  2909. for (var i = 1; i < curvePoints.length; i++) {
  2910. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  2911. }
  2912. var continuedCurve = new Curve3(continuedPoints);
  2913. return continuedCurve;
  2914. };
  2915. Curve3.prototype._computeLength = function (path) {
  2916. var l = 0;
  2917. for (var i = 1; i < path.length; i++) {
  2918. l += (path[i].subtract(path[i - 1])).length();
  2919. }
  2920. return l;
  2921. };
  2922. return Curve3;
  2923. })();
  2924. BABYLON.Curve3 = Curve3;
  2925. // SphericalHarmonics
  2926. var SphericalHarmonics = (function () {
  2927. function SphericalHarmonics() {
  2928. this.L00 = Vector3.Zero();
  2929. this.L1_1 = Vector3.Zero();
  2930. this.L10 = Vector3.Zero();
  2931. this.L11 = Vector3.Zero();
  2932. this.L2_2 = Vector3.Zero();
  2933. this.L2_1 = Vector3.Zero();
  2934. this.L20 = Vector3.Zero();
  2935. this.L21 = Vector3.Zero();
  2936. this.L22 = Vector3.Zero();
  2937. }
  2938. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  2939. var colorVector = new Vector3(color.r, color.g, color.b);
  2940. var c = colorVector.scale(deltaSolidAngle);
  2941. this.L00 = this.L00.add(c.scale(0.282095));
  2942. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  2943. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  2944. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  2945. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  2946. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  2947. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  2948. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  2949. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  2950. };
  2951. SphericalHarmonics.prototype.scale = function (scale) {
  2952. this.L00 = this.L00.scale(scale);
  2953. this.L1_1 = this.L1_1.scale(scale);
  2954. this.L10 = this.L10.scale(scale);
  2955. this.L11 = this.L11.scale(scale);
  2956. this.L2_2 = this.L2_2.scale(scale);
  2957. this.L2_1 = this.L2_1.scale(scale);
  2958. this.L20 = this.L20.scale(scale);
  2959. this.L21 = this.L21.scale(scale);
  2960. this.L22 = this.L22.scale(scale);
  2961. };
  2962. return SphericalHarmonics;
  2963. })();
  2964. BABYLON.SphericalHarmonics = SphericalHarmonics;
  2965. // SphericalPolynomial
  2966. var SphericalPolynomial = (function () {
  2967. function SphericalPolynomial() {
  2968. this.x = Vector3.Zero();
  2969. this.y = Vector3.Zero();
  2970. this.z = Vector3.Zero();
  2971. this.xx = Vector3.Zero();
  2972. this.yy = Vector3.Zero();
  2973. this.zz = Vector3.Zero();
  2974. this.xy = Vector3.Zero();
  2975. this.yz = Vector3.Zero();
  2976. this.zx = Vector3.Zero();
  2977. }
  2978. SphericalPolynomial.prototype.addAmbient = function (color) {
  2979. var colorVector = new Vector3(color.r, color.g, color.b);
  2980. this.xx = this.xx.add(colorVector);
  2981. this.yy = this.yy.add(colorVector);
  2982. this.zz = this.zz.add(colorVector);
  2983. };
  2984. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  2985. var result = new SphericalPolynomial();
  2986. result.x = harmonics.L11.scale(1.02333);
  2987. result.y = harmonics.L1_1.scale(1.02333);
  2988. result.z = harmonics.L10.scale(1.02333);
  2989. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  2990. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  2991. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  2992. result.yz = harmonics.L2_1.scale(0.858086);
  2993. result.zx = harmonics.L21.scale(0.858086);
  2994. result.xy = harmonics.L2_2.scale(0.858086);
  2995. return result;
  2996. };
  2997. return SphericalPolynomial;
  2998. })();
  2999. BABYLON.SphericalPolynomial = SphericalPolynomial;
  3000. // Vertex formats
  3001. var PositionNormalVertex = (function () {
  3002. function PositionNormalVertex(position, normal) {
  3003. if (position === void 0) { position = Vector3.Zero(); }
  3004. if (normal === void 0) { normal = Vector3.Up(); }
  3005. this.position = position;
  3006. this.normal = normal;
  3007. }
  3008. PositionNormalVertex.prototype.clone = function () {
  3009. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  3010. };
  3011. return PositionNormalVertex;
  3012. })();
  3013. BABYLON.PositionNormalVertex = PositionNormalVertex;
  3014. var PositionNormalTextureVertex = (function () {
  3015. function PositionNormalTextureVertex(position, normal, uv) {
  3016. if (position === void 0) { position = Vector3.Zero(); }
  3017. if (normal === void 0) { normal = Vector3.Up(); }
  3018. if (uv === void 0) { uv = Vector2.Zero(); }
  3019. this.position = position;
  3020. this.normal = normal;
  3021. this.uv = uv;
  3022. }
  3023. PositionNormalTextureVertex.prototype.clone = function () {
  3024. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  3025. };
  3026. return PositionNormalTextureVertex;
  3027. })();
  3028. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  3029. // Temporary pre-allocated objects for engine internal use
  3030. // usage in any internal function :
  3031. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  3032. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  3033. var Tmp = (function () {
  3034. function Tmp() {
  3035. }
  3036. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  3037. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  3038. Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 6 temp Vector3 at once should be enough
  3039. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  3040. Tmp.Quaternion = [new Quaternion(0, 0, 0, 0)]; // 1 temp Quaternion at once should be enough
  3041. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  3042. Matrix.Zero(), Matrix.Zero(),
  3043. Matrix.Zero(), Matrix.Zero(),
  3044. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  3045. return Tmp;
  3046. })();
  3047. BABYLON.Tmp = Tmp;
  3048. })(BABYLON || (BABYLON = {}));
  3049. var BABYLON;
  3050. (function (BABYLON) {
  3051. var Database = (function () {
  3052. function Database(urlToScene, callbackManifestChecked) {
  3053. // Handling various flavors of prefixed version of IndexedDB
  3054. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  3055. this.callbackManifestChecked = callbackManifestChecked;
  3056. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  3057. this.db = null;
  3058. this.enableSceneOffline = false;
  3059. this.enableTexturesOffline = false;
  3060. this.manifestVersionFound = 0;
  3061. this.mustUpdateRessources = false;
  3062. this.hasReachedQuota = false;
  3063. if (!Database.IDBStorageEnabled) {
  3064. this.callbackManifestChecked(true);
  3065. }
  3066. else {
  3067. this.checkManifestFile();
  3068. }
  3069. }
  3070. Database.prototype.checkManifestFile = function () {
  3071. var _this = this;
  3072. function noManifestFile() {
  3073. that.enableSceneOffline = false;
  3074. that.enableTexturesOffline = false;
  3075. that.callbackManifestChecked(false);
  3076. }
  3077. var that = this;
  3078. var timeStampUsed = false;
  3079. var manifestURL = this.currentSceneUrl + ".manifest";
  3080. var xhr = new XMLHttpRequest();
  3081. if (navigator.onLine) {
  3082. // Adding a timestamp to by-pass browsers' cache
  3083. timeStampUsed = true;
  3084. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  3085. }
  3086. xhr.open("GET", manifestURL, true);
  3087. xhr.addEventListener("load", function () {
  3088. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  3089. try {
  3090. var manifestFile = JSON.parse(xhr.response);
  3091. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  3092. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  3093. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  3094. _this.manifestVersionFound = manifestFile.version;
  3095. }
  3096. if (_this.callbackManifestChecked) {
  3097. _this.callbackManifestChecked(true);
  3098. }
  3099. }
  3100. catch (ex) {
  3101. noManifestFile();
  3102. }
  3103. }
  3104. else {
  3105. noManifestFile();
  3106. }
  3107. }, false);
  3108. xhr.addEventListener("error", function (event) {
  3109. if (timeStampUsed) {
  3110. timeStampUsed = false;
  3111. // Let's retry without the timeStamp
  3112. // It could fail when coupled with HTML5 Offline API
  3113. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  3114. xhr.open("GET", retryManifestURL, true);
  3115. xhr.send();
  3116. }
  3117. else {
  3118. noManifestFile();
  3119. }
  3120. }, false);
  3121. try {
  3122. xhr.send();
  3123. }
  3124. catch (ex) {
  3125. BABYLON.Tools.Error("Error on XHR send request.");
  3126. that.callbackManifestChecked(false);
  3127. }
  3128. };
  3129. Database.prototype.openAsync = function (successCallback, errorCallback) {
  3130. var _this = this;
  3131. function handleError() {
  3132. that.isSupported = false;
  3133. if (errorCallback)
  3134. errorCallback();
  3135. }
  3136. var that = this;
  3137. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  3138. // Your browser doesn't support IndexedDB
  3139. this.isSupported = false;
  3140. if (errorCallback)
  3141. errorCallback();
  3142. }
  3143. else {
  3144. // If the DB hasn't been opened or created yet
  3145. if (!this.db) {
  3146. this.hasReachedQuota = false;
  3147. this.isSupported = true;
  3148. var request = this.idbFactory.open("babylonjs", 1);
  3149. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3150. request.onerror = function (event) {
  3151. handleError();
  3152. };
  3153. // executes when a version change transaction cannot complete due to other active transactions
  3154. request.onblocked = function (event) {
  3155. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3156. handleError();
  3157. };
  3158. // DB has been opened successfully
  3159. request.onsuccess = function (event) {
  3160. _this.db = request.result;
  3161. successCallback();
  3162. };
  3163. // Initialization of the DB. Creating Scenes & Textures stores
  3164. request.onupgradeneeded = function (event) {
  3165. _this.db = (event.target).result;
  3166. try {
  3167. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3168. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3169. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3170. }
  3171. catch (ex) {
  3172. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3173. handleError();
  3174. }
  3175. };
  3176. }
  3177. else {
  3178. if (successCallback)
  3179. successCallback();
  3180. }
  3181. }
  3182. };
  3183. Database.prototype.loadImageFromDB = function (url, image) {
  3184. var _this = this;
  3185. var completeURL = Database.ReturnFullUrlLocation(url);
  3186. var saveAndLoadImage = function () {
  3187. if (!_this.hasReachedQuota && _this.db !== null) {
  3188. // the texture is not yet in the DB, let's try to save it
  3189. _this._saveImageIntoDBAsync(completeURL, image);
  3190. }
  3191. else {
  3192. image.src = url;
  3193. }
  3194. };
  3195. if (!this.mustUpdateRessources) {
  3196. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3197. }
  3198. else {
  3199. saveAndLoadImage();
  3200. }
  3201. };
  3202. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3203. if (this.isSupported && this.db !== null) {
  3204. var texture;
  3205. var transaction = this.db.transaction(["textures"]);
  3206. transaction.onabort = function (event) {
  3207. image.src = url;
  3208. };
  3209. transaction.oncomplete = function (event) {
  3210. var blobTextureURL;
  3211. if (texture) {
  3212. var URL = window.URL || window.webkitURL;
  3213. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3214. image.onerror = function () {
  3215. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3216. image.src = url;
  3217. };
  3218. image.src = blobTextureURL;
  3219. }
  3220. else {
  3221. notInDBCallback();
  3222. }
  3223. };
  3224. var getRequest = transaction.objectStore("textures").get(url);
  3225. getRequest.onsuccess = function (event) {
  3226. texture = (event.target).result;
  3227. };
  3228. getRequest.onerror = function (event) {
  3229. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3230. image.src = url;
  3231. };
  3232. }
  3233. else {
  3234. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3235. image.src = url;
  3236. }
  3237. };
  3238. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3239. var _this = this;
  3240. if (this.isSupported) {
  3241. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3242. var generateBlobUrl = function () {
  3243. var blobTextureURL;
  3244. if (blob) {
  3245. var URL = window.URL || window.webkitURL;
  3246. try {
  3247. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3248. }
  3249. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3250. catch (ex) {
  3251. blobTextureURL = URL.createObjectURL(blob);
  3252. }
  3253. }
  3254. image.src = blobTextureURL;
  3255. };
  3256. if (Database.IsUASupportingBlobStorage) {
  3257. var xhr = new XMLHttpRequest(), blob;
  3258. xhr.open("GET", url, true);
  3259. xhr.responseType = "blob";
  3260. xhr.addEventListener("load", function () {
  3261. if (xhr.status === 200) {
  3262. // Blob as response (XHR2)
  3263. blob = xhr.response;
  3264. var transaction = _this.db.transaction(["textures"], "readwrite");
  3265. // the transaction could abort because of a QuotaExceededError error
  3266. transaction.onabort = function (event) {
  3267. try {
  3268. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3269. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3270. this.hasReachedQuota = true;
  3271. }
  3272. }
  3273. catch (ex) { }
  3274. generateBlobUrl();
  3275. };
  3276. transaction.oncomplete = function (event) {
  3277. generateBlobUrl();
  3278. };
  3279. var newTexture = { textureUrl: url, data: blob };
  3280. try {
  3281. // Put the blob into the dabase
  3282. var addRequest = transaction.objectStore("textures").put(newTexture);
  3283. addRequest.onsuccess = function (event) {
  3284. };
  3285. addRequest.onerror = function (event) {
  3286. generateBlobUrl();
  3287. };
  3288. }
  3289. catch (ex) {
  3290. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3291. if (ex.code === 25) {
  3292. Database.IsUASupportingBlobStorage = false;
  3293. }
  3294. image.src = url;
  3295. }
  3296. }
  3297. else {
  3298. image.src = url;
  3299. }
  3300. }, false);
  3301. xhr.addEventListener("error", function (event) {
  3302. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3303. image.src = url;
  3304. }, false);
  3305. xhr.send();
  3306. }
  3307. else {
  3308. image.src = url;
  3309. }
  3310. }
  3311. else {
  3312. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3313. image.src = url;
  3314. }
  3315. };
  3316. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3317. var _this = this;
  3318. var updateVersion = function (event) {
  3319. // the version is not yet in the DB or we need to update it
  3320. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3321. };
  3322. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3323. };
  3324. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3325. var _this = this;
  3326. if (this.isSupported) {
  3327. var version;
  3328. try {
  3329. var transaction = this.db.transaction(["versions"]);
  3330. transaction.oncomplete = function (event) {
  3331. if (version) {
  3332. // If the version in the JSON file is > than the version in DB
  3333. if (_this.manifestVersionFound > version.data) {
  3334. _this.mustUpdateRessources = true;
  3335. updateInDBCallback();
  3336. }
  3337. else {
  3338. callback(version.data);
  3339. }
  3340. }
  3341. else {
  3342. _this.mustUpdateRessources = true;
  3343. updateInDBCallback();
  3344. }
  3345. };
  3346. transaction.onabort = function (event) {
  3347. callback(-1);
  3348. };
  3349. var getRequest = transaction.objectStore("versions").get(url);
  3350. getRequest.onsuccess = function (event) {
  3351. version = (event.target).result;
  3352. };
  3353. getRequest.onerror = function (event) {
  3354. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3355. callback(-1);
  3356. };
  3357. }
  3358. catch (ex) {
  3359. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3360. callback(-1);
  3361. }
  3362. }
  3363. else {
  3364. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3365. callback(-1);
  3366. }
  3367. };
  3368. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3369. var _this = this;
  3370. if (this.isSupported && !this.hasReachedQuota) {
  3371. try {
  3372. // Open a transaction to the database
  3373. var transaction = this.db.transaction(["versions"], "readwrite");
  3374. // the transaction could abort because of a QuotaExceededError error
  3375. transaction.onabort = function (event) {
  3376. try {
  3377. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3378. _this.hasReachedQuota = true;
  3379. }
  3380. }
  3381. catch (ex) { }
  3382. callback(-1);
  3383. };
  3384. transaction.oncomplete = function (event) {
  3385. callback(_this.manifestVersionFound);
  3386. };
  3387. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3388. // Put the scene into the database
  3389. var addRequest = transaction.objectStore("versions").put(newVersion);
  3390. addRequest.onsuccess = function (event) {
  3391. };
  3392. addRequest.onerror = function (event) {
  3393. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3394. };
  3395. }
  3396. catch (ex) {
  3397. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3398. callback(-1);
  3399. }
  3400. }
  3401. else {
  3402. callback(-1);
  3403. }
  3404. };
  3405. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3406. var _this = this;
  3407. var completeUrl = Database.ReturnFullUrlLocation(url);
  3408. var saveAndLoadFile = function (event) {
  3409. // the scene is not yet in the DB, let's try to save it
  3410. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3411. };
  3412. this._checkVersionFromDB(completeUrl, function (version) {
  3413. if (version !== -1) {
  3414. if (!_this.mustUpdateRessources) {
  3415. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3416. }
  3417. else {
  3418. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3419. }
  3420. }
  3421. else {
  3422. errorCallback();
  3423. }
  3424. });
  3425. };
  3426. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3427. if (this.isSupported) {
  3428. var targetStore;
  3429. if (url.indexOf(".babylon") !== -1) {
  3430. targetStore = "scenes";
  3431. }
  3432. else {
  3433. targetStore = "textures";
  3434. }
  3435. var file;
  3436. var transaction = this.db.transaction([targetStore]);
  3437. transaction.oncomplete = function (event) {
  3438. if (file) {
  3439. callback(file.data);
  3440. }
  3441. else {
  3442. notInDBCallback();
  3443. }
  3444. };
  3445. transaction.onabort = function (event) {
  3446. notInDBCallback();
  3447. };
  3448. var getRequest = transaction.objectStore(targetStore).get(url);
  3449. getRequest.onsuccess = function (event) {
  3450. file = (event.target).result;
  3451. };
  3452. getRequest.onerror = function (event) {
  3453. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3454. notInDBCallback();
  3455. };
  3456. }
  3457. else {
  3458. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3459. callback();
  3460. }
  3461. };
  3462. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3463. var _this = this;
  3464. if (this.isSupported) {
  3465. var targetStore;
  3466. if (url.indexOf(".babylon") !== -1) {
  3467. targetStore = "scenes";
  3468. }
  3469. else {
  3470. targetStore = "textures";
  3471. }
  3472. // Create XHR
  3473. var xhr = new XMLHttpRequest(), fileData;
  3474. xhr.open("GET", url, true);
  3475. if (useArrayBuffer) {
  3476. xhr.responseType = "arraybuffer";
  3477. }
  3478. xhr.onprogress = progressCallback;
  3479. xhr.addEventListener("load", function () {
  3480. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  3481. // Blob as response (XHR2)
  3482. //fileData = xhr.responseText;
  3483. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  3484. if (!_this.hasReachedQuota) {
  3485. // Open a transaction to the database
  3486. var transaction = _this.db.transaction([targetStore], "readwrite");
  3487. // the transaction could abort because of a QuotaExceededError error
  3488. transaction.onabort = function (event) {
  3489. try {
  3490. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3491. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3492. this.hasReachedQuota = true;
  3493. }
  3494. }
  3495. catch (ex) { }
  3496. callback(fileData);
  3497. };
  3498. transaction.oncomplete = function (event) {
  3499. callback(fileData);
  3500. };
  3501. var newFile;
  3502. if (targetStore === "scenes") {
  3503. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  3504. }
  3505. else {
  3506. newFile = { textureUrl: url, data: fileData };
  3507. }
  3508. try {
  3509. // Put the scene into the database
  3510. var addRequest = transaction.objectStore(targetStore).put(newFile);
  3511. addRequest.onsuccess = function (event) {
  3512. };
  3513. addRequest.onerror = function (event) {
  3514. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  3515. };
  3516. }
  3517. catch (ex) {
  3518. callback(fileData);
  3519. }
  3520. }
  3521. else {
  3522. callback(fileData);
  3523. }
  3524. }
  3525. else {
  3526. callback();
  3527. }
  3528. }, false);
  3529. xhr.addEventListener("error", function (event) {
  3530. BABYLON.Tools.Error("error on XHR request.");
  3531. callback();
  3532. }, false);
  3533. xhr.send();
  3534. }
  3535. else {
  3536. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3537. callback();
  3538. }
  3539. };
  3540. Database.IsUASupportingBlobStorage = true;
  3541. Database.IDBStorageEnabled = true;
  3542. Database.parseURL = function (url) {
  3543. var a = document.createElement('a');
  3544. a.href = url;
  3545. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  3546. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  3547. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  3548. return absLocation;
  3549. };
  3550. Database.ReturnFullUrlLocation = function (url) {
  3551. if (url.indexOf("http:/") === -1) {
  3552. return (Database.parseURL(window.location.href) + url);
  3553. }
  3554. else {
  3555. return url;
  3556. }
  3557. };
  3558. return Database;
  3559. })();
  3560. BABYLON.Database = Database;
  3561. })(BABYLON || (BABYLON = {}));
  3562. var BABYLON;
  3563. (function (BABYLON) {
  3564. var Internals;
  3565. (function (Internals) {
  3566. /*
  3567. * Based on jsTGALoader - Javascript loader for TGA file
  3568. * By Vincent Thibault
  3569. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  3570. */
  3571. var TGATools = (function () {
  3572. function TGATools() {
  3573. }
  3574. TGATools.GetTGAHeader = function (data) {
  3575. var offset = 0;
  3576. var header = {
  3577. id_length: data[offset++],
  3578. colormap_type: data[offset++],
  3579. image_type: data[offset++],
  3580. colormap_index: data[offset++] | data[offset++] << 8,
  3581. colormap_length: data[offset++] | data[offset++] << 8,
  3582. colormap_size: data[offset++],
  3583. origin: [
  3584. data[offset++] | data[offset++] << 8,
  3585. data[offset++] | data[offset++] << 8
  3586. ],
  3587. width: data[offset++] | data[offset++] << 8,
  3588. height: data[offset++] | data[offset++] << 8,
  3589. pixel_size: data[offset++],
  3590. flags: data[offset++]
  3591. };
  3592. return header;
  3593. };
  3594. TGATools.UploadContent = function (gl, data) {
  3595. // Not enough data to contain header ?
  3596. if (data.length < 19) {
  3597. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  3598. return;
  3599. }
  3600. // Read Header
  3601. var offset = 18;
  3602. var header = TGATools.GetTGAHeader(data);
  3603. // Assume it's a valid Targa file.
  3604. if (header.id_length + offset > data.length) {
  3605. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  3606. return;
  3607. }
  3608. // Skip not needed data
  3609. offset += header.id_length;
  3610. var use_rle = false;
  3611. var use_pal = false;
  3612. var use_rgb = false;
  3613. var use_grey = false;
  3614. // Get some informations.
  3615. switch (header.image_type) {
  3616. case TGATools._TYPE_RLE_INDEXED:
  3617. use_rle = true;
  3618. case TGATools._TYPE_INDEXED:
  3619. use_pal = true;
  3620. break;
  3621. case TGATools._TYPE_RLE_RGB:
  3622. use_rle = true;
  3623. case TGATools._TYPE_RGB:
  3624. use_rgb = true;
  3625. break;
  3626. case TGATools._TYPE_RLE_GREY:
  3627. use_rle = true;
  3628. case TGATools._TYPE_GREY:
  3629. use_grey = true;
  3630. break;
  3631. }
  3632. var pixel_data;
  3633. var numAlphaBits = header.flags & 0xf;
  3634. var pixel_size = header.pixel_size >> 3;
  3635. var pixel_total = header.width * header.height * pixel_size;
  3636. // Read palettes
  3637. var palettes;
  3638. if (use_pal) {
  3639. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  3640. }
  3641. // Read LRE
  3642. if (use_rle) {
  3643. pixel_data = new Uint8Array(pixel_total);
  3644. var c, count, i;
  3645. var localOffset = 0;
  3646. var pixels = new Uint8Array(pixel_size);
  3647. while (offset < pixel_total && localOffset < pixel_total) {
  3648. c = data[offset++];
  3649. count = (c & 0x7f) + 1;
  3650. // RLE pixels
  3651. if (c & 0x80) {
  3652. // Bind pixel tmp array
  3653. for (i = 0; i < pixel_size; ++i) {
  3654. pixels[i] = data[offset++];
  3655. }
  3656. // Copy pixel array
  3657. for (i = 0; i < count; ++i) {
  3658. pixel_data.set(pixels, localOffset + i * pixel_size);
  3659. }
  3660. localOffset += pixel_size * count;
  3661. }
  3662. else {
  3663. count *= pixel_size;
  3664. for (i = 0; i < count; ++i) {
  3665. pixel_data[localOffset + i] = data[offset++];
  3666. }
  3667. localOffset += count;
  3668. }
  3669. }
  3670. }
  3671. else {
  3672. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  3673. }
  3674. // Load to texture
  3675. var x_start, y_start, x_step, y_step, y_end, x_end;
  3676. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  3677. default:
  3678. case TGATools._ORIGIN_UL:
  3679. x_start = 0;
  3680. x_step = 1;
  3681. x_end = header.width;
  3682. y_start = 0;
  3683. y_step = 1;
  3684. y_end = header.height;
  3685. break;
  3686. case TGATools._ORIGIN_BL:
  3687. x_start = 0;
  3688. x_step = 1;
  3689. x_end = header.width;
  3690. y_start = header.height - 1;
  3691. y_step = -1;
  3692. y_end = -1;
  3693. break;
  3694. case TGATools._ORIGIN_UR:
  3695. x_start = header.width - 1;
  3696. x_step = -1;
  3697. x_end = -1;
  3698. y_start = 0;
  3699. y_step = 1;
  3700. y_end = header.height;
  3701. break;
  3702. case TGATools._ORIGIN_BR:
  3703. x_start = header.width - 1;
  3704. x_step = -1;
  3705. x_end = -1;
  3706. y_start = header.height - 1;
  3707. y_step = -1;
  3708. y_end = -1;
  3709. break;
  3710. }
  3711. // Load the specify method
  3712. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  3713. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  3714. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  3715. };
  3716. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3717. var image = pixel_data, colormap = palettes;
  3718. var width = header.width, height = header.height;
  3719. var color, i = 0, x, y;
  3720. var imageData = new Uint8Array(width * height * 4);
  3721. for (y = y_start; y !== y_end; y += y_step) {
  3722. for (x = x_start; x !== x_end; x += x_step, i++) {
  3723. color = image[i];
  3724. imageData[(x + width * y) * 4 + 3] = 255;
  3725. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  3726. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  3727. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  3728. }
  3729. }
  3730. return imageData;
  3731. };
  3732. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3733. var image = pixel_data;
  3734. var width = header.width, height = header.height;
  3735. var color, i = 0, x, y;
  3736. var imageData = new Uint8Array(width * height * 4);
  3737. for (y = y_start; y !== y_end; y += y_step) {
  3738. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3739. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  3740. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  3741. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  3742. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  3743. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  3744. }
  3745. }
  3746. return imageData;
  3747. };
  3748. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3749. var image = pixel_data;
  3750. var width = header.width, height = header.height;
  3751. var i = 0, x, y;
  3752. var imageData = new Uint8Array(width * height * 4);
  3753. for (y = y_start; y !== y_end; y += y_step) {
  3754. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  3755. imageData[(x + width * y) * 4 + 3] = 255;
  3756. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3757. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3758. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3759. }
  3760. }
  3761. return imageData;
  3762. };
  3763. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3764. var image = pixel_data;
  3765. var width = header.width, height = header.height;
  3766. var i = 0, x, y;
  3767. var imageData = new Uint8Array(width * height * 4);
  3768. for (y = y_start; y !== y_end; y += y_step) {
  3769. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  3770. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3771. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3772. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3773. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  3774. }
  3775. }
  3776. return imageData;
  3777. };
  3778. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3779. var image = pixel_data;
  3780. var width = header.width, height = header.height;
  3781. var color, i = 0, x, y;
  3782. var imageData = new Uint8Array(width * height * 4);
  3783. for (y = y_start; y !== y_end; y += y_step) {
  3784. for (x = x_start; x !== x_end; x += x_step, i++) {
  3785. color = image[i];
  3786. imageData[(x + width * y) * 4 + 0] = color;
  3787. imageData[(x + width * y) * 4 + 1] = color;
  3788. imageData[(x + width * y) * 4 + 2] = color;
  3789. imageData[(x + width * y) * 4 + 3] = 255;
  3790. }
  3791. }
  3792. return imageData;
  3793. };
  3794. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3795. var image = pixel_data;
  3796. var width = header.width, height = header.height;
  3797. var i = 0, x, y;
  3798. var imageData = new Uint8Array(width * height * 4);
  3799. for (y = y_start; y !== y_end; y += y_step) {
  3800. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3801. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  3802. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  3803. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3804. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  3805. }
  3806. }
  3807. return imageData;
  3808. };
  3809. TGATools._TYPE_NO_DATA = 0;
  3810. TGATools._TYPE_INDEXED = 1;
  3811. TGATools._TYPE_RGB = 2;
  3812. TGATools._TYPE_GREY = 3;
  3813. TGATools._TYPE_RLE_INDEXED = 9;
  3814. TGATools._TYPE_RLE_RGB = 10;
  3815. TGATools._TYPE_RLE_GREY = 11;
  3816. TGATools._ORIGIN_MASK = 0x30;
  3817. TGATools._ORIGIN_SHIFT = 0x04;
  3818. TGATools._ORIGIN_BL = 0x00;
  3819. TGATools._ORIGIN_BR = 0x01;
  3820. TGATools._ORIGIN_UL = 0x02;
  3821. TGATools._ORIGIN_UR = 0x03;
  3822. return TGATools;
  3823. })();
  3824. Internals.TGATools = TGATools;
  3825. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  3826. })(BABYLON || (BABYLON = {}));
  3827. var BABYLON;
  3828. (function (BABYLON) {
  3829. var SmartArray = (function () {
  3830. function SmartArray(capacity) {
  3831. this.length = 0;
  3832. this._duplicateId = 0;
  3833. this.data = new Array(capacity);
  3834. this._id = SmartArray._GlobalId++;
  3835. }
  3836. SmartArray.prototype.push = function (value) {
  3837. this.data[this.length++] = value;
  3838. if (this.length > this.data.length) {
  3839. this.data.length *= 2;
  3840. }
  3841. if (!value.__smartArrayFlags) {
  3842. value.__smartArrayFlags = {};
  3843. }
  3844. value.__smartArrayFlags[this._id] = this._duplicateId;
  3845. };
  3846. SmartArray.prototype.pushNoDuplicate = function (value) {
  3847. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  3848. return;
  3849. }
  3850. this.push(value);
  3851. };
  3852. SmartArray.prototype.sort = function (compareFn) {
  3853. this.data.sort(compareFn);
  3854. };
  3855. SmartArray.prototype.reset = function () {
  3856. this.length = 0;
  3857. this._duplicateId++;
  3858. };
  3859. SmartArray.prototype.concat = function (array) {
  3860. if (array.length === 0) {
  3861. return;
  3862. }
  3863. if (this.length + array.length > this.data.length) {
  3864. this.data.length = (this.length + array.length) * 2;
  3865. }
  3866. for (var index = 0; index < array.length; index++) {
  3867. this.data[this.length++] = (array.data || array)[index];
  3868. }
  3869. };
  3870. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  3871. if (array.length === 0) {
  3872. return;
  3873. }
  3874. if (this.length + array.length > this.data.length) {
  3875. this.data.length = (this.length + array.length) * 2;
  3876. }
  3877. for (var index = 0; index < array.length; index++) {
  3878. var item = (array.data || array)[index];
  3879. this.pushNoDuplicate(item);
  3880. }
  3881. };
  3882. SmartArray.prototype.indexOf = function (value) {
  3883. var position = this.data.indexOf(value);
  3884. if (position >= this.length) {
  3885. return -1;
  3886. }
  3887. return position;
  3888. };
  3889. // Statics
  3890. SmartArray._GlobalId = 0;
  3891. return SmartArray;
  3892. })();
  3893. BABYLON.SmartArray = SmartArray;
  3894. })(BABYLON || (BABYLON = {}));
  3895. var BABYLON;
  3896. (function (BABYLON) {
  3897. var SmartCollection = (function () {
  3898. function SmartCollection(capacity) {
  3899. if (capacity === void 0) { capacity = 10; }
  3900. this.count = 0;
  3901. this._initialCapacity = capacity;
  3902. this.items = {};
  3903. this._keys = new Array(this._initialCapacity);
  3904. }
  3905. SmartCollection.prototype.add = function (key, item) {
  3906. if (this.items[key] != undefined) {
  3907. return -1;
  3908. }
  3909. this.items[key] = item;
  3910. //literal keys are always strings, but we keep source type of key in _keys array
  3911. this._keys[this.count++] = key;
  3912. if (this.count > this._keys.length) {
  3913. this._keys.length *= 2;
  3914. }
  3915. return this.count;
  3916. };
  3917. SmartCollection.prototype.remove = function (key) {
  3918. if (this.items[key] == undefined) {
  3919. return -1;
  3920. }
  3921. return this.removeItemOfIndex(this.indexOf(key));
  3922. };
  3923. SmartCollection.prototype.removeItemOfIndex = function (index) {
  3924. if (index < this.count && index > -1) {
  3925. delete this.items[this._keys[index]];
  3926. //here, shifting by hand is better optimised than .splice
  3927. while (index < this.count) {
  3928. this._keys[index] = this._keys[index + 1];
  3929. index++;
  3930. }
  3931. }
  3932. else {
  3933. return -1;
  3934. }
  3935. return --this.count;
  3936. };
  3937. SmartCollection.prototype.indexOf = function (key) {
  3938. for (var i = 0; i !== this.count; i++) {
  3939. if (this._keys[i] === key) {
  3940. return i;
  3941. }
  3942. }
  3943. return -1;
  3944. };
  3945. SmartCollection.prototype.item = function (key) {
  3946. return this.items[key];
  3947. };
  3948. SmartCollection.prototype.getAllKeys = function () {
  3949. if (this.count > 0) {
  3950. var keys = new Array(this.count);
  3951. for (var i = 0; i < this.count; i++) {
  3952. keys[i] = this._keys[i];
  3953. }
  3954. return keys;
  3955. }
  3956. else {
  3957. return undefined;
  3958. }
  3959. };
  3960. SmartCollection.prototype.getKeyByIndex = function (index) {
  3961. if (index < this.count && index > -1) {
  3962. return this._keys[index];
  3963. }
  3964. else {
  3965. return undefined;
  3966. }
  3967. };
  3968. SmartCollection.prototype.getItemByIndex = function (index) {
  3969. if (index < this.count && index > -1) {
  3970. return this.items[this._keys[index]];
  3971. }
  3972. else {
  3973. return undefined;
  3974. }
  3975. };
  3976. SmartCollection.prototype.empty = function () {
  3977. if (this.count > 0) {
  3978. this.count = 0;
  3979. this.items = {};
  3980. this._keys = new Array(this._initialCapacity);
  3981. }
  3982. };
  3983. SmartCollection.prototype.forEach = function (block) {
  3984. var key;
  3985. for (key in this.items) {
  3986. if (this.items.hasOwnProperty(key)) {
  3987. block(this.items[key]);
  3988. }
  3989. }
  3990. };
  3991. return SmartCollection;
  3992. })();
  3993. BABYLON.SmartCollection = SmartCollection;
  3994. })(BABYLON || (BABYLON = {}));
  3995. var BABYLON;
  3996. (function (BABYLON) {
  3997. // Screenshots
  3998. var screenshotCanvas;
  3999. var cloneValue = function (source, destinationObject) {
  4000. if (!source)
  4001. return null;
  4002. if (source instanceof BABYLON.Mesh) {
  4003. return null;
  4004. }
  4005. if (source instanceof BABYLON.SubMesh) {
  4006. return source.clone(destinationObject);
  4007. }
  4008. else if (source.clone) {
  4009. return source.clone();
  4010. }
  4011. return null;
  4012. };
  4013. var Tools = (function () {
  4014. function Tools() {
  4015. }
  4016. Tools.Instantiate = function (className) {
  4017. var arr = className.split(".");
  4018. var fn = (window || this);
  4019. for (var i = 0, len = arr.length; i < len; i++) {
  4020. fn = fn[arr[i]];
  4021. }
  4022. if (typeof fn !== "function") {
  4023. return null;
  4024. }
  4025. return fn;
  4026. };
  4027. Tools.GetConstructorName = function (obj) {
  4028. var str = (obj.prototype ? obj.prototype.constructor : obj.constructor).toString();
  4029. var cname = str.match(/function\s(\w*)/)[1];
  4030. var aliases = ["", "anonymous", "Anonymous"];
  4031. return aliases.indexOf(cname) > -1 ? "Function" : cname;
  4032. };
  4033. Tools.ToHex = function (i) {
  4034. var str = i.toString(16);
  4035. if (i <= 15) {
  4036. return ("0" + str).toUpperCase();
  4037. }
  4038. return str.toUpperCase();
  4039. };
  4040. Tools.SetImmediate = function (action) {
  4041. if (window.setImmediate) {
  4042. window.setImmediate(action);
  4043. }
  4044. else {
  4045. setTimeout(action, 1);
  4046. }
  4047. };
  4048. Tools.IsExponentOfTwo = function (value) {
  4049. var count = 1;
  4050. do {
  4051. count *= 2;
  4052. } while (count < value);
  4053. return count === value;
  4054. };
  4055. Tools.GetExponentOfTwo = function (value, max) {
  4056. var count = 1;
  4057. do {
  4058. count *= 2;
  4059. } while (count < value);
  4060. if (count > max)
  4061. count = max;
  4062. return count;
  4063. };
  4064. Tools.GetFilename = function (path) {
  4065. var index = path.lastIndexOf("/");
  4066. if (index < 0)
  4067. return path;
  4068. return path.substring(index + 1);
  4069. };
  4070. Tools.GetDOMTextContent = function (element) {
  4071. var result = "";
  4072. var child = element.firstChild;
  4073. while (child) {
  4074. if (child.nodeType === 3) {
  4075. result += child.textContent;
  4076. }
  4077. child = child.nextSibling;
  4078. }
  4079. return result;
  4080. };
  4081. Tools.ToDegrees = function (angle) {
  4082. return angle * 180 / Math.PI;
  4083. };
  4084. Tools.ToRadians = function (angle) {
  4085. return angle * Math.PI / 180;
  4086. };
  4087. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  4088. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  4089. var output = "";
  4090. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  4091. var i = 0;
  4092. var bytes = new Uint8Array(buffer);
  4093. while (i < bytes.length) {
  4094. chr1 = bytes[i++];
  4095. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  4096. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  4097. enc1 = chr1 >> 2;
  4098. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  4099. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  4100. enc4 = chr3 & 63;
  4101. if (isNaN(chr2)) {
  4102. enc3 = enc4 = 64;
  4103. }
  4104. else if (isNaN(chr3)) {
  4105. enc4 = 64;
  4106. }
  4107. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  4108. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  4109. }
  4110. return "data:image/png;base64," + output;
  4111. };
  4112. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  4113. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4114. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4115. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4116. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4117. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4118. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4119. }
  4120. return {
  4121. minimum: minimum,
  4122. maximum: maximum
  4123. };
  4124. };
  4125. Tools.ExtractMinAndMax = function (positions, start, count) {
  4126. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4127. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4128. for (var index = start; index < start + count; index++) {
  4129. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  4130. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4131. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4132. }
  4133. return {
  4134. minimum: minimum,
  4135. maximum: maximum
  4136. };
  4137. };
  4138. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4139. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4140. return undefined;
  4141. return Array.isArray(obj) ? obj : [obj];
  4142. };
  4143. // Misc.
  4144. Tools.GetPointerPrefix = function () {
  4145. var eventPrefix = "pointer";
  4146. // Check if pointer events are supported
  4147. if (!window.PointerEvent && !navigator.pointerEnabled) {
  4148. eventPrefix = "mouse";
  4149. }
  4150. return eventPrefix;
  4151. };
  4152. Tools.QueueNewFrame = function (func) {
  4153. if (window.requestAnimationFrame)
  4154. window.requestAnimationFrame(func);
  4155. else if (window.msRequestAnimationFrame)
  4156. window.msRequestAnimationFrame(func);
  4157. else if (window.webkitRequestAnimationFrame)
  4158. window.webkitRequestAnimationFrame(func);
  4159. else if (window.mozRequestAnimationFrame)
  4160. window.mozRequestAnimationFrame(func);
  4161. else if (window.oRequestAnimationFrame)
  4162. window.oRequestAnimationFrame(func);
  4163. else {
  4164. window.setTimeout(func, 16);
  4165. }
  4166. };
  4167. Tools.RequestFullscreen = function (element) {
  4168. if (element.requestFullscreen)
  4169. element.requestFullscreen();
  4170. else if (element.msRequestFullscreen)
  4171. element.msRequestFullscreen();
  4172. else if (element.webkitRequestFullscreen)
  4173. element.webkitRequestFullscreen();
  4174. else if (element.mozRequestFullScreen)
  4175. element.mozRequestFullScreen();
  4176. };
  4177. Tools.ExitFullscreen = function () {
  4178. if (document.exitFullscreen) {
  4179. document.exitFullscreen();
  4180. }
  4181. else if (document.mozCancelFullScreen) {
  4182. document.mozCancelFullScreen();
  4183. }
  4184. else if (document.webkitCancelFullScreen) {
  4185. document.webkitCancelFullScreen();
  4186. }
  4187. else if (document.msCancelFullScreen) {
  4188. document.msCancelFullScreen();
  4189. }
  4190. };
  4191. // External files
  4192. Tools.CleanUrl = function (url) {
  4193. url = url.replace(/#/mg, "%23");
  4194. return url;
  4195. };
  4196. Tools.LoadImage = function (url, onload, onerror, database) {
  4197. if (url instanceof ArrayBuffer) {
  4198. url = Tools.EncodeArrayBufferTobase64(url);
  4199. }
  4200. url = Tools.CleanUrl(url);
  4201. var img = new Image();
  4202. if (url.substr(0, 5) !== "data:") {
  4203. if (Tools.CorsBehavior) {
  4204. switch (typeof (Tools.CorsBehavior)) {
  4205. case "function":
  4206. var result = Tools.CorsBehavior(url);
  4207. if (result) {
  4208. img.crossOrigin = result;
  4209. }
  4210. break;
  4211. case "string":
  4212. default:
  4213. img.crossOrigin = Tools.CorsBehavior;
  4214. break;
  4215. }
  4216. }
  4217. }
  4218. img.onload = function () {
  4219. onload(img);
  4220. };
  4221. img.onerror = function (err) {
  4222. Tools.Error("Error while trying to load texture: " + url);
  4223. if (Tools.UseFallbackTexture) {
  4224. 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";
  4225. onload(img);
  4226. }
  4227. else {
  4228. onerror();
  4229. }
  4230. };
  4231. var noIndexedDB = function () {
  4232. img.src = url;
  4233. };
  4234. var loadFromIndexedDB = function () {
  4235. database.loadImageFromDB(url, img);
  4236. };
  4237. //ANY database to do!
  4238. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4239. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4240. }
  4241. else {
  4242. if (url.indexOf("file:") === -1) {
  4243. noIndexedDB();
  4244. }
  4245. else {
  4246. try {
  4247. var textureName = url.substring(5);
  4248. var blobURL;
  4249. try {
  4250. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4251. }
  4252. catch (ex) {
  4253. // Chrome doesn't support oneTimeOnly parameter
  4254. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4255. }
  4256. img.src = blobURL;
  4257. }
  4258. catch (e) {
  4259. img.src = null;
  4260. }
  4261. }
  4262. }
  4263. return img;
  4264. };
  4265. //ANY
  4266. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4267. url = Tools.CleanUrl(url);
  4268. var noIndexedDB = function () {
  4269. var request = new XMLHttpRequest();
  4270. var loadUrl = Tools.BaseUrl + url;
  4271. request.open('GET', loadUrl, true);
  4272. if (useArrayBuffer) {
  4273. request.responseType = "arraybuffer";
  4274. }
  4275. request.onprogress = progressCallBack;
  4276. request.onreadystatechange = function () {
  4277. if (request.readyState === 4) {
  4278. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  4279. callback(!useArrayBuffer ? request.responseText : request.response);
  4280. }
  4281. else {
  4282. if (onError) {
  4283. onError();
  4284. }
  4285. else {
  4286. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4287. }
  4288. }
  4289. }
  4290. };
  4291. request.send(null);
  4292. };
  4293. var loadFromIndexedDB = function () {
  4294. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4295. };
  4296. if (url.indexOf("file:") !== -1) {
  4297. var fileName = url.substring(5);
  4298. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  4299. }
  4300. else {
  4301. // Caching all files
  4302. if (database && database.enableSceneOffline) {
  4303. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4304. }
  4305. else {
  4306. noIndexedDB();
  4307. }
  4308. }
  4309. };
  4310. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4311. var reader = new FileReader();
  4312. reader.onload = function (e) {
  4313. //target doesn't have result from ts 1.3
  4314. callback(e.target['result']);
  4315. };
  4316. reader.onprogress = progressCallback;
  4317. reader.readAsDataURL(fileToLoad);
  4318. };
  4319. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4320. var reader = new FileReader();
  4321. reader.onerror = function (e) {
  4322. Tools.Log("Error while reading file: " + fileToLoad.name);
  4323. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  4324. };
  4325. reader.onload = function (e) {
  4326. //target doesn't have result from ts 1.3
  4327. callback(e.target['result']);
  4328. };
  4329. reader.onprogress = progressCallBack;
  4330. if (!useArrayBuffer) {
  4331. // Asynchronous read
  4332. reader.readAsText(fileToLoad);
  4333. }
  4334. else {
  4335. reader.readAsArrayBuffer(fileToLoad);
  4336. }
  4337. };
  4338. //returns a downloadable url to a file content.
  4339. Tools.FileAsURL = function (content) {
  4340. var fileBlob = new Blob([content]);
  4341. var url = window.URL || window.webkitURL;
  4342. var link = url.createObjectURL(fileBlob);
  4343. return link;
  4344. };
  4345. // Misc.
  4346. Tools.Clamp = function (value, min, max) {
  4347. if (min === void 0) { min = 0; }
  4348. if (max === void 0) { max = 1; }
  4349. return Math.min(max, Math.max(min, value));
  4350. };
  4351. // Returns -1 when value is a negative number and
  4352. // +1 when value is a positive number.
  4353. Tools.Sign = function (value) {
  4354. value = +value; // convert to a number
  4355. if (value === 0 || isNaN(value))
  4356. return value;
  4357. return value > 0 ? 1 : -1;
  4358. };
  4359. Tools.Format = function (value, decimals) {
  4360. if (decimals === void 0) { decimals = 2; }
  4361. return value.toFixed(decimals);
  4362. };
  4363. Tools.CheckExtends = function (v, min, max) {
  4364. if (v.x < min.x)
  4365. min.x = v.x;
  4366. if (v.y < min.y)
  4367. min.y = v.y;
  4368. if (v.z < min.z)
  4369. min.z = v.z;
  4370. if (v.x > max.x)
  4371. max.x = v.x;
  4372. if (v.y > max.y)
  4373. max.y = v.y;
  4374. if (v.z > max.z)
  4375. max.z = v.z;
  4376. };
  4377. Tools.WithinEpsilon = function (a, b, epsilon) {
  4378. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4379. var num = a - b;
  4380. return -epsilon <= num && num <= epsilon;
  4381. };
  4382. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4383. for (var prop in source) {
  4384. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4385. continue;
  4386. }
  4387. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4388. continue;
  4389. }
  4390. var sourceValue = source[prop];
  4391. var typeOfSourceValue = typeof sourceValue;
  4392. if (typeOfSourceValue === "function") {
  4393. continue;
  4394. }
  4395. if (typeOfSourceValue === "object") {
  4396. if (sourceValue instanceof Array) {
  4397. destination[prop] = [];
  4398. if (sourceValue.length > 0) {
  4399. if (typeof sourceValue[0] == "object") {
  4400. for (var index = 0; index < sourceValue.length; index++) {
  4401. var clonedValue = cloneValue(sourceValue[index], destination);
  4402. if (destination[prop].indexOf(clonedValue) === -1) {
  4403. destination[prop].push(clonedValue);
  4404. }
  4405. }
  4406. }
  4407. else {
  4408. destination[prop] = sourceValue.slice(0);
  4409. }
  4410. }
  4411. }
  4412. else {
  4413. destination[prop] = cloneValue(sourceValue, destination);
  4414. }
  4415. }
  4416. else {
  4417. destination[prop] = sourceValue;
  4418. }
  4419. }
  4420. };
  4421. Tools.IsEmpty = function (obj) {
  4422. for (var i in obj) {
  4423. return false;
  4424. }
  4425. return true;
  4426. };
  4427. Tools.RegisterTopRootEvents = function (events) {
  4428. for (var index = 0; index < events.length; index++) {
  4429. var event = events[index];
  4430. window.addEventListener(event.name, event.handler, false);
  4431. try {
  4432. if (window.parent) {
  4433. window.parent.addEventListener(event.name, event.handler, false);
  4434. }
  4435. }
  4436. catch (e) {
  4437. }
  4438. }
  4439. };
  4440. Tools.UnregisterTopRootEvents = function (events) {
  4441. for (var index = 0; index < events.length; index++) {
  4442. var event = events[index];
  4443. window.removeEventListener(event.name, event.handler);
  4444. try {
  4445. if (window.parent) {
  4446. window.parent.removeEventListener(event.name, event.handler);
  4447. }
  4448. }
  4449. catch (e) {
  4450. }
  4451. }
  4452. };
  4453. Tools.DumpFramebuffer = function (width, height, engine, successCallback) {
  4454. // Read the contents of the framebuffer
  4455. var numberOfChannelsByLine = width * 4;
  4456. var halfHeight = height / 2;
  4457. //Reading datas from WebGL
  4458. var data = engine.readPixels(0, 0, width, height);
  4459. //To flip image on Y axis.
  4460. for (var i = 0; i < halfHeight; i++) {
  4461. for (var j = 0; j < numberOfChannelsByLine; j++) {
  4462. var currentCell = j + i * numberOfChannelsByLine;
  4463. var targetLine = height - i - 1;
  4464. var targetCell = j + targetLine * numberOfChannelsByLine;
  4465. var temp = data[currentCell];
  4466. data[currentCell] = data[targetCell];
  4467. data[targetCell] = temp;
  4468. }
  4469. }
  4470. // Create a 2D canvas to store the result
  4471. if (!screenshotCanvas) {
  4472. screenshotCanvas = document.createElement('canvas');
  4473. }
  4474. screenshotCanvas.width = width;
  4475. screenshotCanvas.height = height;
  4476. var context = screenshotCanvas.getContext('2d');
  4477. // Copy the pixels to a 2D canvas
  4478. var imageData = context.createImageData(width, height);
  4479. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  4480. var castData = imageData.data;
  4481. castData.set(data);
  4482. context.putImageData(imageData, 0, 0);
  4483. var base64Image = screenshotCanvas.toDataURL();
  4484. if (successCallback) {
  4485. successCallback(base64Image);
  4486. }
  4487. else {
  4488. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  4489. if (("download" in document.createElement("a"))) {
  4490. var a = window.document.createElement("a");
  4491. a.href = base64Image;
  4492. var date = new Date();
  4493. var stringDate = date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  4494. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  4495. window.document.body.appendChild(a);
  4496. a.addEventListener("click", function () {
  4497. a.parentElement.removeChild(a);
  4498. });
  4499. a.click();
  4500. }
  4501. else {
  4502. var newWindow = window.open("");
  4503. var img = newWindow.document.createElement("img");
  4504. img.src = base64Image;
  4505. newWindow.document.body.appendChild(img);
  4506. }
  4507. }
  4508. };
  4509. Tools.CreateScreenshot = function (engine, camera, size, successCallback) {
  4510. var width;
  4511. var height;
  4512. //If a precision value is specified
  4513. if (size.precision) {
  4514. width = Math.round(engine.getRenderWidth() * size.precision);
  4515. height = Math.round(width / engine.getAspectRatio(camera));
  4516. size = { width: width, height: height };
  4517. }
  4518. else if (size.width && size.height) {
  4519. width = size.width;
  4520. height = size.height;
  4521. }
  4522. else if (size.width && !size.height) {
  4523. width = size.width;
  4524. height = Math.round(width / engine.getAspectRatio(camera));
  4525. size = { width: width, height: height };
  4526. }
  4527. else if (size.height && !size.width) {
  4528. height = size.height;
  4529. width = Math.round(height * engine.getAspectRatio(camera));
  4530. size = { width: width, height: height };
  4531. }
  4532. else if (!isNaN(size)) {
  4533. height = size;
  4534. width = size;
  4535. }
  4536. else {
  4537. Tools.Error("Invalid 'size' parameter !");
  4538. return;
  4539. }
  4540. var scene = camera.getScene();
  4541. var previousCamera = null;
  4542. if (scene.activeCamera !== camera) {
  4543. previousCamera = scene.activeCamera;
  4544. scene.activeCamera = camera;
  4545. }
  4546. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  4547. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  4548. texture.renderList = scene.meshes;
  4549. texture.onAfterRender = function () {
  4550. Tools.DumpFramebuffer(width, height, engine, successCallback);
  4551. };
  4552. scene.incrementRenderId();
  4553. texture.render(true);
  4554. texture.dispose();
  4555. if (previousCamera) {
  4556. scene.activeCamera = previousCamera;
  4557. }
  4558. camera.getProjectionMatrix(true); // Force cache refresh;
  4559. };
  4560. // XHR response validator for local file scenario
  4561. Tools.ValidateXHRData = function (xhr, dataType) {
  4562. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  4563. if (dataType === void 0) { dataType = 7; }
  4564. try {
  4565. if (dataType & 1) {
  4566. if (xhr.responseText && xhr.responseText.length > 0) {
  4567. return true;
  4568. }
  4569. else if (dataType === 1) {
  4570. return false;
  4571. }
  4572. }
  4573. if (dataType & 2) {
  4574. // Check header width and height since there is no "TGA" magic number
  4575. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  4576. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  4577. return true;
  4578. }
  4579. else if (dataType === 2) {
  4580. return false;
  4581. }
  4582. }
  4583. if (dataType & 4) {
  4584. // Check for the "DDS" magic number
  4585. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  4586. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  4587. return true;
  4588. }
  4589. else {
  4590. return false;
  4591. }
  4592. }
  4593. }
  4594. catch (e) {
  4595. }
  4596. return false;
  4597. };
  4598. Object.defineProperty(Tools, "NoneLogLevel", {
  4599. get: function () {
  4600. return Tools._NoneLogLevel;
  4601. },
  4602. enumerable: true,
  4603. configurable: true
  4604. });
  4605. Object.defineProperty(Tools, "MessageLogLevel", {
  4606. get: function () {
  4607. return Tools._MessageLogLevel;
  4608. },
  4609. enumerable: true,
  4610. configurable: true
  4611. });
  4612. Object.defineProperty(Tools, "WarningLogLevel", {
  4613. get: function () {
  4614. return Tools._WarningLogLevel;
  4615. },
  4616. enumerable: true,
  4617. configurable: true
  4618. });
  4619. Object.defineProperty(Tools, "ErrorLogLevel", {
  4620. get: function () {
  4621. return Tools._ErrorLogLevel;
  4622. },
  4623. enumerable: true,
  4624. configurable: true
  4625. });
  4626. Object.defineProperty(Tools, "AllLogLevel", {
  4627. get: function () {
  4628. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  4629. },
  4630. enumerable: true,
  4631. configurable: true
  4632. });
  4633. Tools._AddLogEntry = function (entry) {
  4634. Tools._LogCache = entry + Tools._LogCache;
  4635. if (Tools.OnNewCacheEntry) {
  4636. Tools.OnNewCacheEntry(entry);
  4637. }
  4638. };
  4639. Tools._FormatMessage = function (message) {
  4640. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  4641. var date = new Date();
  4642. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  4643. };
  4644. Tools._LogDisabled = function (message) {
  4645. // nothing to do
  4646. };
  4647. Tools._LogEnabled = function (message) {
  4648. var formattedMessage = Tools._FormatMessage(message);
  4649. console.log("BJS - " + formattedMessage);
  4650. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  4651. Tools._AddLogEntry(entry);
  4652. };
  4653. Tools._WarnDisabled = function (message) {
  4654. // nothing to do
  4655. };
  4656. Tools._WarnEnabled = function (message) {
  4657. var formattedMessage = Tools._FormatMessage(message);
  4658. console.warn("BJS - " + formattedMessage);
  4659. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  4660. Tools._AddLogEntry(entry);
  4661. };
  4662. Tools._ErrorDisabled = function (message) {
  4663. // nothing to do
  4664. };
  4665. Tools._ErrorEnabled = function (message) {
  4666. Tools.errorsCount++;
  4667. var formattedMessage = Tools._FormatMessage(message);
  4668. console.error("BJS - " + formattedMessage);
  4669. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  4670. Tools._AddLogEntry(entry);
  4671. };
  4672. Object.defineProperty(Tools, "LogCache", {
  4673. get: function () {
  4674. return Tools._LogCache;
  4675. },
  4676. enumerable: true,
  4677. configurable: true
  4678. });
  4679. Tools.ClearLogCache = function () {
  4680. Tools._LogCache = "";
  4681. Tools.errorsCount = 0;
  4682. };
  4683. Object.defineProperty(Tools, "LogLevels", {
  4684. set: function (level) {
  4685. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  4686. Tools.Log = Tools._LogEnabled;
  4687. }
  4688. else {
  4689. Tools.Log = Tools._LogDisabled;
  4690. }
  4691. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  4692. Tools.Warn = Tools._WarnEnabled;
  4693. }
  4694. else {
  4695. Tools.Warn = Tools._WarnDisabled;
  4696. }
  4697. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  4698. Tools.Error = Tools._ErrorEnabled;
  4699. }
  4700. else {
  4701. Tools.Error = Tools._ErrorDisabled;
  4702. }
  4703. },
  4704. enumerable: true,
  4705. configurable: true
  4706. });
  4707. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  4708. get: function () {
  4709. return Tools._PerformanceNoneLogLevel;
  4710. },
  4711. enumerable: true,
  4712. configurable: true
  4713. });
  4714. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  4715. get: function () {
  4716. return Tools._PerformanceUserMarkLogLevel;
  4717. },
  4718. enumerable: true,
  4719. configurable: true
  4720. });
  4721. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  4722. get: function () {
  4723. return Tools._PerformanceConsoleLogLevel;
  4724. },
  4725. enumerable: true,
  4726. configurable: true
  4727. });
  4728. Object.defineProperty(Tools, "PerformanceLogLevel", {
  4729. set: function (level) {
  4730. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  4731. Tools.StartPerformanceCounter = Tools._StartUserMark;
  4732. Tools.EndPerformanceCounter = Tools._EndUserMark;
  4733. return;
  4734. }
  4735. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  4736. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  4737. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  4738. return;
  4739. }
  4740. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4741. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4742. },
  4743. enumerable: true,
  4744. configurable: true
  4745. });
  4746. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  4747. };
  4748. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  4749. };
  4750. Tools._StartUserMark = function (counterName, condition) {
  4751. if (condition === void 0) { condition = true; }
  4752. if (!condition || !Tools._performance.mark) {
  4753. return;
  4754. }
  4755. Tools._performance.mark(counterName + "-Begin");
  4756. };
  4757. Tools._EndUserMark = function (counterName, condition) {
  4758. if (condition === void 0) { condition = true; }
  4759. if (!condition || !Tools._performance.mark) {
  4760. return;
  4761. }
  4762. Tools._performance.mark(counterName + "-End");
  4763. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  4764. };
  4765. Tools._StartPerformanceConsole = function (counterName, condition) {
  4766. if (condition === void 0) { condition = true; }
  4767. if (!condition) {
  4768. return;
  4769. }
  4770. Tools._StartUserMark(counterName, condition);
  4771. if (console.time) {
  4772. console.time(counterName);
  4773. }
  4774. };
  4775. Tools._EndPerformanceConsole = function (counterName, condition) {
  4776. if (condition === void 0) { condition = true; }
  4777. if (!condition) {
  4778. return;
  4779. }
  4780. Tools._EndUserMark(counterName, condition);
  4781. if (console.time) {
  4782. console.timeEnd(counterName);
  4783. }
  4784. };
  4785. Object.defineProperty(Tools, "Now", {
  4786. get: function () {
  4787. if (window.performance && window.performance.now) {
  4788. return window.performance.now();
  4789. }
  4790. return new Date().getTime();
  4791. },
  4792. enumerable: true,
  4793. configurable: true
  4794. });
  4795. Tools.BaseUrl = "";
  4796. Tools.CorsBehavior = "anonymous";
  4797. Tools.UseFallbackTexture = true;
  4798. // Logs
  4799. Tools._NoneLogLevel = 0;
  4800. Tools._MessageLogLevel = 1;
  4801. Tools._WarningLogLevel = 2;
  4802. Tools._ErrorLogLevel = 4;
  4803. Tools._LogCache = "";
  4804. Tools.errorsCount = 0;
  4805. Tools.Log = Tools._LogEnabled;
  4806. Tools.Warn = Tools._WarnEnabled;
  4807. Tools.Error = Tools._ErrorEnabled;
  4808. // Performances
  4809. Tools._PerformanceNoneLogLevel = 0;
  4810. Tools._PerformanceUserMarkLogLevel = 1;
  4811. Tools._PerformanceConsoleLogLevel = 2;
  4812. Tools._performance = window.performance;
  4813. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4814. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4815. return Tools;
  4816. })();
  4817. BABYLON.Tools = Tools;
  4818. /**
  4819. * An implementation of a loop for asynchronous functions.
  4820. */
  4821. var AsyncLoop = (function () {
  4822. /**
  4823. * Constroctor.
  4824. * @param iterations the number of iterations.
  4825. * @param _fn the function to run each iteration
  4826. * @param _successCallback the callback that will be called upon succesful execution
  4827. * @param offset starting offset.
  4828. */
  4829. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  4830. if (offset === void 0) { offset = 0; }
  4831. this.iterations = iterations;
  4832. this._fn = _fn;
  4833. this._successCallback = _successCallback;
  4834. this.index = offset - 1;
  4835. this._done = false;
  4836. }
  4837. /**
  4838. * Execute the next iteration. Must be called after the last iteration was finished.
  4839. */
  4840. AsyncLoop.prototype.executeNext = function () {
  4841. if (!this._done) {
  4842. if (this.index + 1 < this.iterations) {
  4843. ++this.index;
  4844. this._fn(this);
  4845. }
  4846. else {
  4847. this.breakLoop();
  4848. }
  4849. }
  4850. };
  4851. /**
  4852. * Break the loop and run the success callback.
  4853. */
  4854. AsyncLoop.prototype.breakLoop = function () {
  4855. this._done = true;
  4856. this._successCallback();
  4857. };
  4858. /**
  4859. * Helper function
  4860. */
  4861. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  4862. if (offset === void 0) { offset = 0; }
  4863. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  4864. loop.executeNext();
  4865. return loop;
  4866. };
  4867. /**
  4868. * A for-loop that will run a given number of iterations synchronous and the rest async.
  4869. * @param iterations total number of iterations
  4870. * @param syncedIterations number of synchronous iterations in each async iteration.
  4871. * @param fn the function to call each iteration.
  4872. * @param callback a success call back that will be called when iterating stops.
  4873. * @param breakFunction a break condition (optional)
  4874. * @param timeout timeout settings for the setTimeout function. default - 0.
  4875. * @constructor
  4876. */
  4877. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  4878. if (timeout === void 0) { timeout = 0; }
  4879. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  4880. if (breakFunction && breakFunction())
  4881. loop.breakLoop();
  4882. else {
  4883. setTimeout(function () {
  4884. for (var i = 0; i < syncedIterations; ++i) {
  4885. var iteration = (loop.index * syncedIterations) + i;
  4886. if (iteration >= iterations)
  4887. break;
  4888. fn(iteration);
  4889. if (breakFunction && breakFunction()) {
  4890. loop.breakLoop();
  4891. break;
  4892. }
  4893. }
  4894. loop.executeNext();
  4895. }, timeout);
  4896. }
  4897. }, callback);
  4898. };
  4899. return AsyncLoop;
  4900. })();
  4901. BABYLON.AsyncLoop = AsyncLoop;
  4902. })(BABYLON || (BABYLON = {}));
  4903. var BABYLON;
  4904. (function (BABYLON) {
  4905. var _DepthCullingState = (function () {
  4906. function _DepthCullingState() {
  4907. this._isDepthTestDirty = false;
  4908. this._isDepthMaskDirty = false;
  4909. this._isDepthFuncDirty = false;
  4910. this._isCullFaceDirty = false;
  4911. this._isCullDirty = false;
  4912. this._isZOffsetDirty = false;
  4913. }
  4914. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  4915. get: function () {
  4916. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  4917. },
  4918. enumerable: true,
  4919. configurable: true
  4920. });
  4921. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  4922. get: function () {
  4923. return this._zOffset;
  4924. },
  4925. set: function (value) {
  4926. if (this._zOffset === value) {
  4927. return;
  4928. }
  4929. this._zOffset = value;
  4930. this._isZOffsetDirty = true;
  4931. },
  4932. enumerable: true,
  4933. configurable: true
  4934. });
  4935. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  4936. get: function () {
  4937. return this._cullFace;
  4938. },
  4939. set: function (value) {
  4940. if (this._cullFace === value) {
  4941. return;
  4942. }
  4943. this._cullFace = value;
  4944. this._isCullFaceDirty = true;
  4945. },
  4946. enumerable: true,
  4947. configurable: true
  4948. });
  4949. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  4950. get: function () {
  4951. return this._cull;
  4952. },
  4953. set: function (value) {
  4954. if (this._cull === value) {
  4955. return;
  4956. }
  4957. this._cull = value;
  4958. this._isCullDirty = true;
  4959. },
  4960. enumerable: true,
  4961. configurable: true
  4962. });
  4963. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  4964. get: function () {
  4965. return this._depthFunc;
  4966. },
  4967. set: function (value) {
  4968. if (this._depthFunc === value) {
  4969. return;
  4970. }
  4971. this._depthFunc = value;
  4972. this._isDepthFuncDirty = true;
  4973. },
  4974. enumerable: true,
  4975. configurable: true
  4976. });
  4977. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  4978. get: function () {
  4979. return this._depthMask;
  4980. },
  4981. set: function (value) {
  4982. if (this._depthMask === value) {
  4983. return;
  4984. }
  4985. this._depthMask = value;
  4986. this._isDepthMaskDirty = true;
  4987. },
  4988. enumerable: true,
  4989. configurable: true
  4990. });
  4991. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  4992. get: function () {
  4993. return this._depthTest;
  4994. },
  4995. set: function (value) {
  4996. if (this._depthTest === value) {
  4997. return;
  4998. }
  4999. this._depthTest = value;
  5000. this._isDepthTestDirty = true;
  5001. },
  5002. enumerable: true,
  5003. configurable: true
  5004. });
  5005. _DepthCullingState.prototype.reset = function () {
  5006. this._depthMask = true;
  5007. this._depthTest = true;
  5008. this._depthFunc = null;
  5009. this._cull = null;
  5010. this._cullFace = null;
  5011. this._zOffset = 0;
  5012. this._isDepthTestDirty = true;
  5013. this._isDepthMaskDirty = true;
  5014. this._isDepthFuncDirty = false;
  5015. this._isCullFaceDirty = false;
  5016. this._isCullDirty = false;
  5017. this._isZOffsetDirty = false;
  5018. };
  5019. _DepthCullingState.prototype.apply = function (gl) {
  5020. if (!this.isDirty) {
  5021. return;
  5022. }
  5023. // Cull
  5024. if (this._isCullDirty) {
  5025. if (this.cull) {
  5026. gl.enable(gl.CULL_FACE);
  5027. }
  5028. else {
  5029. gl.disable(gl.CULL_FACE);
  5030. }
  5031. this._isCullDirty = false;
  5032. }
  5033. // Cull face
  5034. if (this._isCullFaceDirty) {
  5035. gl.cullFace(this.cullFace);
  5036. this._isCullFaceDirty = false;
  5037. }
  5038. // Depth mask
  5039. if (this._isDepthMaskDirty) {
  5040. gl.depthMask(this.depthMask);
  5041. this._isDepthMaskDirty = false;
  5042. }
  5043. // Depth test
  5044. if (this._isDepthTestDirty) {
  5045. if (this.depthTest) {
  5046. gl.enable(gl.DEPTH_TEST);
  5047. }
  5048. else {
  5049. gl.disable(gl.DEPTH_TEST);
  5050. }
  5051. this._isDepthTestDirty = false;
  5052. }
  5053. // Depth func
  5054. if (this._isDepthFuncDirty) {
  5055. gl.depthFunc(this.depthFunc);
  5056. this._isDepthFuncDirty = false;
  5057. }
  5058. // zOffset
  5059. if (this._isZOffsetDirty) {
  5060. if (this.zOffset) {
  5061. gl.enable(gl.POLYGON_OFFSET_FILL);
  5062. gl.polygonOffset(this.zOffset, 0);
  5063. }
  5064. else {
  5065. gl.disable(gl.POLYGON_OFFSET_FILL);
  5066. }
  5067. this._isZOffsetDirty = false;
  5068. }
  5069. };
  5070. return _DepthCullingState;
  5071. })();
  5072. BABYLON._DepthCullingState = _DepthCullingState;
  5073. var _AlphaState = (function () {
  5074. function _AlphaState() {
  5075. this._isAlphaBlendDirty = false;
  5076. this._isBlendFunctionParametersDirty = false;
  5077. this._alphaBlend = false;
  5078. this._blendFunctionParameters = new Array(4);
  5079. }
  5080. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  5081. get: function () {
  5082. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  5083. },
  5084. enumerable: true,
  5085. configurable: true
  5086. });
  5087. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  5088. get: function () {
  5089. return this._alphaBlend;
  5090. },
  5091. set: function (value) {
  5092. if (this._alphaBlend === value) {
  5093. return;
  5094. }
  5095. this._alphaBlend = value;
  5096. this._isAlphaBlendDirty = true;
  5097. },
  5098. enumerable: true,
  5099. configurable: true
  5100. });
  5101. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  5102. if (this._blendFunctionParameters[0] === value0 &&
  5103. this._blendFunctionParameters[1] === value1 &&
  5104. this._blendFunctionParameters[2] === value2 &&
  5105. this._blendFunctionParameters[3] === value3) {
  5106. return;
  5107. }
  5108. this._blendFunctionParameters[0] = value0;
  5109. this._blendFunctionParameters[1] = value1;
  5110. this._blendFunctionParameters[2] = value2;
  5111. this._blendFunctionParameters[3] = value3;
  5112. this._isBlendFunctionParametersDirty = true;
  5113. };
  5114. _AlphaState.prototype.reset = function () {
  5115. this._alphaBlend = false;
  5116. this._blendFunctionParameters[0] = null;
  5117. this._blendFunctionParameters[1] = null;
  5118. this._blendFunctionParameters[2] = null;
  5119. this._blendFunctionParameters[3] = null;
  5120. this._isAlphaBlendDirty = true;
  5121. this._isBlendFunctionParametersDirty = false;
  5122. };
  5123. _AlphaState.prototype.apply = function (gl) {
  5124. if (!this.isDirty) {
  5125. return;
  5126. }
  5127. // Alpha blend
  5128. if (this._isAlphaBlendDirty) {
  5129. if (this._alphaBlend) {
  5130. gl.enable(gl.BLEND);
  5131. }
  5132. else {
  5133. gl.disable(gl.BLEND);
  5134. }
  5135. this._isAlphaBlendDirty = false;
  5136. }
  5137. // Alpha function
  5138. if (this._isBlendFunctionParametersDirty) {
  5139. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  5140. this._isBlendFunctionParametersDirty = false;
  5141. }
  5142. };
  5143. return _AlphaState;
  5144. })();
  5145. BABYLON._AlphaState = _AlphaState;
  5146. var compileShader = function (gl, source, type, defines) {
  5147. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  5148. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  5149. gl.compileShader(shader);
  5150. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  5151. throw new Error(gl.getShaderInfoLog(shader));
  5152. }
  5153. return shader;
  5154. };
  5155. var getWebGLTextureType = function (gl, type) {
  5156. var textureType = gl.UNSIGNED_BYTE;
  5157. if (type === Engine.TEXTURETYPE_FLOAT)
  5158. textureType = gl.FLOAT;
  5159. return textureType;
  5160. };
  5161. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  5162. var magFilter = gl.NEAREST;
  5163. var minFilter = gl.NEAREST;
  5164. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  5165. magFilter = gl.LINEAR;
  5166. if (generateMipMaps) {
  5167. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  5168. }
  5169. else {
  5170. minFilter = gl.LINEAR;
  5171. }
  5172. }
  5173. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  5174. magFilter = gl.LINEAR;
  5175. if (generateMipMaps) {
  5176. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  5177. }
  5178. else {
  5179. minFilter = gl.LINEAR;
  5180. }
  5181. }
  5182. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5183. magFilter = gl.NEAREST;
  5184. if (generateMipMaps) {
  5185. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  5186. }
  5187. else {
  5188. minFilter = gl.NEAREST;
  5189. }
  5190. }
  5191. return {
  5192. min: minFilter,
  5193. mag: magFilter
  5194. };
  5195. };
  5196. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, onLoad, samplingMode) {
  5197. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  5198. var engine = scene.getEngine();
  5199. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  5200. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  5201. gl.bindTexture(gl.TEXTURE_2D, texture);
  5202. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  5203. texture._baseWidth = width;
  5204. texture._baseHeight = height;
  5205. texture._width = potWidth;
  5206. texture._height = potHeight;
  5207. texture.isReady = true;
  5208. processFunction(potWidth, potHeight);
  5209. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  5210. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5211. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5212. if (!noMipmap && !isCompressed) {
  5213. gl.generateMipmap(gl.TEXTURE_2D);
  5214. }
  5215. gl.bindTexture(gl.TEXTURE_2D, null);
  5216. engine.resetTextureCache();
  5217. scene._removePendingData(texture);
  5218. if (onLoad) {
  5219. onLoad();
  5220. }
  5221. };
  5222. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  5223. var img;
  5224. var onload = function () {
  5225. loadedImages[index] = img;
  5226. loadedImages._internalCount++;
  5227. scene._removePendingData(img);
  5228. if (loadedImages._internalCount === 6) {
  5229. onfinish(loadedImages);
  5230. }
  5231. };
  5232. var onerror = function () {
  5233. scene._removePendingData(img);
  5234. };
  5235. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  5236. scene._addPendingData(img);
  5237. };
  5238. var cascadeLoad = function (rootUrl, scene, onfinish, files) {
  5239. var loadedImages = [];
  5240. loadedImages._internalCount = 0;
  5241. for (var index = 0; index < 6; index++) {
  5242. partialLoad(files[index], index, loadedImages, scene, onfinish);
  5243. }
  5244. };
  5245. var EngineCapabilities = (function () {
  5246. function EngineCapabilities() {
  5247. }
  5248. return EngineCapabilities;
  5249. })();
  5250. BABYLON.EngineCapabilities = EngineCapabilities;
  5251. /**
  5252. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  5253. */
  5254. var Engine = (function () {
  5255. /**
  5256. * @constructor
  5257. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  5258. * @param {boolean} [antialias] - enable antialias
  5259. * @param options - further options to be sent to the getContext function
  5260. */
  5261. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  5262. var _this = this;
  5263. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = true; }
  5264. // Public members
  5265. this.isFullscreen = false;
  5266. this.isPointerLock = false;
  5267. this.cullBackFaces = true;
  5268. this.renderEvenInBackground = true;
  5269. // To enable/disable IDB support and avoid XHR on .manifest
  5270. this.enableOfflineSupport = true;
  5271. this.scenes = new Array();
  5272. this._windowIsBackground = false;
  5273. this._webGLVersion = "1.0";
  5274. this._drawCalls = 0;
  5275. this._renderingQueueLaunched = false;
  5276. this._activeRenderLoops = [];
  5277. // FPS
  5278. this.fpsRange = 60;
  5279. this.previousFramesDuration = [];
  5280. this.fps = 60;
  5281. this.deltaTime = 0;
  5282. // States
  5283. this._depthCullingState = new _DepthCullingState();
  5284. this._alphaState = new _AlphaState();
  5285. this._alphaMode = Engine.ALPHA_DISABLE;
  5286. // Cache
  5287. this._loadedTexturesCache = new Array();
  5288. this._maxTextureChannels = 16;
  5289. this._activeTexturesCache = new Array(this._maxTextureChannels);
  5290. this._compiledEffects = {};
  5291. this._uintIndicesCurrentlySet = false;
  5292. this._renderingCanvas = canvas;
  5293. options = options || {};
  5294. options.antialias = antialias;
  5295. if (options.preserveDrawingBuffer === undefined) {
  5296. options.preserveDrawingBuffer = false;
  5297. }
  5298. // GL
  5299. //try {
  5300. // this._gl = <WebGLRenderingContext>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  5301. // if (this._gl) {
  5302. // this._webGLVersion = "2.0";
  5303. // }
  5304. //} catch (e) {
  5305. // // Do nothing
  5306. //}
  5307. if (!this._gl) {
  5308. try {
  5309. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  5310. }
  5311. catch (e) {
  5312. throw new Error("WebGL not supported");
  5313. }
  5314. }
  5315. if (!this._gl) {
  5316. throw new Error("WebGL not supported");
  5317. }
  5318. this._onBlur = function () {
  5319. _this._windowIsBackground = true;
  5320. };
  5321. this._onFocus = function () {
  5322. _this._windowIsBackground = false;
  5323. };
  5324. window.addEventListener("blur", this._onBlur);
  5325. window.addEventListener("focus", this._onFocus);
  5326. // Viewport
  5327. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / (window.devicePixelRatio || 1.0) : 1.0;
  5328. this.resize();
  5329. // Caps
  5330. this._caps = new EngineCapabilities();
  5331. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  5332. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  5333. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  5334. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  5335. // Infos
  5336. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  5337. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  5338. if (rendererInfo != null) {
  5339. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  5340. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  5341. }
  5342. if (!this._glVendor) {
  5343. this._glVendor = "Unknown vendor";
  5344. }
  5345. if (!this._glRenderer) {
  5346. this._glRenderer = "Unknown renderer";
  5347. }
  5348. // Extensions
  5349. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  5350. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  5351. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  5352. 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');
  5353. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  5354. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  5355. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  5356. this._caps.fragmentDepthSupported = this._gl.getExtension('EXT_frag_depth') !== null;
  5357. this._caps.highPrecisionShaderSupported = true;
  5358. this._caps.drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  5359. this._caps.textureFloatLinearFiltering = this._gl.getExtension('OES_texture_float_linear');
  5360. this._caps.textureLOD = this._gl.getExtension('EXT_shader_texture_lod');
  5361. if (this._gl.getShaderPrecisionFormat) {
  5362. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  5363. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  5364. }
  5365. // Depth buffer
  5366. this.setDepthBuffer(true);
  5367. this.setDepthFunctionToLessOrEqual();
  5368. this.setDepthWrite(true);
  5369. // Fullscreen
  5370. this._onFullscreenChange = function () {
  5371. if (document.fullscreen !== undefined) {
  5372. _this.isFullscreen = document.fullscreen;
  5373. }
  5374. else if (document.mozFullScreen !== undefined) {
  5375. _this.isFullscreen = document.mozFullScreen;
  5376. }
  5377. else if (document.webkitIsFullScreen !== undefined) {
  5378. _this.isFullscreen = document.webkitIsFullScreen;
  5379. }
  5380. else if (document.msIsFullScreen !== undefined) {
  5381. _this.isFullscreen = document.msIsFullScreen;
  5382. }
  5383. // Pointer lock
  5384. if (_this.isFullscreen && _this._pointerLockRequested) {
  5385. canvas.requestPointerLock = canvas.requestPointerLock ||
  5386. canvas.msRequestPointerLock ||
  5387. canvas.mozRequestPointerLock ||
  5388. canvas.webkitRequestPointerLock;
  5389. if (canvas.requestPointerLock) {
  5390. canvas.requestPointerLock();
  5391. }
  5392. }
  5393. };
  5394. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  5395. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  5396. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  5397. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  5398. // Pointer lock
  5399. this._onPointerLockChange = function () {
  5400. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  5401. document.webkitPointerLockElement === canvas ||
  5402. document.msPointerLockElement === canvas ||
  5403. document.pointerLockElement === canvas);
  5404. };
  5405. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  5406. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  5407. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  5408. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  5409. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  5410. Engine.audioEngine = new BABYLON.AudioEngine();
  5411. }
  5412. //default loading screen
  5413. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  5414. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  5415. }
  5416. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  5417. get: function () {
  5418. return Engine._ALPHA_DISABLE;
  5419. },
  5420. enumerable: true,
  5421. configurable: true
  5422. });
  5423. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  5424. get: function () {
  5425. return Engine._ALPHA_ONEONE;
  5426. },
  5427. enumerable: true,
  5428. configurable: true
  5429. });
  5430. Object.defineProperty(Engine, "ALPHA_ADD", {
  5431. get: function () {
  5432. return Engine._ALPHA_ADD;
  5433. },
  5434. enumerable: true,
  5435. configurable: true
  5436. });
  5437. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  5438. get: function () {
  5439. return Engine._ALPHA_COMBINE;
  5440. },
  5441. enumerable: true,
  5442. configurable: true
  5443. });
  5444. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  5445. get: function () {
  5446. return Engine._ALPHA_SUBTRACT;
  5447. },
  5448. enumerable: true,
  5449. configurable: true
  5450. });
  5451. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  5452. get: function () {
  5453. return Engine._ALPHA_MULTIPLY;
  5454. },
  5455. enumerable: true,
  5456. configurable: true
  5457. });
  5458. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  5459. get: function () {
  5460. return Engine._ALPHA_MAXIMIZED;
  5461. },
  5462. enumerable: true,
  5463. configurable: true
  5464. });
  5465. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  5466. get: function () {
  5467. return Engine._DELAYLOADSTATE_NONE;
  5468. },
  5469. enumerable: true,
  5470. configurable: true
  5471. });
  5472. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  5473. get: function () {
  5474. return Engine._DELAYLOADSTATE_LOADED;
  5475. },
  5476. enumerable: true,
  5477. configurable: true
  5478. });
  5479. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  5480. get: function () {
  5481. return Engine._DELAYLOADSTATE_LOADING;
  5482. },
  5483. enumerable: true,
  5484. configurable: true
  5485. });
  5486. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  5487. get: function () {
  5488. return Engine._DELAYLOADSTATE_NOTLOADED;
  5489. },
  5490. enumerable: true,
  5491. configurable: true
  5492. });
  5493. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  5494. get: function () {
  5495. return Engine._TEXTUREFORMAT_ALPHA;
  5496. },
  5497. enumerable: true,
  5498. configurable: true
  5499. });
  5500. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  5501. get: function () {
  5502. return Engine._TEXTUREFORMAT_LUMINANCE;
  5503. },
  5504. enumerable: true,
  5505. configurable: true
  5506. });
  5507. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  5508. get: function () {
  5509. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  5510. },
  5511. enumerable: true,
  5512. configurable: true
  5513. });
  5514. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  5515. get: function () {
  5516. return Engine._TEXTUREFORMAT_RGB;
  5517. },
  5518. enumerable: true,
  5519. configurable: true
  5520. });
  5521. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  5522. get: function () {
  5523. return Engine._TEXTUREFORMAT_RGBA;
  5524. },
  5525. enumerable: true,
  5526. configurable: true
  5527. });
  5528. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  5529. get: function () {
  5530. return Engine._TEXTURETYPE_UNSIGNED_INT;
  5531. },
  5532. enumerable: true,
  5533. configurable: true
  5534. });
  5535. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  5536. get: function () {
  5537. return Engine._TEXTURETYPE_FLOAT;
  5538. },
  5539. enumerable: true,
  5540. configurable: true
  5541. });
  5542. Object.defineProperty(Engine, "Version", {
  5543. get: function () {
  5544. return "2.4.0-alpha";
  5545. },
  5546. enumerable: true,
  5547. configurable: true
  5548. });
  5549. Object.defineProperty(Engine.prototype, "webGLVersion", {
  5550. get: function () {
  5551. return this._webGLVersion;
  5552. },
  5553. enumerable: true,
  5554. configurable: true
  5555. });
  5556. Engine.prototype._prepareWorkingCanvas = function () {
  5557. if (this._workingCanvas) {
  5558. return;
  5559. }
  5560. this._workingCanvas = document.createElement("canvas");
  5561. this._workingContext = this._workingCanvas.getContext("2d");
  5562. };
  5563. Engine.prototype.resetTextureCache = function () {
  5564. for (var index = 0; index < this._maxTextureChannels; index++) {
  5565. this._activeTexturesCache[index] = null;
  5566. }
  5567. };
  5568. Engine.prototype.getGlInfo = function () {
  5569. return {
  5570. vendor: this._glVendor,
  5571. renderer: this._glRenderer,
  5572. version: this._glVersion
  5573. };
  5574. };
  5575. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  5576. if (useScreen === void 0) { useScreen = false; }
  5577. var viewport = camera.viewport;
  5578. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  5579. };
  5580. Engine.prototype.getRenderWidth = function (useScreen) {
  5581. if (useScreen === void 0) { useScreen = false; }
  5582. if (!useScreen && this._currentRenderTarget) {
  5583. return this._currentRenderTarget._width;
  5584. }
  5585. return this._renderingCanvas.width;
  5586. };
  5587. Engine.prototype.getRenderHeight = function (useScreen) {
  5588. if (useScreen === void 0) { useScreen = false; }
  5589. if (!useScreen && this._currentRenderTarget) {
  5590. return this._currentRenderTarget._height;
  5591. }
  5592. return this._renderingCanvas.height;
  5593. };
  5594. Engine.prototype.getRenderingCanvas = function () {
  5595. return this._renderingCanvas;
  5596. };
  5597. Engine.prototype.getRenderingCanvasClientRect = function () {
  5598. return this._renderingCanvas.getBoundingClientRect();
  5599. };
  5600. Engine.prototype.setHardwareScalingLevel = function (level) {
  5601. this._hardwareScalingLevel = level;
  5602. this.resize();
  5603. };
  5604. Engine.prototype.getHardwareScalingLevel = function () {
  5605. return this._hardwareScalingLevel;
  5606. };
  5607. Engine.prototype.getLoadedTexturesCache = function () {
  5608. return this._loadedTexturesCache;
  5609. };
  5610. Engine.prototype.getCaps = function () {
  5611. return this._caps;
  5612. };
  5613. Object.defineProperty(Engine.prototype, "drawCalls", {
  5614. get: function () {
  5615. return this._drawCalls;
  5616. },
  5617. enumerable: true,
  5618. configurable: true
  5619. });
  5620. // Methods
  5621. Engine.prototype.resetDrawCalls = function () {
  5622. this._drawCalls = 0;
  5623. };
  5624. Engine.prototype.setDepthFunctionToGreater = function () {
  5625. this._depthCullingState.depthFunc = this._gl.GREATER;
  5626. };
  5627. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  5628. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  5629. };
  5630. Engine.prototype.setDepthFunctionToLess = function () {
  5631. this._depthCullingState.depthFunc = this._gl.LESS;
  5632. };
  5633. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  5634. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  5635. };
  5636. /**
  5637. * stop executing a render loop function and remove it from the execution array
  5638. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  5639. */
  5640. Engine.prototype.stopRenderLoop = function (renderFunction) {
  5641. if (!renderFunction) {
  5642. this._activeRenderLoops = [];
  5643. return;
  5644. }
  5645. var index = this._activeRenderLoops.indexOf(renderFunction);
  5646. if (index >= 0) {
  5647. this._activeRenderLoops.splice(index, 1);
  5648. }
  5649. };
  5650. Engine.prototype._renderLoop = function () {
  5651. var shouldRender = true;
  5652. if (!this.renderEvenInBackground && this._windowIsBackground) {
  5653. shouldRender = false;
  5654. }
  5655. if (shouldRender) {
  5656. // Start new frame
  5657. this.beginFrame();
  5658. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  5659. var renderFunction = this._activeRenderLoops[index];
  5660. renderFunction();
  5661. }
  5662. // Present
  5663. this.endFrame();
  5664. }
  5665. if (this._activeRenderLoops.length > 0) {
  5666. // Register new frame
  5667. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5668. }
  5669. else {
  5670. this._renderingQueueLaunched = false;
  5671. }
  5672. };
  5673. /**
  5674. * Register and execute a render loop. The engine can have more than one render function.
  5675. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  5676. * @example
  5677. * engine.runRenderLoop(function () {
  5678. * scene.render()
  5679. * })
  5680. */
  5681. Engine.prototype.runRenderLoop = function (renderFunction) {
  5682. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  5683. return;
  5684. }
  5685. this._activeRenderLoops.push(renderFunction);
  5686. if (!this._renderingQueueLaunched) {
  5687. this._renderingQueueLaunched = true;
  5688. this._bindedRenderFunction = this._renderLoop.bind(this);
  5689. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5690. }
  5691. };
  5692. /**
  5693. * Toggle full screen mode.
  5694. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  5695. */
  5696. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  5697. if (this.isFullscreen) {
  5698. BABYLON.Tools.ExitFullscreen();
  5699. }
  5700. else {
  5701. this._pointerLockRequested = requestPointerLock;
  5702. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  5703. }
  5704. };
  5705. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  5706. this.applyStates();
  5707. if (backBuffer) {
  5708. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  5709. }
  5710. if (depthStencil && this._depthCullingState.depthMask) {
  5711. this._gl.clearDepth(1.0);
  5712. }
  5713. var mode = 0;
  5714. if (backBuffer) {
  5715. mode |= this._gl.COLOR_BUFFER_BIT;
  5716. }
  5717. if (depthStencil && this._depthCullingState.depthMask) {
  5718. mode |= this._gl.DEPTH_BUFFER_BIT;
  5719. }
  5720. this._gl.clear(mode);
  5721. };
  5722. /**
  5723. * Set the WebGL's viewport
  5724. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  5725. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  5726. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  5727. */
  5728. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  5729. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  5730. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  5731. var x = viewport.x || 0;
  5732. var y = viewport.y || 0;
  5733. this._cachedViewport = viewport;
  5734. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  5735. };
  5736. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  5737. this._cachedViewport = null;
  5738. this._gl.viewport(x, y, width, height);
  5739. };
  5740. Engine.prototype.beginFrame = function () {
  5741. this._measureFps();
  5742. };
  5743. Engine.prototype.endFrame = function () {
  5744. //this.flushFramebuffer();
  5745. };
  5746. /**
  5747. * resize the view according to the canvas' size.
  5748. * @example
  5749. * window.addEventListener("resize", function () {
  5750. * engine.resize();
  5751. * });
  5752. */
  5753. Engine.prototype.resize = function () {
  5754. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  5755. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  5756. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  5757. for (var index = 0; index < this.scenes.length; index++) {
  5758. var scene = this.scenes[index];
  5759. if (scene.debugLayer.isVisible()) {
  5760. scene.debugLayer._syncPositions();
  5761. }
  5762. }
  5763. };
  5764. /**
  5765. * force a specific size of the canvas
  5766. * @param {number} width - the new canvas' width
  5767. * @param {number} height - the new canvas' height
  5768. */
  5769. Engine.prototype.setSize = function (width, height) {
  5770. this._renderingCanvas.width = width;
  5771. this._renderingCanvas.height = height;
  5772. for (var index = 0; index < this.scenes.length; index++) {
  5773. var scene = this.scenes[index];
  5774. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  5775. var cam = scene.cameras[camIndex];
  5776. cam._currentRenderId = 0;
  5777. }
  5778. }
  5779. };
  5780. Engine.prototype.bindFramebuffer = function (texture, faceIndex) {
  5781. this._currentRenderTarget = texture;
  5782. var gl = this._gl;
  5783. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  5784. if (texture.isCube) {
  5785. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  5786. }
  5787. else {
  5788. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  5789. }
  5790. this._gl.viewport(0, 0, texture._width, texture._height);
  5791. this.wipeCaches();
  5792. };
  5793. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  5794. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  5795. this._currentRenderTarget = null;
  5796. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  5797. var gl = this._gl;
  5798. gl.bindTexture(gl.TEXTURE_2D, texture);
  5799. gl.generateMipmap(gl.TEXTURE_2D);
  5800. gl.bindTexture(gl.TEXTURE_2D, null);
  5801. }
  5802. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5803. };
  5804. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  5805. if (texture.generateMipMaps) {
  5806. var gl = this._gl;
  5807. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  5808. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  5809. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  5810. }
  5811. };
  5812. Engine.prototype.flushFramebuffer = function () {
  5813. this._gl.flush();
  5814. };
  5815. Engine.prototype.restoreDefaultFramebuffer = function () {
  5816. this._currentRenderTarget = null;
  5817. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5818. this.setViewport(this._cachedViewport);
  5819. this.wipeCaches();
  5820. };
  5821. // VBOs
  5822. Engine.prototype._resetVertexBufferBinding = function () {
  5823. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  5824. this._cachedVertexBuffers = null;
  5825. };
  5826. Engine.prototype.createVertexBuffer = function (vertices) {
  5827. var vbo = this._gl.createBuffer();
  5828. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5829. if (vertices instanceof Float32Array) {
  5830. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  5831. }
  5832. else {
  5833. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  5834. }
  5835. this._resetVertexBufferBinding();
  5836. vbo.references = 1;
  5837. return vbo;
  5838. };
  5839. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  5840. var vbo = this._gl.createBuffer();
  5841. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5842. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5843. this._resetVertexBufferBinding();
  5844. vbo.references = 1;
  5845. return vbo;
  5846. };
  5847. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  5848. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5849. if (offset === undefined) {
  5850. offset = 0;
  5851. }
  5852. if (vertices instanceof Float32Array) {
  5853. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  5854. }
  5855. else {
  5856. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  5857. }
  5858. this._resetVertexBufferBinding();
  5859. };
  5860. Engine.prototype._resetIndexBufferBinding = function () {
  5861. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  5862. this._cachedIndexBuffer = null;
  5863. };
  5864. Engine.prototype.createIndexBuffer = function (indices) {
  5865. var vbo = this._gl.createBuffer();
  5866. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  5867. // Check for 32 bits indices
  5868. var arrayBuffer;
  5869. var need32Bits = false;
  5870. if (this._caps.uintIndices) {
  5871. for (var index = 0; index < indices.length; index++) {
  5872. if (indices[index] > 65535) {
  5873. need32Bits = true;
  5874. break;
  5875. }
  5876. }
  5877. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  5878. }
  5879. else {
  5880. arrayBuffer = new Uint16Array(indices);
  5881. }
  5882. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  5883. this._resetIndexBufferBinding();
  5884. vbo.references = 1;
  5885. vbo.is32Bits = need32Bits;
  5886. return vbo;
  5887. };
  5888. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  5889. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  5890. this._cachedVertexBuffers = vertexBuffer;
  5891. this._cachedEffectForVertexBuffers = effect;
  5892. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5893. var offset = 0;
  5894. for (var index = 0; index < vertexDeclaration.length; index++) {
  5895. var order = effect.getAttributeLocation(index);
  5896. if (order >= 0) {
  5897. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  5898. }
  5899. offset += vertexDeclaration[index] * 4;
  5900. }
  5901. }
  5902. if (this._cachedIndexBuffer !== indexBuffer) {
  5903. this._cachedIndexBuffer = indexBuffer;
  5904. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  5905. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  5906. }
  5907. };
  5908. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  5909. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  5910. this._cachedVertexBuffers = vertexBuffers;
  5911. this._cachedEffectForVertexBuffers = effect;
  5912. var attributes = effect.getAttributesNames();
  5913. for (var index = 0; index < attributes.length; index++) {
  5914. var order = effect.getAttributeLocation(index);
  5915. if (order >= 0) {
  5916. var vertexBuffer = vertexBuffers[attributes[index]];
  5917. if (!vertexBuffer) {
  5918. continue;
  5919. }
  5920. var stride = vertexBuffer.getStrideSize();
  5921. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  5922. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  5923. }
  5924. }
  5925. }
  5926. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  5927. this._cachedIndexBuffer = indexBuffer;
  5928. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  5929. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  5930. }
  5931. };
  5932. Engine.prototype._releaseBuffer = function (buffer) {
  5933. buffer.references--;
  5934. if (buffer.references === 0) {
  5935. this._gl.deleteBuffer(buffer);
  5936. return true;
  5937. }
  5938. return false;
  5939. };
  5940. Engine.prototype.createInstancesBuffer = function (capacity) {
  5941. var buffer = this._gl.createBuffer();
  5942. buffer.capacity = capacity;
  5943. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  5944. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5945. return buffer;
  5946. };
  5947. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  5948. this._gl.deleteBuffer(buffer);
  5949. };
  5950. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  5951. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  5952. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  5953. for (var index = 0; index < 4; index++) {
  5954. var offsetLocation = offsetLocations[index];
  5955. this._gl.enableVertexAttribArray(offsetLocation);
  5956. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  5957. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  5958. }
  5959. };
  5960. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  5961. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  5962. for (var index = 0; index < 4; index++) {
  5963. var offsetLocation = offsetLocations[index];
  5964. this._gl.disableVertexAttribArray(offsetLocation);
  5965. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  5966. }
  5967. };
  5968. Engine.prototype.applyStates = function () {
  5969. this._depthCullingState.apply(this._gl);
  5970. this._alphaState.apply(this._gl);
  5971. };
  5972. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  5973. // Apply states
  5974. this.applyStates();
  5975. this._drawCalls++;
  5976. // Render
  5977. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  5978. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  5979. if (instancesCount) {
  5980. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  5981. return;
  5982. }
  5983. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  5984. };
  5985. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  5986. // Apply states
  5987. this.applyStates();
  5988. this._drawCalls++;
  5989. if (instancesCount) {
  5990. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  5991. return;
  5992. }
  5993. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  5994. };
  5995. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  5996. // Apply states
  5997. this.applyStates();
  5998. this._drawCalls++;
  5999. if (instancesCount) {
  6000. this._caps.instancedArrays.drawArraysInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  6001. return;
  6002. }
  6003. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  6004. };
  6005. // Shaders
  6006. Engine.prototype._releaseEffect = function (effect) {
  6007. if (this._compiledEffects[effect._key]) {
  6008. delete this._compiledEffects[effect._key];
  6009. if (effect.getProgram()) {
  6010. this._gl.deleteProgram(effect.getProgram());
  6011. }
  6012. }
  6013. };
  6014. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  6015. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  6016. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  6017. var name = vertex + "+" + fragment + "@" + defines;
  6018. if (this._compiledEffects[name]) {
  6019. return this._compiledEffects[name];
  6020. }
  6021. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  6022. effect._key = name;
  6023. this._compiledEffects[name] = effect;
  6024. return effect;
  6025. };
  6026. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  6027. if (uniformsNames === void 0) { uniformsNames = []; }
  6028. if (samplers === void 0) { samplers = []; }
  6029. if (defines === void 0) { defines = ""; }
  6030. return this.createEffect({
  6031. vertex: "particles",
  6032. fragmentElement: fragmentName
  6033. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  6034. };
  6035. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  6036. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  6037. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  6038. var shaderProgram = this._gl.createProgram();
  6039. this._gl.attachShader(shaderProgram, vertexShader);
  6040. this._gl.attachShader(shaderProgram, fragmentShader);
  6041. this._gl.linkProgram(shaderProgram);
  6042. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  6043. if (!linked) {
  6044. var error = this._gl.getProgramInfoLog(shaderProgram);
  6045. if (error) {
  6046. throw new Error(error);
  6047. }
  6048. }
  6049. this._gl.deleteShader(vertexShader);
  6050. this._gl.deleteShader(fragmentShader);
  6051. return shaderProgram;
  6052. };
  6053. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  6054. var results = [];
  6055. for (var index = 0; index < uniformsNames.length; index++) {
  6056. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  6057. }
  6058. return results;
  6059. };
  6060. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  6061. var results = [];
  6062. for (var index = 0; index < attributesNames.length; index++) {
  6063. try {
  6064. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  6065. }
  6066. catch (e) {
  6067. results.push(-1);
  6068. }
  6069. }
  6070. return results;
  6071. };
  6072. Engine.prototype.enableEffect = function (effect) {
  6073. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  6074. if (effect && effect.onBind) {
  6075. effect.onBind(effect);
  6076. }
  6077. return;
  6078. }
  6079. this._vertexAttribArrays = this._vertexAttribArrays || [];
  6080. // Use program
  6081. this._gl.useProgram(effect.getProgram());
  6082. for (var i in this._vertexAttribArrays) {
  6083. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  6084. continue;
  6085. }
  6086. this._vertexAttribArrays[i] = false;
  6087. this._gl.disableVertexAttribArray(i);
  6088. }
  6089. var attributesCount = effect.getAttributesCount();
  6090. for (var index = 0; index < attributesCount; index++) {
  6091. // Attributes
  6092. var order = effect.getAttributeLocation(index);
  6093. if (order >= 0) {
  6094. this._vertexAttribArrays[order] = true;
  6095. this._gl.enableVertexAttribArray(order);
  6096. }
  6097. }
  6098. this._currentEffect = effect;
  6099. if (effect.onBind) {
  6100. effect.onBind(effect);
  6101. }
  6102. };
  6103. Engine.prototype.setArray = function (uniform, array) {
  6104. if (!uniform)
  6105. return;
  6106. this._gl.uniform1fv(uniform, array);
  6107. };
  6108. Engine.prototype.setArray2 = function (uniform, array) {
  6109. if (!uniform || array.length % 2 !== 0)
  6110. return;
  6111. this._gl.uniform2fv(uniform, array);
  6112. };
  6113. Engine.prototype.setArray3 = function (uniform, array) {
  6114. if (!uniform || array.length % 3 !== 0)
  6115. return;
  6116. this._gl.uniform3fv(uniform, array);
  6117. };
  6118. Engine.prototype.setArray4 = function (uniform, array) {
  6119. if (!uniform || array.length % 4 !== 0)
  6120. return;
  6121. this._gl.uniform4fv(uniform, array);
  6122. };
  6123. Engine.prototype.setMatrices = function (uniform, matrices) {
  6124. if (!uniform)
  6125. return;
  6126. this._gl.uniformMatrix4fv(uniform, false, matrices);
  6127. };
  6128. Engine.prototype.setMatrix = function (uniform, matrix) {
  6129. if (!uniform)
  6130. return;
  6131. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  6132. };
  6133. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  6134. if (!uniform)
  6135. return;
  6136. this._gl.uniformMatrix3fv(uniform, false, matrix);
  6137. };
  6138. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  6139. if (!uniform)
  6140. return;
  6141. this._gl.uniformMatrix2fv(uniform, false, matrix);
  6142. };
  6143. Engine.prototype.setFloat = function (uniform, value) {
  6144. if (!uniform)
  6145. return;
  6146. this._gl.uniform1f(uniform, value);
  6147. };
  6148. Engine.prototype.setFloat2 = function (uniform, x, y) {
  6149. if (!uniform)
  6150. return;
  6151. this._gl.uniform2f(uniform, x, y);
  6152. };
  6153. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  6154. if (!uniform)
  6155. return;
  6156. this._gl.uniform3f(uniform, x, y, z);
  6157. };
  6158. Engine.prototype.setBool = function (uniform, bool) {
  6159. if (!uniform)
  6160. return;
  6161. this._gl.uniform1i(uniform, bool);
  6162. };
  6163. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  6164. if (!uniform)
  6165. return;
  6166. this._gl.uniform4f(uniform, x, y, z, w);
  6167. };
  6168. Engine.prototype.setColor3 = function (uniform, color3) {
  6169. if (!uniform)
  6170. return;
  6171. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  6172. };
  6173. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  6174. if (!uniform)
  6175. return;
  6176. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  6177. };
  6178. // States
  6179. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  6180. if (zOffset === void 0) { zOffset = 0; }
  6181. if (reverseSide === void 0) { reverseSide = false; }
  6182. // Culling
  6183. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  6184. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  6185. var cullFace = this.cullBackFaces ? showSide : hideSide;
  6186. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  6187. if (culling) {
  6188. this._depthCullingState.cullFace = cullFace;
  6189. this._depthCullingState.cull = true;
  6190. }
  6191. else {
  6192. this._depthCullingState.cull = false;
  6193. }
  6194. }
  6195. // Z offset
  6196. this._depthCullingState.zOffset = zOffset;
  6197. };
  6198. Engine.prototype.setDepthBuffer = function (enable) {
  6199. this._depthCullingState.depthTest = enable;
  6200. };
  6201. Engine.prototype.getDepthWrite = function () {
  6202. return this._depthCullingState.depthMask;
  6203. };
  6204. Engine.prototype.setDepthWrite = function (enable) {
  6205. this._depthCullingState.depthMask = enable;
  6206. };
  6207. Engine.prototype.setColorWrite = function (enable) {
  6208. this._gl.colorMask(enable, enable, enable, enable);
  6209. };
  6210. Engine.prototype.setAlphaMode = function (mode) {
  6211. if (this._alphaMode === mode) {
  6212. return;
  6213. }
  6214. switch (mode) {
  6215. case Engine.ALPHA_DISABLE:
  6216. this.setDepthWrite(true);
  6217. this._alphaState.alphaBlend = false;
  6218. break;
  6219. case Engine.ALPHA_COMBINE:
  6220. this.setDepthWrite(false);
  6221. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  6222. this._alphaState.alphaBlend = true;
  6223. break;
  6224. case Engine.ALPHA_ONEONE:
  6225. this.setDepthWrite(false);
  6226. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6227. this._alphaState.alphaBlend = true;
  6228. break;
  6229. case Engine.ALPHA_ADD:
  6230. this.setDepthWrite(false);
  6231. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6232. this._alphaState.alphaBlend = true;
  6233. break;
  6234. case Engine.ALPHA_SUBTRACT:
  6235. this.setDepthWrite(false);
  6236. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6237. this._alphaState.alphaBlend = true;
  6238. break;
  6239. case Engine.ALPHA_MULTIPLY:
  6240. this.setDepthWrite(false);
  6241. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  6242. this._alphaState.alphaBlend = true;
  6243. break;
  6244. case Engine.ALPHA_MAXIMIZED:
  6245. this.setDepthWrite(false);
  6246. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6247. this._alphaState.alphaBlend = true;
  6248. break;
  6249. }
  6250. this._alphaMode = mode;
  6251. };
  6252. Engine.prototype.getAlphaMode = function () {
  6253. return this._alphaMode;
  6254. };
  6255. Engine.prototype.setAlphaTesting = function (enable) {
  6256. this._alphaTest = enable;
  6257. };
  6258. Engine.prototype.getAlphaTesting = function () {
  6259. return this._alphaTest;
  6260. };
  6261. // Textures
  6262. Engine.prototype.wipeCaches = function () {
  6263. this.resetTextureCache();
  6264. this._currentEffect = null;
  6265. this._depthCullingState.reset();
  6266. this._alphaState.reset();
  6267. this._cachedVertexBuffers = null;
  6268. this._cachedIndexBuffer = null;
  6269. this._cachedEffectForVertexBuffers = null;
  6270. };
  6271. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  6272. var gl = this._gl;
  6273. gl.bindTexture(gl.TEXTURE_2D, texture);
  6274. var magFilter = gl.NEAREST;
  6275. var minFilter = gl.NEAREST;
  6276. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6277. magFilter = gl.LINEAR;
  6278. minFilter = gl.LINEAR;
  6279. }
  6280. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6281. magFilter = gl.LINEAR;
  6282. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6283. }
  6284. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  6285. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  6286. gl.bindTexture(gl.TEXTURE_2D, null);
  6287. texture.samplingMode = samplingMode;
  6288. };
  6289. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  6290. var _this = this;
  6291. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6292. if (onLoad === void 0) { onLoad = null; }
  6293. if (onError === void 0) { onError = null; }
  6294. if (buffer === void 0) { buffer = null; }
  6295. var texture = this._gl.createTexture();
  6296. var extension;
  6297. var fromData = false;
  6298. if (url.substr(0, 5) === "data:") {
  6299. fromData = true;
  6300. }
  6301. if (!fromData)
  6302. extension = url.substr(url.length - 4, 4).toLowerCase();
  6303. else {
  6304. var oldUrl = url;
  6305. fromData = oldUrl.split(':');
  6306. url = oldUrl;
  6307. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  6308. }
  6309. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6310. var isTGA = (extension === ".tga");
  6311. scene._addPendingData(texture);
  6312. texture.url = url;
  6313. texture.noMipmap = noMipmap;
  6314. texture.references = 1;
  6315. texture.samplingMode = samplingMode;
  6316. this._loadedTexturesCache.push(texture);
  6317. var onerror = function () {
  6318. scene._removePendingData(texture);
  6319. if (onError) {
  6320. onError();
  6321. }
  6322. };
  6323. var callback;
  6324. if (isTGA) {
  6325. callback = function (arrayBuffer) {
  6326. var data = new Uint8Array(arrayBuffer);
  6327. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  6328. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  6329. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  6330. }, onLoad, samplingMode);
  6331. };
  6332. if (!(fromData instanceof Array))
  6333. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  6334. callback(arrayBuffer);
  6335. }, onerror, scene.database, true);
  6336. else
  6337. callback(buffer);
  6338. }
  6339. else if (isDDS) {
  6340. callback = function (data) {
  6341. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6342. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  6343. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  6344. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  6345. }, onLoad, samplingMode);
  6346. };
  6347. if (!(fromData instanceof Array))
  6348. BABYLON.Tools.LoadFile(url, function (data) {
  6349. callback(data);
  6350. }, onerror, scene.database, true);
  6351. else
  6352. callback(buffer);
  6353. }
  6354. else {
  6355. var onload = function (img) {
  6356. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  6357. var isPot = (img.width === potWidth && img.height === potHeight);
  6358. if (!isPot) {
  6359. _this._prepareWorkingCanvas();
  6360. _this._workingCanvas.width = potWidth;
  6361. _this._workingCanvas.height = potHeight;
  6362. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6363. _this._workingContext.imageSmoothingEnabled = false;
  6364. _this._workingContext.mozImageSmoothingEnabled = false;
  6365. _this._workingContext.oImageSmoothingEnabled = false;
  6366. _this._workingContext.webkitImageSmoothingEnabled = false;
  6367. _this._workingContext.msImageSmoothingEnabled = false;
  6368. }
  6369. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  6370. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6371. _this._workingContext.imageSmoothingEnabled = true;
  6372. _this._workingContext.mozImageSmoothingEnabled = true;
  6373. _this._workingContext.oImageSmoothingEnabled = true;
  6374. _this._workingContext.webkitImageSmoothingEnabled = true;
  6375. _this._workingContext.msImageSmoothingEnabled = true;
  6376. }
  6377. }
  6378. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  6379. }, onLoad, samplingMode);
  6380. };
  6381. if (!(fromData instanceof Array))
  6382. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6383. else
  6384. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  6385. }
  6386. return texture;
  6387. };
  6388. Engine.prototype._getInternalFormat = function (format) {
  6389. var internalFormat = this._gl.RGBA;
  6390. switch (format) {
  6391. case Engine.TEXTUREFORMAT_ALPHA:
  6392. internalFormat = this._gl.ALPHA;
  6393. break;
  6394. case Engine.TEXTUREFORMAT_LUMINANCE:
  6395. internalFormat = this._gl.LUMINANCE;
  6396. break;
  6397. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  6398. internalFormat = this._gl.LUMINANCE_ALPHA;
  6399. break;
  6400. case Engine.TEXTUREFORMAT_RGB:
  6401. internalFormat = this._gl.RGB;
  6402. break;
  6403. case Engine.TEXTUREFORMAT_RGBA:
  6404. internalFormat = this._gl.RGBA;
  6405. break;
  6406. }
  6407. return internalFormat;
  6408. };
  6409. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  6410. if (compression === void 0) { compression = null; }
  6411. var internalFormat = this._getInternalFormat(format);
  6412. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6413. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6414. if (compression) {
  6415. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  6416. }
  6417. else {
  6418. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  6419. }
  6420. if (texture.generateMipMaps) {
  6421. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6422. }
  6423. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6424. this.resetTextureCache();
  6425. texture.isReady = true;
  6426. };
  6427. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  6428. if (compression === void 0) { compression = null; }
  6429. var texture = this._gl.createTexture();
  6430. texture._baseWidth = width;
  6431. texture._baseHeight = height;
  6432. texture._width = width;
  6433. texture._height = height;
  6434. texture.references = 1;
  6435. this.updateRawTexture(texture, data, format, invertY, compression);
  6436. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6437. // Filters
  6438. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  6439. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6440. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6441. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6442. texture.samplingMode = samplingMode;
  6443. this._loadedTexturesCache.push(texture);
  6444. return texture;
  6445. };
  6446. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode, forceExponantOfTwo) {
  6447. if (forceExponantOfTwo === void 0) { forceExponantOfTwo = true; }
  6448. var texture = this._gl.createTexture();
  6449. texture._baseWidth = width;
  6450. texture._baseHeight = height;
  6451. if (forceExponantOfTwo) {
  6452. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  6453. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  6454. }
  6455. this.resetTextureCache();
  6456. texture._width = width;
  6457. texture._height = height;
  6458. texture.isReady = false;
  6459. texture.generateMipMaps = generateMipMaps;
  6460. texture.references = 1;
  6461. texture.samplingMode = samplingMode;
  6462. this.updateTextureSamplingMode(samplingMode, texture);
  6463. this._loadedTexturesCache.push(texture);
  6464. return texture;
  6465. };
  6466. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  6467. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  6468. if (texture.isCube) {
  6469. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, texture);
  6470. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6471. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6472. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6473. }
  6474. else {
  6475. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6476. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6477. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6478. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6479. }
  6480. };
  6481. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  6482. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6483. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  6484. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  6485. if (texture.generateMipMaps) {
  6486. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6487. }
  6488. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6489. this.resetTextureCache();
  6490. texture.isReady = true;
  6491. };
  6492. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  6493. if (texture._isDisabled) {
  6494. return;
  6495. }
  6496. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6497. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  6498. try {
  6499. // Testing video texture support
  6500. if (this._videoTextureSupported === undefined) {
  6501. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6502. if (this._gl.getError() !== 0) {
  6503. this._videoTextureSupported = false;
  6504. }
  6505. else {
  6506. this._videoTextureSupported = true;
  6507. }
  6508. }
  6509. // Copy video through the current working canvas if video texture is not supported
  6510. if (!this._videoTextureSupported) {
  6511. if (!texture._workingCanvas) {
  6512. texture._workingCanvas = document.createElement("canvas");
  6513. texture._workingContext = texture._workingCanvas.getContext("2d");
  6514. texture._workingCanvas.width = texture._width;
  6515. texture._workingCanvas.height = texture._height;
  6516. }
  6517. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  6518. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  6519. }
  6520. else {
  6521. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6522. }
  6523. if (texture.generateMipMaps) {
  6524. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6525. }
  6526. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6527. this.resetTextureCache();
  6528. texture.isReady = true;
  6529. }
  6530. catch (ex) {
  6531. // Something unexpected
  6532. // Let's disable the texture
  6533. texture._isDisabled = true;
  6534. }
  6535. };
  6536. Engine.prototype.createRenderTargetTexture = function (size, options) {
  6537. // old version had a "generateMipMaps" arg instead of options.
  6538. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  6539. // in the same way, generateDepthBuffer is defaulted to true
  6540. var generateMipMaps = false;
  6541. var generateDepthBuffer = true;
  6542. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6543. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6544. if (options !== undefined) {
  6545. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6546. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  6547. type = options.type === undefined ? type : options.type;
  6548. if (options.samplingMode !== undefined) {
  6549. samplingMode = options.samplingMode;
  6550. }
  6551. if (type === Engine.TEXTURETYPE_FLOAT) {
  6552. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  6553. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  6554. }
  6555. }
  6556. var gl = this._gl;
  6557. var texture = gl.createTexture();
  6558. gl.bindTexture(gl.TEXTURE_2D, texture);
  6559. var width = size.width || size;
  6560. var height = size.height || size;
  6561. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6562. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  6563. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6564. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  6565. }
  6566. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6567. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6568. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6569. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6570. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  6571. var depthBuffer;
  6572. // Create the depth buffer
  6573. if (generateDepthBuffer) {
  6574. depthBuffer = gl.createRenderbuffer();
  6575. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6576. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  6577. }
  6578. // Create the framebuffer
  6579. var framebuffer = gl.createFramebuffer();
  6580. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6581. if (generateDepthBuffer) {
  6582. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6583. }
  6584. if (generateMipMaps) {
  6585. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6586. }
  6587. // Unbind
  6588. gl.bindTexture(gl.TEXTURE_2D, null);
  6589. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6590. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6591. texture._framebuffer = framebuffer;
  6592. if (generateDepthBuffer) {
  6593. texture._depthBuffer = depthBuffer;
  6594. }
  6595. texture._width = width;
  6596. texture._height = height;
  6597. texture.isReady = true;
  6598. texture.generateMipMaps = generateMipMaps;
  6599. texture.references = 1;
  6600. texture.samplingMode = samplingMode;
  6601. this.resetTextureCache();
  6602. this._loadedTexturesCache.push(texture);
  6603. return texture;
  6604. };
  6605. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  6606. var gl = this._gl;
  6607. var texture = gl.createTexture();
  6608. var generateMipMaps = true;
  6609. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6610. if (options !== undefined) {
  6611. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6612. if (options.samplingMode !== undefined) {
  6613. samplingMode = options.samplingMode;
  6614. }
  6615. }
  6616. texture.isCube = true;
  6617. texture.references = 1;
  6618. texture.generateMipMaps = generateMipMaps;
  6619. texture.references = 1;
  6620. texture.samplingMode = samplingMode;
  6621. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6622. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6623. for (var face = 0; face < 6; face++) {
  6624. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  6625. }
  6626. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  6627. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  6628. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6629. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6630. // Create the depth buffer
  6631. var depthBuffer = gl.createRenderbuffer();
  6632. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6633. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  6634. // Create the framebuffer
  6635. var framebuffer = gl.createFramebuffer();
  6636. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6637. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6638. // Mipmaps
  6639. if (texture.generateMipMaps) {
  6640. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6641. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6642. }
  6643. // Unbind
  6644. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6645. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6646. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6647. texture._framebuffer = framebuffer;
  6648. texture._depthBuffer = depthBuffer;
  6649. this.resetTextureCache();
  6650. texture._width = size;
  6651. texture._height = size;
  6652. texture.isReady = true;
  6653. return texture;
  6654. };
  6655. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap) {
  6656. var _this = this;
  6657. var gl = this._gl;
  6658. var texture = gl.createTexture();
  6659. texture.isCube = true;
  6660. texture.url = rootUrl;
  6661. texture.references = 1;
  6662. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  6663. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6664. if (isDDS) {
  6665. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  6666. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6667. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  6668. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6669. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  6670. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  6671. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  6672. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6673. }
  6674. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6675. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  6676. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6677. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6678. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6679. _this.resetTextureCache();
  6680. texture._width = info.width;
  6681. texture._height = info.height;
  6682. texture.isReady = true;
  6683. }, null, null, true);
  6684. }
  6685. else {
  6686. cascadeLoad(rootUrl, scene, function (imgs) {
  6687. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  6688. var height = width;
  6689. _this._prepareWorkingCanvas();
  6690. _this._workingCanvas.width = width;
  6691. _this._workingCanvas.height = height;
  6692. var faces = [
  6693. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6694. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6695. ];
  6696. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6697. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6698. for (var index = 0; index < faces.length; index++) {
  6699. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  6700. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  6701. }
  6702. if (!noMipmap) {
  6703. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6704. }
  6705. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6706. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6707. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6708. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6709. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6710. _this.resetTextureCache();
  6711. texture._width = width;
  6712. texture._height = height;
  6713. texture.isReady = true;
  6714. }, files);
  6715. }
  6716. return texture;
  6717. };
  6718. Engine.prototype.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback) {
  6719. var _this = this;
  6720. var gl = this._gl;
  6721. var texture = gl.createTexture();
  6722. scene._addPendingData(texture);
  6723. texture.isCube = true;
  6724. texture.references = 1;
  6725. texture.url = url;
  6726. var internalFormat = this._getInternalFormat(format);
  6727. var textureType = gl.UNSIGNED_BYTE;
  6728. if (type === Engine.TEXTURETYPE_FLOAT) {
  6729. textureType = gl.FLOAT;
  6730. }
  6731. var width = size;
  6732. var height = width;
  6733. var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  6734. texture._width = width;
  6735. texture._height = height;
  6736. var onerror = function () {
  6737. scene._removePendingData(texture);
  6738. };
  6739. var internalCallback = function (data) {
  6740. var rgbeDataArrays = callback(data);
  6741. var facesIndex = [
  6742. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6743. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6744. ];
  6745. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6746. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6747. for (var index = 0; index < facesIndex.length; index++) {
  6748. var faceData = rgbeDataArrays[index];
  6749. gl.texImage2D(facesIndex[index], 0, internalFormat, width, height, 0, internalFormat, textureType, faceData);
  6750. }
  6751. if (!noMipmap && isPot) {
  6752. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6753. }
  6754. else {
  6755. noMipmap = true;
  6756. }
  6757. if (textureType == gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
  6758. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  6759. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  6760. }
  6761. else {
  6762. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6763. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6764. }
  6765. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6766. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6767. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6768. texture.isReady = true;
  6769. _this.resetTextureCache();
  6770. scene._removePendingData(texture);
  6771. };
  6772. BABYLON.Tools.LoadFile(url, function (data) {
  6773. internalCallback(data);
  6774. }, onerror, scene.database, true);
  6775. return texture;
  6776. };
  6777. ;
  6778. Engine.prototype._releaseTexture = function (texture) {
  6779. var gl = this._gl;
  6780. if (texture._framebuffer) {
  6781. gl.deleteFramebuffer(texture._framebuffer);
  6782. }
  6783. if (texture._depthBuffer) {
  6784. gl.deleteRenderbuffer(texture._depthBuffer);
  6785. }
  6786. gl.deleteTexture(texture);
  6787. // Unbind channels
  6788. this.unbindAllTextures();
  6789. var index = this._loadedTexturesCache.indexOf(texture);
  6790. if (index !== -1) {
  6791. this._loadedTexturesCache.splice(index, 1);
  6792. }
  6793. };
  6794. Engine.prototype.bindSamplers = function (effect) {
  6795. this._gl.useProgram(effect.getProgram());
  6796. var samplers = effect.getSamplers();
  6797. for (var index = 0; index < samplers.length; index++) {
  6798. var uniform = effect.getUniform(samplers[index]);
  6799. this._gl.uniform1i(uniform, index);
  6800. }
  6801. this._currentEffect = null;
  6802. };
  6803. Engine.prototype._bindTexture = function (channel, texture) {
  6804. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6805. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6806. this._activeTexturesCache[channel] = null;
  6807. };
  6808. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  6809. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  6810. };
  6811. Engine.prototype.unbindAllTextures = function () {
  6812. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  6813. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6814. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6815. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6816. this._activeTexturesCache[channel] = null;
  6817. }
  6818. };
  6819. Engine.prototype.setTexture = function (channel, texture) {
  6820. if (channel < 0) {
  6821. return;
  6822. }
  6823. // Not ready?
  6824. if (!texture || !texture.isReady()) {
  6825. if (this._activeTexturesCache[channel] != null) {
  6826. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6827. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6828. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6829. this._activeTexturesCache[channel] = null;
  6830. }
  6831. return;
  6832. }
  6833. // Video
  6834. var alreadyActivated = false;
  6835. if (texture instanceof BABYLON.VideoTexture) {
  6836. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6837. alreadyActivated = true;
  6838. texture.update();
  6839. }
  6840. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  6841. texture.delayLoad();
  6842. return;
  6843. }
  6844. if (this._activeTexturesCache[channel] === texture) {
  6845. return;
  6846. }
  6847. this._activeTexturesCache[channel] = texture;
  6848. var internalTexture = texture.getInternalTexture();
  6849. if (!alreadyActivated) {
  6850. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6851. }
  6852. if (internalTexture.isCube) {
  6853. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  6854. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  6855. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  6856. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  6857. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  6858. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  6859. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  6860. }
  6861. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  6862. }
  6863. else {
  6864. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  6865. if (internalTexture._cachedWrapU !== texture.wrapU) {
  6866. internalTexture._cachedWrapU = texture.wrapU;
  6867. switch (texture.wrapU) {
  6868. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6869. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  6870. break;
  6871. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6872. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  6873. break;
  6874. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6875. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  6876. break;
  6877. }
  6878. }
  6879. if (internalTexture._cachedWrapV !== texture.wrapV) {
  6880. internalTexture._cachedWrapV = texture.wrapV;
  6881. switch (texture.wrapV) {
  6882. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6883. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  6884. break;
  6885. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6886. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  6887. break;
  6888. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6889. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  6890. break;
  6891. }
  6892. }
  6893. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  6894. }
  6895. };
  6896. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  6897. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  6898. var value = texture.anisotropicFilteringLevel;
  6899. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6900. value = 1;
  6901. }
  6902. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  6903. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  6904. texture._cachedAnisotropicFilteringLevel = value;
  6905. }
  6906. };
  6907. Engine.prototype.readPixels = function (x, y, width, height) {
  6908. var data = new Uint8Array(height * width * 4);
  6909. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  6910. return data;
  6911. };
  6912. Engine.prototype.releaseInternalTexture = function (texture) {
  6913. if (!texture) {
  6914. return;
  6915. }
  6916. texture.references--;
  6917. // Final reference ?
  6918. if (texture.references === 0) {
  6919. var texturesCache = this.getLoadedTexturesCache();
  6920. var index = texturesCache.indexOf(texture);
  6921. if (index > -1) {
  6922. texturesCache.splice(index, 1);
  6923. }
  6924. this._releaseTexture(texture);
  6925. }
  6926. };
  6927. // Dispose
  6928. Engine.prototype.dispose = function () {
  6929. this.hideLoadingUI();
  6930. this.stopRenderLoop();
  6931. // Release scenes
  6932. while (this.scenes.length) {
  6933. this.scenes[0].dispose();
  6934. }
  6935. // Release audio engine
  6936. Engine.audioEngine.dispose();
  6937. // Release effects
  6938. for (var name in this._compiledEffects) {
  6939. this._gl.deleteProgram(this._compiledEffects[name]._program);
  6940. }
  6941. // Unbind
  6942. for (var i in this._vertexAttribArrays) {
  6943. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  6944. continue;
  6945. }
  6946. this._gl.disableVertexAttribArray(i);
  6947. }
  6948. this._gl = null;
  6949. // Events
  6950. window.removeEventListener("blur", this._onBlur);
  6951. window.removeEventListener("focus", this._onFocus);
  6952. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  6953. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  6954. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  6955. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  6956. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  6957. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  6958. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  6959. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  6960. };
  6961. // Loading screen
  6962. Engine.prototype.displayLoadingUI = function () {
  6963. this._loadingScreen.displayLoadingUI();
  6964. };
  6965. Engine.prototype.hideLoadingUI = function () {
  6966. this._loadingScreen.hideLoadingUI();
  6967. };
  6968. Object.defineProperty(Engine.prototype, "loadingScreen", {
  6969. get: function () {
  6970. return this._loadingScreen;
  6971. },
  6972. set: function (loadingScreen) {
  6973. this._loadingScreen = loadingScreen;
  6974. },
  6975. enumerable: true,
  6976. configurable: true
  6977. });
  6978. Object.defineProperty(Engine.prototype, "loadingUIText", {
  6979. set: function (text) {
  6980. this._loadingScreen.loadingUIText = text;
  6981. },
  6982. enumerable: true,
  6983. configurable: true
  6984. });
  6985. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  6986. set: function (color) {
  6987. this._loadingScreen.loadingUIBackgroundColor = color;
  6988. },
  6989. enumerable: true,
  6990. configurable: true
  6991. });
  6992. // FPS
  6993. Engine.prototype.getFps = function () {
  6994. return this.fps;
  6995. };
  6996. Engine.prototype.getDeltaTime = function () {
  6997. return this.deltaTime;
  6998. };
  6999. Engine.prototype._measureFps = function () {
  7000. this.previousFramesDuration.push(BABYLON.Tools.Now);
  7001. var length = this.previousFramesDuration.length;
  7002. if (length >= 2) {
  7003. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  7004. }
  7005. if (length >= this.fpsRange) {
  7006. if (length > this.fpsRange) {
  7007. this.previousFramesDuration.splice(0, 1);
  7008. length = this.previousFramesDuration.length;
  7009. }
  7010. var sum = 0;
  7011. for (var id = 0; id < length - 1; id++) {
  7012. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  7013. }
  7014. this.fps = 1000.0 / (sum / (length - 1));
  7015. }
  7016. };
  7017. // Statics
  7018. Engine.isSupported = function () {
  7019. try {
  7020. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  7021. if (navigator.isCocoonJS) {
  7022. return true;
  7023. }
  7024. var tempcanvas = document.createElement("canvas");
  7025. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  7026. return gl != null && !!window.WebGLRenderingContext;
  7027. }
  7028. catch (e) {
  7029. return false;
  7030. }
  7031. };
  7032. // Const statics
  7033. Engine._ALPHA_DISABLE = 0;
  7034. Engine._ALPHA_ADD = 1;
  7035. Engine._ALPHA_COMBINE = 2;
  7036. Engine._ALPHA_SUBTRACT = 3;
  7037. Engine._ALPHA_MULTIPLY = 4;
  7038. Engine._ALPHA_MAXIMIZED = 5;
  7039. Engine._ALPHA_ONEONE = 6;
  7040. Engine._DELAYLOADSTATE_NONE = 0;
  7041. Engine._DELAYLOADSTATE_LOADED = 1;
  7042. Engine._DELAYLOADSTATE_LOADING = 2;
  7043. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  7044. Engine._TEXTUREFORMAT_ALPHA = 0;
  7045. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  7046. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  7047. Engine._TEXTUREFORMAT_RGB = 4;
  7048. Engine._TEXTUREFORMAT_RGBA = 5;
  7049. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  7050. Engine._TEXTURETYPE_FLOAT = 1;
  7051. // Updatable statics so stick with vars here
  7052. Engine.Epsilon = 0.001;
  7053. Engine.CollisionsEpsilon = 0.001;
  7054. Engine.CodeRepository = "src/";
  7055. Engine.ShadersRepository = "src/Shaders/";
  7056. return Engine;
  7057. })();
  7058. BABYLON.Engine = Engine;
  7059. })(BABYLON || (BABYLON = {}));
  7060. var BABYLON;
  7061. (function (BABYLON) {
  7062. /**
  7063. * Node is the basic class for all scene objects (Mesh, Light Camera).
  7064. */
  7065. var Node = (function () {
  7066. /**
  7067. * @constructor
  7068. * @param {string} name - the name and id to be given to this node
  7069. * @param {BABYLON.Scene} the scene this node will be added to
  7070. */
  7071. function Node(name, scene) {
  7072. this.state = "";
  7073. this.animations = new Array();
  7074. this._ranges = {};
  7075. this._childrenFlag = -1;
  7076. this._isEnabled = true;
  7077. this._isReady = true;
  7078. this._currentRenderId = -1;
  7079. this._parentRenderId = -1;
  7080. this.name = name;
  7081. this.id = name;
  7082. this._scene = scene;
  7083. this._initCache();
  7084. }
  7085. Node.prototype.getScene = function () {
  7086. return this._scene;
  7087. };
  7088. Node.prototype.getEngine = function () {
  7089. return this._scene.getEngine();
  7090. };
  7091. // override it in derived class
  7092. Node.prototype.getWorldMatrix = function () {
  7093. return BABYLON.Matrix.Identity();
  7094. };
  7095. // override it in derived class if you add new variables to the cache
  7096. // and call the parent class method
  7097. Node.prototype._initCache = function () {
  7098. this._cache = {};
  7099. this._cache.parent = undefined;
  7100. };
  7101. Node.prototype.updateCache = function (force) {
  7102. if (!force && this.isSynchronized())
  7103. return;
  7104. this._cache.parent = this.parent;
  7105. this._updateCache();
  7106. };
  7107. // override it in derived class if you add new variables to the cache
  7108. // and call the parent class method if !ignoreParentClass
  7109. Node.prototype._updateCache = function (ignoreParentClass) {
  7110. };
  7111. // override it in derived class if you add new variables to the cache
  7112. Node.prototype._isSynchronized = function () {
  7113. return true;
  7114. };
  7115. Node.prototype._markSyncedWithParent = function () {
  7116. this._parentRenderId = this.parent._currentRenderId;
  7117. };
  7118. Node.prototype.isSynchronizedWithParent = function () {
  7119. if (!this.parent) {
  7120. return true;
  7121. }
  7122. if (this._parentRenderId !== this.parent._currentRenderId) {
  7123. return false;
  7124. }
  7125. return this.parent.isSynchronized();
  7126. };
  7127. Node.prototype.isSynchronized = function (updateCache) {
  7128. var check = this.hasNewParent();
  7129. check = check || !this.isSynchronizedWithParent();
  7130. check = check || !this._isSynchronized();
  7131. if (updateCache)
  7132. this.updateCache(true);
  7133. return !check;
  7134. };
  7135. Node.prototype.hasNewParent = function (update) {
  7136. if (this._cache.parent === this.parent)
  7137. return false;
  7138. if (update)
  7139. this._cache.parent = this.parent;
  7140. return true;
  7141. };
  7142. /**
  7143. * Is this node ready to be used/rendered
  7144. * @return {boolean} is it ready
  7145. */
  7146. Node.prototype.isReady = function () {
  7147. return this._isReady;
  7148. };
  7149. /**
  7150. * Is this node enabled.
  7151. * If the node has a parent and is enabled, the parent will be inspected as well.
  7152. * @return {boolean} whether this node (and its parent) is enabled.
  7153. * @see setEnabled
  7154. */
  7155. Node.prototype.isEnabled = function () {
  7156. if (!this._isEnabled) {
  7157. return false;
  7158. }
  7159. if (this.parent) {
  7160. return this.parent.isEnabled();
  7161. }
  7162. return true;
  7163. };
  7164. /**
  7165. * Set the enabled state of this node.
  7166. * @param {boolean} value - the new enabled state
  7167. * @see isEnabled
  7168. */
  7169. Node.prototype.setEnabled = function (value) {
  7170. this._isEnabled = value;
  7171. };
  7172. /**
  7173. * Is this node a descendant of the given node.
  7174. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  7175. * @param {BABYLON.Node} ancestor - The parent node to inspect
  7176. * @see parent
  7177. */
  7178. Node.prototype.isDescendantOf = function (ancestor) {
  7179. if (this.parent) {
  7180. if (this.parent === ancestor) {
  7181. return true;
  7182. }
  7183. return this.parent.isDescendantOf(ancestor);
  7184. }
  7185. return false;
  7186. };
  7187. Node.prototype._getDescendants = function (list, results) {
  7188. for (var index = 0; index < list.length; index++) {
  7189. var item = list[index];
  7190. if (item.isDescendantOf(this)) {
  7191. results.push(item);
  7192. }
  7193. }
  7194. };
  7195. /**
  7196. * Will return all nodes that have this node as parent.
  7197. * @return {BABYLON.Node[]} all children nodes of all types.
  7198. */
  7199. Node.prototype.getDescendants = function () {
  7200. var results = [];
  7201. this._getDescendants(this._scene.meshes, results);
  7202. this._getDescendants(this._scene.lights, results);
  7203. this._getDescendants(this._scene.cameras, results);
  7204. return results;
  7205. };
  7206. Node.prototype._setReady = function (state) {
  7207. if (state === this._isReady) {
  7208. return;
  7209. }
  7210. if (!state) {
  7211. this._isReady = false;
  7212. return;
  7213. }
  7214. this._isReady = true;
  7215. if (this.onReady) {
  7216. this.onReady(this);
  7217. }
  7218. };
  7219. Node.prototype.getAnimationByName = function (name) {
  7220. for (var i = 0; i < this.animations.length; i++) {
  7221. var animation = this.animations[i];
  7222. if (animation.name === name) {
  7223. return animation;
  7224. }
  7225. }
  7226. return null;
  7227. };
  7228. Node.prototype.createAnimationRange = function (name, from, to) {
  7229. // check name not already in use
  7230. if (!this._ranges[name]) {
  7231. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  7232. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  7233. if (this.animations[i]) {
  7234. this.animations[i].createRange(name, from, to);
  7235. }
  7236. }
  7237. }
  7238. };
  7239. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  7240. if (deleteFrames === void 0) { deleteFrames = true; }
  7241. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  7242. if (this.animations[i]) {
  7243. this.animations[i].deleteRange(name, deleteFrames);
  7244. }
  7245. }
  7246. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  7247. };
  7248. Node.prototype.getAnimationRange = function (name) {
  7249. return this._ranges[name];
  7250. };
  7251. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  7252. var range = this.getAnimationRange(name);
  7253. if (!range) {
  7254. return null;
  7255. }
  7256. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  7257. };
  7258. Node.prototype.serializeAnimationRanges = function () {
  7259. var serializationRanges = [];
  7260. for (var name in this._ranges) {
  7261. var range = {};
  7262. range.name = name;
  7263. range.from = this._ranges[name].from;
  7264. range.to = this._ranges[name].to;
  7265. serializationRanges.push(range);
  7266. }
  7267. return serializationRanges;
  7268. };
  7269. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  7270. if (parsedNode.ranges) {
  7271. for (var index = 0; index < parsedNode.ranges.length; index++) {
  7272. var data = parsedNode.ranges[index];
  7273. node.createAnimationRange(data.name, data.from, data.to);
  7274. }
  7275. }
  7276. };
  7277. return Node;
  7278. })();
  7279. BABYLON.Node = Node;
  7280. })(BABYLON || (BABYLON = {}));
  7281. var BABYLON;
  7282. (function (BABYLON) {
  7283. var FilesInput = (function () {
  7284. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  7285. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  7286. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  7287. this._engine = p_engine;
  7288. this._canvas = p_canvas;
  7289. this._currentScene = p_scene;
  7290. this._sceneLoadedCallback = p_sceneLoadedCallback;
  7291. this._progressCallback = p_progressCallback;
  7292. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  7293. this._textureLoadingCallback = p_textureLoadingCallback;
  7294. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  7295. }
  7296. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  7297. var _this = this;
  7298. if (p_elementToMonitor) {
  7299. this._elementToMonitor = p_elementToMonitor;
  7300. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  7301. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  7302. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  7303. }
  7304. };
  7305. FilesInput.prototype.renderFunction = function () {
  7306. if (this._additionnalRenderLoopLogicCallback) {
  7307. this._additionnalRenderLoopLogicCallback();
  7308. }
  7309. if (this._currentScene) {
  7310. if (this._textureLoadingCallback) {
  7311. var remaining = this._currentScene.getWaitingItemsCount();
  7312. if (remaining > 0) {
  7313. this._textureLoadingCallback(remaining);
  7314. }
  7315. }
  7316. this._currentScene.render();
  7317. }
  7318. };
  7319. FilesInput.prototype.drag = function (e) {
  7320. e.stopPropagation();
  7321. e.preventDefault();
  7322. };
  7323. FilesInput.prototype.drop = function (eventDrop) {
  7324. eventDrop.stopPropagation();
  7325. eventDrop.preventDefault();
  7326. this.loadFiles(eventDrop);
  7327. };
  7328. FilesInput.prototype.loadFiles = function (event) {
  7329. if (this._startingProcessingFilesCallback)
  7330. this._startingProcessingFilesCallback();
  7331. // Handling data transfer via drag'n'drop
  7332. if (event && event.dataTransfer && event.dataTransfer.files) {
  7333. this._filesToLoad = event.dataTransfer.files;
  7334. }
  7335. // Handling files from input files
  7336. if (event && event.target && event.target.files) {
  7337. this._filesToLoad = event.target.files;
  7338. }
  7339. if (this._filesToLoad && this._filesToLoad.length > 0) {
  7340. for (var i = 0; i < this._filesToLoad.length; i++) {
  7341. switch (this._filesToLoad[i].type) {
  7342. case "image/jpeg":
  7343. case "image/png":
  7344. case "image/bmp":
  7345. FilesInput.FilesTextures[this._filesToLoad[i].name] = this._filesToLoad[i];
  7346. break;
  7347. case "image/targa":
  7348. case "image/vnd.ms-dds":
  7349. case "audio/wav":
  7350. case "audio/x-wav":
  7351. case "audio/mp3":
  7352. case "audio/mpeg":
  7353. case "audio/mpeg3":
  7354. case "audio/x-mpeg-3":
  7355. case "audio/ogg":
  7356. FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
  7357. break;
  7358. default:
  7359. if ((this._filesToLoad[i].name.indexOf(".babylon") !== -1 || this._filesToLoad[i].name.indexOf(".stl") !== -1 ||
  7360. this._filesToLoad[i].name.indexOf(".obj") !== -1 || this._filesToLoad[i].name.indexOf(".mtl") !== -1)
  7361. && this._filesToLoad[i].name.indexOf(".manifest") === -1
  7362. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  7363. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  7364. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  7365. this._sceneFileToLoad = this._filesToLoad[i];
  7366. }
  7367. break;
  7368. }
  7369. }
  7370. this.reload();
  7371. }
  7372. };
  7373. FilesInput.prototype.reload = function () {
  7374. var _this = this;
  7375. var that = this;
  7376. // If a ".babylon" file has been provided
  7377. if (this._sceneFileToLoad) {
  7378. if (this._currentScene) {
  7379. if (BABYLON.Tools.errorsCount > 0) {
  7380. BABYLON.Tools.ClearLogCache();
  7381. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  7382. }
  7383. this._engine.stopRenderLoop();
  7384. this._currentScene.dispose();
  7385. }
  7386. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  7387. that._currentScene = newScene;
  7388. // Wait for textures and shaders to be ready
  7389. that._currentScene.executeWhenReady(function () {
  7390. // Attach camera to canvas inputs
  7391. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  7392. that._currentScene.createDefaultCameraOrLight();
  7393. }
  7394. that._currentScene.activeCamera.attachControl(that._canvas);
  7395. if (that._sceneLoadedCallback) {
  7396. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  7397. }
  7398. that._engine.runRenderLoop(function () { that.renderFunction(); });
  7399. });
  7400. }, function (progress) {
  7401. if (_this._progressCallback) {
  7402. _this._progressCallback(progress);
  7403. }
  7404. });
  7405. }
  7406. else {
  7407. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  7408. }
  7409. };
  7410. FilesInput.FilesTextures = new Array();
  7411. FilesInput.FilesToLoad = new Array();
  7412. return FilesInput;
  7413. })();
  7414. BABYLON.FilesInput = FilesInput;
  7415. })(BABYLON || (BABYLON = {}));
  7416. var BABYLON;
  7417. (function (BABYLON) {
  7418. var IntersectionInfo = (function () {
  7419. function IntersectionInfo(bu, bv, distance) {
  7420. this.bu = bu;
  7421. this.bv = bv;
  7422. this.distance = distance;
  7423. this.faceId = 0;
  7424. this.subMeshId = 0;
  7425. }
  7426. return IntersectionInfo;
  7427. })();
  7428. BABYLON.IntersectionInfo = IntersectionInfo;
  7429. var PickingInfo = (function () {
  7430. function PickingInfo() {
  7431. this.hit = false;
  7432. this.distance = 0;
  7433. this.pickedPoint = null;
  7434. this.pickedMesh = null;
  7435. this.bu = 0;
  7436. this.bv = 0;
  7437. this.faceId = -1;
  7438. this.subMeshId = 0;
  7439. this.pickedSprite = null;
  7440. }
  7441. // Methods
  7442. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  7443. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  7444. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  7445. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  7446. return null;
  7447. }
  7448. var indices = this.pickedMesh.getIndices();
  7449. var result;
  7450. if (useVerticesNormals) {
  7451. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  7452. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  7453. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  7454. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  7455. normal0 = normal0.scale(this.bu);
  7456. normal1 = normal1.scale(this.bv);
  7457. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  7458. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  7459. }
  7460. else {
  7461. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  7462. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  7463. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  7464. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  7465. var p1p2 = vertex1.subtract(vertex2);
  7466. var p3p2 = vertex3.subtract(vertex2);
  7467. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  7468. }
  7469. if (useWorldCoordinates) {
  7470. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  7471. }
  7472. return BABYLON.Vector3.Normalize(result);
  7473. };
  7474. PickingInfo.prototype.getTextureCoordinates = function () {
  7475. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  7476. return null;
  7477. }
  7478. var indices = this.pickedMesh.getIndices();
  7479. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  7480. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  7481. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  7482. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  7483. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  7484. uv1 = uv1.scale(this.bu);
  7485. uv2 = uv2.scale(this.bv);
  7486. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  7487. };
  7488. return PickingInfo;
  7489. })();
  7490. BABYLON.PickingInfo = PickingInfo;
  7491. })(BABYLON || (BABYLON = {}));
  7492. var BABYLON;
  7493. (function (BABYLON) {
  7494. var BoundingSphere = (function () {
  7495. function BoundingSphere(minimum, maximum) {
  7496. this.minimum = minimum;
  7497. this.maximum = maximum;
  7498. this._tempRadiusVector = BABYLON.Vector3.Zero();
  7499. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  7500. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  7501. this.radius = distance * 0.5;
  7502. this.centerWorld = BABYLON.Vector3.Zero();
  7503. this._update(BABYLON.Matrix.Identity());
  7504. }
  7505. // Methods
  7506. BoundingSphere.prototype._update = function (world) {
  7507. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  7508. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  7509. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  7510. };
  7511. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  7512. for (var i = 0; i < 6; i++) {
  7513. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  7514. return false;
  7515. }
  7516. return true;
  7517. };
  7518. BoundingSphere.prototype.intersectsPoint = function (point) {
  7519. var x = this.centerWorld.x - point.x;
  7520. var y = this.centerWorld.y - point.y;
  7521. var z = this.centerWorld.z - point.z;
  7522. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7523. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  7524. return false;
  7525. return true;
  7526. };
  7527. // Statics
  7528. BoundingSphere.Intersects = function (sphere0, sphere1) {
  7529. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  7530. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  7531. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  7532. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7533. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  7534. return false;
  7535. return true;
  7536. };
  7537. return BoundingSphere;
  7538. })();
  7539. BABYLON.BoundingSphere = BoundingSphere;
  7540. })(BABYLON || (BABYLON = {}));
  7541. var BABYLON;
  7542. (function (BABYLON) {
  7543. var BoundingBox = (function () {
  7544. function BoundingBox(minimum, maximum) {
  7545. this.minimum = minimum;
  7546. this.maximum = maximum;
  7547. this.vectors = new Array();
  7548. this.vectorsWorld = new Array();
  7549. // Bounding vectors
  7550. this.vectors.push(this.minimum.clone());
  7551. this.vectors.push(this.maximum.clone());
  7552. this.vectors.push(this.minimum.clone());
  7553. this.vectors[2].x = this.maximum.x;
  7554. this.vectors.push(this.minimum.clone());
  7555. this.vectors[3].y = this.maximum.y;
  7556. this.vectors.push(this.minimum.clone());
  7557. this.vectors[4].z = this.maximum.z;
  7558. this.vectors.push(this.maximum.clone());
  7559. this.vectors[5].z = this.minimum.z;
  7560. this.vectors.push(this.maximum.clone());
  7561. this.vectors[6].x = this.minimum.x;
  7562. this.vectors.push(this.maximum.clone());
  7563. this.vectors[7].y = this.minimum.y;
  7564. // OBB
  7565. this.center = this.maximum.add(this.minimum).scale(0.5);
  7566. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  7567. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  7568. // World
  7569. for (var index = 0; index < this.vectors.length; index++) {
  7570. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  7571. }
  7572. this.minimumWorld = BABYLON.Vector3.Zero();
  7573. this.maximumWorld = BABYLON.Vector3.Zero();
  7574. this._update(BABYLON.Matrix.Identity());
  7575. }
  7576. // Methods
  7577. BoundingBox.prototype.getWorldMatrix = function () {
  7578. return this._worldMatrix;
  7579. };
  7580. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  7581. this._worldMatrix.copyFrom(matrix);
  7582. return this;
  7583. };
  7584. BoundingBox.prototype._update = function (world) {
  7585. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  7586. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  7587. for (var index = 0; index < this.vectors.length; index++) {
  7588. var v = this.vectorsWorld[index];
  7589. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  7590. if (v.x < this.minimumWorld.x)
  7591. this.minimumWorld.x = v.x;
  7592. if (v.y < this.minimumWorld.y)
  7593. this.minimumWorld.y = v.y;
  7594. if (v.z < this.minimumWorld.z)
  7595. this.minimumWorld.z = v.z;
  7596. if (v.x > this.maximumWorld.x)
  7597. this.maximumWorld.x = v.x;
  7598. if (v.y > this.maximumWorld.y)
  7599. this.maximumWorld.y = v.y;
  7600. if (v.z > this.maximumWorld.z)
  7601. this.maximumWorld.z = v.z;
  7602. }
  7603. // OBB
  7604. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  7605. this.center.scaleInPlace(0.5);
  7606. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  7607. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  7608. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  7609. this._worldMatrix = world;
  7610. };
  7611. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  7612. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  7613. };
  7614. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7615. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  7616. };
  7617. BoundingBox.prototype.intersectsPoint = function (point) {
  7618. var delta = -BABYLON.Engine.Epsilon;
  7619. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  7620. return false;
  7621. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  7622. return false;
  7623. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  7624. return false;
  7625. return true;
  7626. };
  7627. BoundingBox.prototype.intersectsSphere = function (sphere) {
  7628. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  7629. };
  7630. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  7631. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  7632. return false;
  7633. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  7634. return false;
  7635. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  7636. return false;
  7637. return true;
  7638. };
  7639. // Statics
  7640. BoundingBox.Intersects = function (box0, box1) {
  7641. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  7642. return false;
  7643. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  7644. return false;
  7645. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  7646. return false;
  7647. return true;
  7648. };
  7649. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  7650. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  7651. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  7652. return (num <= (sphereRadius * sphereRadius));
  7653. };
  7654. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  7655. for (var p = 0; p < 6; p++) {
  7656. for (var i = 0; i < 8; i++) {
  7657. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7658. return false;
  7659. }
  7660. }
  7661. }
  7662. return true;
  7663. };
  7664. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  7665. for (var p = 0; p < 6; p++) {
  7666. var inCount = 8;
  7667. for (var i = 0; i < 8; i++) {
  7668. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7669. --inCount;
  7670. }
  7671. else {
  7672. break;
  7673. }
  7674. }
  7675. if (inCount === 0)
  7676. return false;
  7677. }
  7678. return true;
  7679. };
  7680. return BoundingBox;
  7681. })();
  7682. BABYLON.BoundingBox = BoundingBox;
  7683. })(BABYLON || (BABYLON = {}));
  7684. var BABYLON;
  7685. (function (BABYLON) {
  7686. var computeBoxExtents = function (axis, box) {
  7687. var p = BABYLON.Vector3.Dot(box.center, axis);
  7688. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  7689. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  7690. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  7691. var r = r0 + r1 + r2;
  7692. return {
  7693. min: p - r,
  7694. max: p + r
  7695. };
  7696. };
  7697. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  7698. var axisOverlap = function (axis, box0, box1) {
  7699. var result0 = computeBoxExtents(axis, box0);
  7700. var result1 = computeBoxExtents(axis, box1);
  7701. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  7702. };
  7703. var BoundingInfo = (function () {
  7704. function BoundingInfo(minimum, maximum) {
  7705. this.minimum = minimum;
  7706. this.maximum = maximum;
  7707. this._isLocked = false;
  7708. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  7709. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  7710. }
  7711. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  7712. get: function () {
  7713. return this._isLocked;
  7714. },
  7715. set: function (value) {
  7716. this._isLocked = value;
  7717. },
  7718. enumerable: true,
  7719. configurable: true
  7720. });
  7721. // Methods
  7722. BoundingInfo.prototype.update = function (world) {
  7723. if (this._isLocked) {
  7724. return;
  7725. }
  7726. this.boundingBox._update(world);
  7727. this.boundingSphere._update(world);
  7728. };
  7729. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  7730. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  7731. return false;
  7732. return this.boundingBox.isInFrustum(frustumPlanes);
  7733. };
  7734. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7735. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  7736. };
  7737. BoundingInfo.prototype._checkCollision = function (collider) {
  7738. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  7739. };
  7740. BoundingInfo.prototype.intersectsPoint = function (point) {
  7741. if (!this.boundingSphere.centerWorld) {
  7742. return false;
  7743. }
  7744. if (!this.boundingSphere.intersectsPoint(point)) {
  7745. return false;
  7746. }
  7747. if (!this.boundingBox.intersectsPoint(point)) {
  7748. return false;
  7749. }
  7750. return true;
  7751. };
  7752. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  7753. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  7754. return false;
  7755. }
  7756. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  7757. return false;
  7758. }
  7759. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  7760. return false;
  7761. }
  7762. if (!precise) {
  7763. return true;
  7764. }
  7765. var box0 = this.boundingBox;
  7766. var box1 = boundingInfo.boundingBox;
  7767. if (!axisOverlap(box0.directions[0], box0, box1))
  7768. return false;
  7769. if (!axisOverlap(box0.directions[1], box0, box1))
  7770. return false;
  7771. if (!axisOverlap(box0.directions[2], box0, box1))
  7772. return false;
  7773. if (!axisOverlap(box1.directions[0], box0, box1))
  7774. return false;
  7775. if (!axisOverlap(box1.directions[1], box0, box1))
  7776. return false;
  7777. if (!axisOverlap(box1.directions[2], box0, box1))
  7778. return false;
  7779. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  7780. return false;
  7781. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  7782. return false;
  7783. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  7784. return false;
  7785. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  7786. return false;
  7787. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  7788. return false;
  7789. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  7790. return false;
  7791. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  7792. return false;
  7793. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  7794. return false;
  7795. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  7796. return false;
  7797. return true;
  7798. };
  7799. return BoundingInfo;
  7800. })();
  7801. BABYLON.BoundingInfo = BoundingInfo;
  7802. })(BABYLON || (BABYLON = {}));
  7803. var BABYLON;
  7804. (function (BABYLON) {
  7805. var AbstractMesh = (function (_super) {
  7806. __extends(AbstractMesh, _super);
  7807. // Constructor
  7808. function AbstractMesh(name, scene) {
  7809. var _this = this;
  7810. _super.call(this, name, scene);
  7811. // Properties
  7812. this.definedFacingForward = true; // orientation for POV movement & rotation
  7813. this.position = new BABYLON.Vector3(0, 0, 0);
  7814. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7815. this.scaling = new BABYLON.Vector3(1, 1, 1);
  7816. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  7817. this.visibility = 1.0;
  7818. this.alphaIndex = Number.MAX_VALUE;
  7819. this.infiniteDistance = false;
  7820. this.isVisible = true;
  7821. this.isPickable = true;
  7822. this.showBoundingBox = false;
  7823. this.showSubMeshesBoundingBox = false;
  7824. this.onDispose = null;
  7825. this.isBlocker = false;
  7826. this.renderingGroupId = 0;
  7827. this.receiveShadows = false;
  7828. this.renderOutline = false;
  7829. this.outlineColor = BABYLON.Color3.Red();
  7830. this.outlineWidth = 0.02;
  7831. this.renderOverlay = false;
  7832. this.overlayColor = BABYLON.Color3.Red();
  7833. this.overlayAlpha = 0.5;
  7834. this.hasVertexAlpha = false;
  7835. this.useVertexColors = true;
  7836. this.applyFog = true;
  7837. this.computeBonesUsingShaders = true;
  7838. this.scalingDeterminant = 1;
  7839. this.numBoneInfluencers = 4;
  7840. this.useOctreeForRenderingSelection = true;
  7841. this.useOctreeForPicking = true;
  7842. this.useOctreeForCollisions = true;
  7843. this.layerMask = 0x0FFFFFFF;
  7844. this.alwaysSelectAsActiveMesh = false;
  7845. // Physics
  7846. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  7847. // Collisions
  7848. this._checkCollisions = false;
  7849. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7850. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  7851. this._collider = new BABYLON.Collider();
  7852. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7853. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7854. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7855. // Edges
  7856. this.edgesWidth = 1;
  7857. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  7858. // Cache
  7859. this._localWorld = BABYLON.Matrix.Zero();
  7860. this._worldMatrix = BABYLON.Matrix.Zero();
  7861. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  7862. this._absolutePosition = BABYLON.Vector3.Zero();
  7863. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  7864. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  7865. this._isDirty = false;
  7866. this._pivotMatrix = BABYLON.Matrix.Identity();
  7867. this._isDisposed = false;
  7868. this._renderId = 0;
  7869. this._intersectionsInProgress = new Array();
  7870. this._onAfterWorldMatrixUpdate = new Array();
  7871. this._isWorldMatrixFrozen = false;
  7872. this._unIndexed = false;
  7873. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  7874. if (collidedMesh === void 0) { collidedMesh = null; }
  7875. //TODO move this to the collision coordinator!
  7876. if (_this.getScene().workerCollisions)
  7877. newPosition.multiplyInPlace(_this._collider.radius);
  7878. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  7879. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  7880. _this.position.addInPlace(_this._diffPositionForCollisions);
  7881. }
  7882. if (_this.onCollide && collidedMesh) {
  7883. _this.onCollide(collidedMesh);
  7884. }
  7885. if (_this.onCollisionPositionChange) {
  7886. _this.onCollisionPositionChange(_this.position);
  7887. }
  7888. };
  7889. scene.addMesh(this);
  7890. }
  7891. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  7892. get: function () {
  7893. return AbstractMesh._BILLBOARDMODE_NONE;
  7894. },
  7895. enumerable: true,
  7896. configurable: true
  7897. });
  7898. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  7899. get: function () {
  7900. return AbstractMesh._BILLBOARDMODE_X;
  7901. },
  7902. enumerable: true,
  7903. configurable: true
  7904. });
  7905. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  7906. get: function () {
  7907. return AbstractMesh._BILLBOARDMODE_Y;
  7908. },
  7909. enumerable: true,
  7910. configurable: true
  7911. });
  7912. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  7913. get: function () {
  7914. return AbstractMesh._BILLBOARDMODE_Z;
  7915. },
  7916. enumerable: true,
  7917. configurable: true
  7918. });
  7919. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  7920. get: function () {
  7921. return AbstractMesh._BILLBOARDMODE_ALL;
  7922. },
  7923. enumerable: true,
  7924. configurable: true
  7925. });
  7926. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  7927. get: function () {
  7928. return this._skeleton;
  7929. },
  7930. set: function (value) {
  7931. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  7932. this._skeleton._unregisterMeshWithPoseMatrix(this);
  7933. }
  7934. if (value && value.needInitialSkinMatrix) {
  7935. value._registerMeshWithPoseMatrix(this);
  7936. }
  7937. this._skeleton = value;
  7938. if (!this._skeleton) {
  7939. this._bonesTransformMatrices = null;
  7940. }
  7941. },
  7942. enumerable: true,
  7943. configurable: true
  7944. });
  7945. // Methods
  7946. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  7947. this._poseMatrix.copyFrom(matrix);
  7948. };
  7949. AbstractMesh.prototype.getPoseMatrix = function () {
  7950. return this._poseMatrix;
  7951. };
  7952. AbstractMesh.prototype.disableEdgesRendering = function () {
  7953. if (this._edgesRenderer !== undefined) {
  7954. this._edgesRenderer.dispose();
  7955. this._edgesRenderer = undefined;
  7956. }
  7957. };
  7958. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  7959. if (epsilon === void 0) { epsilon = 0.95; }
  7960. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  7961. this.disableEdgesRendering();
  7962. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  7963. };
  7964. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  7965. get: function () {
  7966. return false;
  7967. },
  7968. enumerable: true,
  7969. configurable: true
  7970. });
  7971. AbstractMesh.prototype.getLOD = function (camera) {
  7972. return this;
  7973. };
  7974. AbstractMesh.prototype.getTotalVertices = function () {
  7975. return 0;
  7976. };
  7977. AbstractMesh.prototype.getIndices = function () {
  7978. return null;
  7979. };
  7980. AbstractMesh.prototype.getVerticesData = function (kind) {
  7981. return null;
  7982. };
  7983. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  7984. return false;
  7985. };
  7986. AbstractMesh.prototype.getBoundingInfo = function () {
  7987. if (this._masterMesh) {
  7988. return this._masterMesh.getBoundingInfo();
  7989. }
  7990. if (!this._boundingInfo) {
  7991. this._updateBoundingInfo();
  7992. }
  7993. return this._boundingInfo;
  7994. };
  7995. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  7996. get: function () {
  7997. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  7998. },
  7999. enumerable: true,
  8000. configurable: true
  8001. });
  8002. AbstractMesh.prototype._preActivate = function () {
  8003. };
  8004. AbstractMesh.prototype._activate = function (renderId) {
  8005. this._renderId = renderId;
  8006. };
  8007. AbstractMesh.prototype.getWorldMatrix = function () {
  8008. if (this._masterMesh) {
  8009. return this._masterMesh.getWorldMatrix();
  8010. }
  8011. if (this._currentRenderId !== this.getScene().getRenderId()) {
  8012. this.computeWorldMatrix();
  8013. }
  8014. return this._worldMatrix;
  8015. };
  8016. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  8017. get: function () {
  8018. return this._worldMatrix;
  8019. },
  8020. enumerable: true,
  8021. configurable: true
  8022. });
  8023. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  8024. get: function () {
  8025. return this._absolutePosition;
  8026. },
  8027. enumerable: true,
  8028. configurable: true
  8029. });
  8030. AbstractMesh.prototype.freezeWorldMatrix = function () {
  8031. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  8032. this.computeWorldMatrix(true);
  8033. this._isWorldMatrixFrozen = true;
  8034. };
  8035. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  8036. this._isWorldMatrixFrozen = false;
  8037. this.computeWorldMatrix(true);
  8038. };
  8039. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  8040. get: function () {
  8041. return this._isWorldMatrixFrozen;
  8042. },
  8043. enumerable: true,
  8044. configurable: true
  8045. });
  8046. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  8047. axis.normalize();
  8048. if (!this.rotationQuaternion) {
  8049. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  8050. this.rotation = BABYLON.Vector3.Zero();
  8051. }
  8052. var rotationQuaternion;
  8053. if (!space || space === BABYLON.Space.LOCAL) {
  8054. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8055. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  8056. }
  8057. else {
  8058. if (this.parent) {
  8059. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8060. invertParentWorldMatrix.invert();
  8061. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  8062. }
  8063. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8064. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  8065. }
  8066. };
  8067. AbstractMesh.prototype.translate = function (axis, distance, space) {
  8068. var displacementVector = axis.scale(distance);
  8069. if (!space || space === BABYLON.Space.LOCAL) {
  8070. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  8071. this.setPositionWithLocalVector(tempV3);
  8072. }
  8073. else {
  8074. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  8075. }
  8076. };
  8077. AbstractMesh.prototype.getAbsolutePosition = function () {
  8078. this.computeWorldMatrix();
  8079. return this._absolutePosition;
  8080. };
  8081. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  8082. if (!absolutePosition) {
  8083. return;
  8084. }
  8085. var absolutePositionX;
  8086. var absolutePositionY;
  8087. var absolutePositionZ;
  8088. if (absolutePosition.x === undefined) {
  8089. if (arguments.length < 3) {
  8090. return;
  8091. }
  8092. absolutePositionX = arguments[0];
  8093. absolutePositionY = arguments[1];
  8094. absolutePositionZ = arguments[2];
  8095. }
  8096. else {
  8097. absolutePositionX = absolutePosition.x;
  8098. absolutePositionY = absolutePosition.y;
  8099. absolutePositionZ = absolutePosition.z;
  8100. }
  8101. if (this.parent) {
  8102. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8103. invertParentWorldMatrix.invert();
  8104. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  8105. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  8106. }
  8107. else {
  8108. this.position.x = absolutePositionX;
  8109. this.position.y = absolutePositionY;
  8110. this.position.z = absolutePositionZ;
  8111. }
  8112. };
  8113. // ================================== Point of View Movement =================================
  8114. /**
  8115. * Perform relative position change from the point of view of behind the front of the mesh.
  8116. * This is performed taking into account the meshes current rotation, so you do not have to care.
  8117. * Supports definition of mesh facing forward or backward.
  8118. * @param {number} amountRight
  8119. * @param {number} amountUp
  8120. * @param {number} amountForward
  8121. */
  8122. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  8123. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  8124. };
  8125. /**
  8126. * Calculate relative position change from the point of view of behind the front of the mesh.
  8127. * This is performed taking into account the meshes current rotation, so you do not have to care.
  8128. * Supports definition of mesh facing forward or backward.
  8129. * @param {number} amountRight
  8130. * @param {number} amountUp
  8131. * @param {number} amountForward
  8132. */
  8133. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  8134. var rotMatrix = new BABYLON.Matrix();
  8135. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  8136. rotQuaternion.toRotationMatrix(rotMatrix);
  8137. var translationDelta = BABYLON.Vector3.Zero();
  8138. var defForwardMult = this.definedFacingForward ? -1 : 1;
  8139. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  8140. return translationDelta;
  8141. };
  8142. // ================================== Point of View Rotation =================================
  8143. /**
  8144. * Perform relative rotation change from the point of view of behind the front of the mesh.
  8145. * Supports definition of mesh facing forward or backward.
  8146. * @param {number} flipBack
  8147. * @param {number} twirlClockwise
  8148. * @param {number} tiltRight
  8149. */
  8150. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  8151. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  8152. };
  8153. /**
  8154. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  8155. * Supports definition of mesh facing forward or backward.
  8156. * @param {number} flipBack
  8157. * @param {number} twirlClockwise
  8158. * @param {number} tiltRight
  8159. */
  8160. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  8161. var defForwardMult = this.definedFacingForward ? 1 : -1;
  8162. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  8163. };
  8164. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  8165. this._pivotMatrix = matrix;
  8166. this._cache.pivotMatrixUpdated = true;
  8167. };
  8168. AbstractMesh.prototype.getPivotMatrix = function () {
  8169. return this._pivotMatrix;
  8170. };
  8171. AbstractMesh.prototype._isSynchronized = function () {
  8172. if (this._isDirty) {
  8173. return false;
  8174. }
  8175. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  8176. return false;
  8177. if (this._cache.pivotMatrixUpdated) {
  8178. return false;
  8179. }
  8180. if (this.infiniteDistance) {
  8181. return false;
  8182. }
  8183. if (!this._cache.position.equals(this.position))
  8184. return false;
  8185. if (this.rotationQuaternion) {
  8186. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  8187. return false;
  8188. }
  8189. else {
  8190. if (!this._cache.rotation.equals(this.rotation))
  8191. return false;
  8192. }
  8193. if (!this._cache.scaling.equals(this.scaling))
  8194. return false;
  8195. return true;
  8196. };
  8197. AbstractMesh.prototype._initCache = function () {
  8198. _super.prototype._initCache.call(this);
  8199. this._cache.localMatrixUpdated = false;
  8200. this._cache.position = BABYLON.Vector3.Zero();
  8201. this._cache.scaling = BABYLON.Vector3.Zero();
  8202. this._cache.rotation = BABYLON.Vector3.Zero();
  8203. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  8204. this._cache.billboardMode = -1;
  8205. };
  8206. AbstractMesh.prototype.markAsDirty = function (property) {
  8207. if (property === "rotation") {
  8208. this.rotationQuaternion = null;
  8209. }
  8210. this._currentRenderId = Number.MAX_VALUE;
  8211. this._isDirty = true;
  8212. };
  8213. AbstractMesh.prototype._updateBoundingInfo = function () {
  8214. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  8215. this._boundingInfo.update(this.worldMatrixFromCache);
  8216. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  8217. };
  8218. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  8219. if (!this.subMeshes) {
  8220. return;
  8221. }
  8222. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  8223. var subMesh = this.subMeshes[subIndex];
  8224. if (!subMesh.IsGlobal) {
  8225. subMesh.updateBoundingInfo(matrix);
  8226. }
  8227. }
  8228. };
  8229. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  8230. if (this._isWorldMatrixFrozen) {
  8231. return this._worldMatrix;
  8232. }
  8233. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  8234. this._currentRenderId = this.getScene().getRenderId();
  8235. return this._worldMatrix;
  8236. }
  8237. this._cache.position.copyFrom(this.position);
  8238. this._cache.scaling.copyFrom(this.scaling);
  8239. this._cache.pivotMatrixUpdated = false;
  8240. this._cache.billboardMode = this.billboardMode;
  8241. this._currentRenderId = this.getScene().getRenderId();
  8242. this._isDirty = false;
  8243. // Scaling
  8244. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  8245. // Rotation
  8246. if (this.rotationQuaternion) {
  8247. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  8248. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  8249. }
  8250. else {
  8251. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  8252. this._cache.rotation.copyFrom(this.rotation);
  8253. }
  8254. // Translation
  8255. if (this.infiniteDistance && !this.parent) {
  8256. var camera = this.getScene().activeCamera;
  8257. if (camera) {
  8258. var cameraWorldMatrix = camera.getWorldMatrix();
  8259. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  8260. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  8261. }
  8262. }
  8263. else {
  8264. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  8265. }
  8266. // Composing transformations
  8267. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  8268. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  8269. // Billboarding
  8270. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  8271. var localPosition = this.position.clone();
  8272. var zero = this.getScene().activeCamera.globalPosition.clone();
  8273. if (this.parent && this.parent.position) {
  8274. localPosition.addInPlace(this.parent.position);
  8275. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, BABYLON.Tmp.Matrix[2]);
  8276. }
  8277. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  8278. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  8279. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  8280. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  8281. zero.y = localPosition.y + 0.001;
  8282. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  8283. zero.z = localPosition.z + 0.001;
  8284. }
  8285. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), BABYLON.Tmp.Matrix[3]);
  8286. BABYLON.Tmp.Matrix[3].m[12] = BABYLON.Tmp.Matrix[3].m[13] = BABYLON.Tmp.Matrix[3].m[14] = 0;
  8287. BABYLON.Tmp.Matrix[3].invert();
  8288. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[3], this._localWorld);
  8289. this._rotateYByPI.multiplyToRef(this._localWorld, BABYLON.Tmp.Matrix[5]);
  8290. }
  8291. // Local world
  8292. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  8293. // Parent
  8294. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  8295. this._markSyncedWithParent();
  8296. if (this._meshToBoneReferal) {
  8297. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  8298. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  8299. }
  8300. else {
  8301. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  8302. }
  8303. }
  8304. else {
  8305. this._worldMatrix.copyFrom(this._localWorld);
  8306. }
  8307. // Bounding info
  8308. this._updateBoundingInfo();
  8309. // Absolute position
  8310. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  8311. // Callbacks
  8312. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  8313. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  8314. }
  8315. if (!this._poseMatrix) {
  8316. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  8317. }
  8318. return this._worldMatrix;
  8319. };
  8320. /**
  8321. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  8322. * @param func: callback function to add
  8323. */
  8324. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  8325. this._onAfterWorldMatrixUpdate.push(func);
  8326. };
  8327. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  8328. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  8329. if (index > -1) {
  8330. this._onAfterWorldMatrixUpdate.splice(index, 1);
  8331. }
  8332. };
  8333. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  8334. this.computeWorldMatrix();
  8335. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  8336. };
  8337. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  8338. this.computeWorldMatrix();
  8339. var invLocalWorldMatrix = this._localWorld.clone();
  8340. invLocalWorldMatrix.invert();
  8341. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  8342. };
  8343. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  8344. this.computeWorldMatrix(true);
  8345. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  8346. };
  8347. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  8348. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  8349. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  8350. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  8351. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  8352. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  8353. /// <returns>Mesh oriented towards targetMesh</returns>
  8354. yawCor = yawCor || 0; // default to zero if undefined
  8355. pitchCor = pitchCor || 0;
  8356. rollCor = rollCor || 0;
  8357. var dv = targetPoint.subtract(this.position);
  8358. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  8359. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  8360. var pitch = Math.atan2(dv.y, len);
  8361. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  8362. };
  8363. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  8364. this._meshToBoneReferal = affectedMesh;
  8365. this.parent = bone;
  8366. if (bone.getWorldMatrix().determinant() < 0) {
  8367. this.scalingDeterminant *= -1;
  8368. }
  8369. };
  8370. AbstractMesh.prototype.detachFromBone = function () {
  8371. if (this.parent.getWorldMatrix().determinant() < 0) {
  8372. this.scalingDeterminant *= -1;
  8373. }
  8374. this._meshToBoneReferal = null;
  8375. this.parent = null;
  8376. };
  8377. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  8378. return this._boundingInfo.isInFrustum(frustumPlanes);
  8379. };
  8380. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  8381. if (!camera) {
  8382. camera = this.getScene().activeCamera;
  8383. }
  8384. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  8385. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  8386. return false;
  8387. }
  8388. return true;
  8389. };
  8390. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  8391. if (!this._boundingInfo || !mesh._boundingInfo) {
  8392. return false;
  8393. }
  8394. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  8395. };
  8396. AbstractMesh.prototype.intersectsPoint = function (point) {
  8397. if (!this._boundingInfo) {
  8398. return false;
  8399. }
  8400. return this._boundingInfo.intersectsPoint(point);
  8401. };
  8402. // Physics
  8403. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  8404. var physicsEngine = this.getScene().getPhysicsEngine();
  8405. if (!physicsEngine) {
  8406. return null;
  8407. }
  8408. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  8409. if (impostor.impostor) {
  8410. // Old API
  8411. options = impostor;
  8412. impostor = impostor.impostor;
  8413. }
  8414. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  8415. physicsEngine._unregisterMesh(this);
  8416. return null;
  8417. }
  8418. if (!options) {
  8419. options = { mass: 0, friction: 0.2, restitution: 0.2 };
  8420. }
  8421. else {
  8422. if (!options.mass && options.mass !== 0)
  8423. options.mass = 0;
  8424. if (!options.friction && options.friction !== 0)
  8425. options.friction = 0.2;
  8426. if (!options.restitution && options.restitution !== 0)
  8427. options.restitution = 0.2;
  8428. }
  8429. this._physicImpostor = impostor;
  8430. this._physicsMass = options.mass;
  8431. this._physicsFriction = options.friction;
  8432. this._physicRestitution = options.restitution;
  8433. return physicsEngine._registerMesh(this, impostor, options);
  8434. };
  8435. AbstractMesh.prototype.getPhysicsImpostor = function () {
  8436. if (!this._physicImpostor) {
  8437. return BABYLON.PhysicsEngine.NoImpostor;
  8438. }
  8439. return this._physicImpostor;
  8440. };
  8441. AbstractMesh.prototype.getPhysicsMass = function () {
  8442. if (!this._physicsMass) {
  8443. return 0;
  8444. }
  8445. return this._physicsMass;
  8446. };
  8447. AbstractMesh.prototype.getPhysicsFriction = function () {
  8448. if (!this._physicsFriction) {
  8449. return 0;
  8450. }
  8451. return this._physicsFriction;
  8452. };
  8453. AbstractMesh.prototype.getPhysicsRestitution = function () {
  8454. if (!this._physicRestitution) {
  8455. return 0;
  8456. }
  8457. return this._physicRestitution;
  8458. };
  8459. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  8460. if (!camera) {
  8461. camera = this.getScene().activeCamera;
  8462. }
  8463. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  8464. };
  8465. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  8466. if (!camera) {
  8467. camera = this.getScene().activeCamera;
  8468. }
  8469. return this.absolutePosition.subtract(camera.position).length();
  8470. };
  8471. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  8472. if (!this._physicImpostor) {
  8473. return;
  8474. }
  8475. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  8476. };
  8477. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  8478. if (!this._physicImpostor) {
  8479. return;
  8480. }
  8481. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  8482. };
  8483. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  8484. BABYLON.Tools.Warn("updatePhysicsBodyPosition() is deprecated, please use updatePhysicsBody()");
  8485. this.updatePhysicsBody();
  8486. };
  8487. AbstractMesh.prototype.updatePhysicsBody = function () {
  8488. if (!this._physicImpostor) {
  8489. return;
  8490. }
  8491. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  8492. };
  8493. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  8494. // Collisions
  8495. get: function () {
  8496. return this._checkCollisions;
  8497. },
  8498. set: function (collisionEnabled) {
  8499. this._checkCollisions = collisionEnabled;
  8500. if (this.getScene().workerCollisions) {
  8501. this.getScene().collisionCoordinator.onMeshUpdated(this);
  8502. }
  8503. },
  8504. enumerable: true,
  8505. configurable: true
  8506. });
  8507. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  8508. var globalPosition = this.getAbsolutePosition();
  8509. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  8510. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  8511. this._collider.radius = this.ellipsoid;
  8512. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  8513. };
  8514. // Submeshes octree
  8515. /**
  8516. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  8517. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  8518. */
  8519. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  8520. if (maxCapacity === void 0) { maxCapacity = 64; }
  8521. if (maxDepth === void 0) { maxDepth = 2; }
  8522. if (!this._submeshesOctree) {
  8523. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  8524. }
  8525. this.computeWorldMatrix(true);
  8526. // Update octree
  8527. var bbox = this.getBoundingInfo().boundingBox;
  8528. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  8529. return this._submeshesOctree;
  8530. };
  8531. // Collisions
  8532. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  8533. this._generatePointsArray();
  8534. // Transformation
  8535. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  8536. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  8537. subMesh._lastColliderWorldVertices = [];
  8538. subMesh._trianglePlanes = [];
  8539. var start = subMesh.verticesStart;
  8540. var end = (subMesh.verticesStart + subMesh.verticesCount);
  8541. for (var i = start; i < end; i++) {
  8542. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  8543. }
  8544. }
  8545. // Collide
  8546. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  8547. if (collider.collisionFound) {
  8548. collider.collidedMesh = this;
  8549. }
  8550. };
  8551. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  8552. var subMeshes;
  8553. var len;
  8554. // Octrees
  8555. if (this._submeshesOctree && this.useOctreeForCollisions) {
  8556. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  8557. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  8558. len = intersections.length;
  8559. subMeshes = intersections.data;
  8560. }
  8561. else {
  8562. subMeshes = this.subMeshes;
  8563. len = subMeshes.length;
  8564. }
  8565. for (var index = 0; index < len; index++) {
  8566. var subMesh = subMeshes[index];
  8567. // Bounding test
  8568. if (len > 1 && !subMesh._checkCollision(collider))
  8569. continue;
  8570. this._collideForSubMesh(subMesh, transformMatrix, collider);
  8571. }
  8572. };
  8573. AbstractMesh.prototype._checkCollision = function (collider) {
  8574. // Bounding box test
  8575. if (!this._boundingInfo._checkCollision(collider))
  8576. return;
  8577. // Transformation matrix
  8578. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  8579. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  8580. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  8581. };
  8582. // Picking
  8583. AbstractMesh.prototype._generatePointsArray = function () {
  8584. return false;
  8585. };
  8586. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  8587. var pickingInfo = new BABYLON.PickingInfo();
  8588. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  8589. return pickingInfo;
  8590. }
  8591. if (!this._generatePointsArray()) {
  8592. return pickingInfo;
  8593. }
  8594. var intersectInfo = null;
  8595. // Octrees
  8596. var subMeshes;
  8597. var len;
  8598. if (this._submeshesOctree && this.useOctreeForPicking) {
  8599. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  8600. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  8601. len = intersections.length;
  8602. subMeshes = intersections.data;
  8603. }
  8604. else {
  8605. subMeshes = this.subMeshes;
  8606. len = subMeshes.length;
  8607. }
  8608. for (var index = 0; index < len; index++) {
  8609. var subMesh = subMeshes[index];
  8610. // Bounding test
  8611. if (len > 1 && !subMesh.canIntersects(ray))
  8612. continue;
  8613. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  8614. if (currentIntersectInfo) {
  8615. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  8616. intersectInfo = currentIntersectInfo;
  8617. intersectInfo.subMeshId = index;
  8618. if (fastCheck) {
  8619. break;
  8620. }
  8621. }
  8622. }
  8623. }
  8624. if (intersectInfo) {
  8625. // Get picked point
  8626. var world = this.getWorldMatrix();
  8627. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  8628. var direction = ray.direction.clone();
  8629. direction = direction.scale(intersectInfo.distance);
  8630. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  8631. var pickedPoint = worldOrigin.add(worldDirection);
  8632. // Return result
  8633. pickingInfo.hit = true;
  8634. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  8635. pickingInfo.pickedPoint = pickedPoint;
  8636. pickingInfo.pickedMesh = this;
  8637. pickingInfo.bu = intersectInfo.bu;
  8638. pickingInfo.bv = intersectInfo.bv;
  8639. pickingInfo.faceId = intersectInfo.faceId;
  8640. pickingInfo.subMeshId = intersectInfo.subMeshId;
  8641. return pickingInfo;
  8642. }
  8643. return pickingInfo;
  8644. };
  8645. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8646. return null;
  8647. };
  8648. AbstractMesh.prototype.releaseSubMeshes = function () {
  8649. if (this.subMeshes) {
  8650. while (this.subMeshes.length) {
  8651. this.subMeshes[0].dispose();
  8652. }
  8653. }
  8654. else {
  8655. this.subMeshes = new Array();
  8656. }
  8657. };
  8658. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  8659. var index;
  8660. // Skeleton
  8661. this.skeleton = null;
  8662. // Animations
  8663. this.getScene().stopAnimation(this);
  8664. // Physics
  8665. if (this.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  8666. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  8667. }
  8668. // Intersections in progress
  8669. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  8670. var other = this._intersectionsInProgress[index];
  8671. var pos = other._intersectionsInProgress.indexOf(this);
  8672. other._intersectionsInProgress.splice(pos, 1);
  8673. }
  8674. this._intersectionsInProgress = [];
  8675. // Edges
  8676. if (this._edgesRenderer) {
  8677. this._edgesRenderer.dispose();
  8678. this._edgesRenderer = null;
  8679. }
  8680. // SubMeshes
  8681. this.releaseSubMeshes();
  8682. // Remove from scene
  8683. this.getScene().removeMesh(this);
  8684. if (!doNotRecurse) {
  8685. // Particles
  8686. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8687. if (this.getScene().particleSystems[index].emitter === this) {
  8688. this.getScene().particleSystems[index].dispose();
  8689. index--;
  8690. }
  8691. }
  8692. // Children
  8693. var objects = this.getScene().meshes.slice(0);
  8694. for (index = 0; index < objects.length; index++) {
  8695. if (objects[index].parent === this) {
  8696. objects[index].dispose();
  8697. }
  8698. }
  8699. }
  8700. else {
  8701. for (index = 0; index < this.getScene().meshes.length; index++) {
  8702. var obj = this.getScene().meshes[index];
  8703. if (obj.parent === this) {
  8704. obj.parent = null;
  8705. obj.computeWorldMatrix(true);
  8706. }
  8707. }
  8708. }
  8709. this._onAfterWorldMatrixUpdate = [];
  8710. this._isDisposed = true;
  8711. // Callback
  8712. if (this.onDispose) {
  8713. this.onDispose();
  8714. }
  8715. };
  8716. // Statics
  8717. AbstractMesh._BILLBOARDMODE_NONE = 0;
  8718. AbstractMesh._BILLBOARDMODE_X = 1;
  8719. AbstractMesh._BILLBOARDMODE_Y = 2;
  8720. AbstractMesh._BILLBOARDMODE_Z = 4;
  8721. AbstractMesh._BILLBOARDMODE_ALL = 7;
  8722. return AbstractMesh;
  8723. })(BABYLON.Node);
  8724. BABYLON.AbstractMesh = AbstractMesh;
  8725. })(BABYLON || (BABYLON = {}));
  8726. var BABYLON;
  8727. (function (BABYLON) {
  8728. var Light = (function (_super) {
  8729. __extends(Light, _super);
  8730. function Light(name, scene) {
  8731. _super.call(this, name, scene);
  8732. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  8733. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  8734. this.intensity = 1.0;
  8735. this.range = Number.MAX_VALUE;
  8736. this.includeOnlyWithLayerMask = 0;
  8737. this.includedOnlyMeshes = new Array();
  8738. this.excludedMeshes = new Array();
  8739. this.excludeWithLayerMask = 0;
  8740. this._excludedMeshesIds = new Array();
  8741. this._includedOnlyMeshesIds = new Array();
  8742. scene.addLight(this);
  8743. }
  8744. Light.prototype.getShadowGenerator = function () {
  8745. return this._shadowGenerator;
  8746. };
  8747. Light.prototype.getAbsolutePosition = function () {
  8748. return BABYLON.Vector3.Zero();
  8749. };
  8750. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  8751. };
  8752. Light.prototype._getWorldMatrix = function () {
  8753. return BABYLON.Matrix.Identity();
  8754. };
  8755. Light.prototype.canAffectMesh = function (mesh) {
  8756. if (!mesh) {
  8757. return true;
  8758. }
  8759. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  8760. return false;
  8761. }
  8762. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  8763. return false;
  8764. }
  8765. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  8766. return false;
  8767. }
  8768. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  8769. return false;
  8770. }
  8771. return true;
  8772. };
  8773. Light.prototype.getWorldMatrix = function () {
  8774. this._currentRenderId = this.getScene().getRenderId();
  8775. var worldMatrix = this._getWorldMatrix();
  8776. if (this.parent && this.parent.getWorldMatrix) {
  8777. if (!this._parentedWorldMatrix) {
  8778. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  8779. }
  8780. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  8781. this._markSyncedWithParent();
  8782. return this._parentedWorldMatrix;
  8783. }
  8784. return worldMatrix;
  8785. };
  8786. Light.prototype.dispose = function () {
  8787. if (this._shadowGenerator) {
  8788. this._shadowGenerator.dispose();
  8789. this._shadowGenerator = null;
  8790. }
  8791. // Animations
  8792. this.getScene().stopAnimation(this);
  8793. // Remove from scene
  8794. this.getScene().removeLight(this);
  8795. };
  8796. Light.prototype.serialize = function () {
  8797. var serializationObject = {};
  8798. serializationObject.name = this.name;
  8799. serializationObject.id = this.id;
  8800. serializationObject.tags = BABYLON.Tags.GetTags(this);
  8801. if (this.intensity) {
  8802. serializationObject.intensity = this.intensity;
  8803. }
  8804. // Parent
  8805. if (this.parent) {
  8806. serializationObject.parentId = this.parent.id;
  8807. }
  8808. serializationObject.range = this.range;
  8809. serializationObject.diffuse = this.diffuse.asArray();
  8810. serializationObject.specular = this.specular.asArray();
  8811. return serializationObject;
  8812. };
  8813. Light.Parse = function (parsedLight, scene) {
  8814. var light;
  8815. switch (parsedLight.type) {
  8816. case 0:
  8817. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  8818. break;
  8819. case 1:
  8820. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  8821. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  8822. break;
  8823. case 2:
  8824. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  8825. break;
  8826. case 3:
  8827. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  8828. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  8829. break;
  8830. }
  8831. light.id = parsedLight.id;
  8832. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  8833. if (parsedLight.intensity !== undefined) {
  8834. light.intensity = parsedLight.intensity;
  8835. }
  8836. if (parsedLight.range) {
  8837. light.range = parsedLight.range;
  8838. }
  8839. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  8840. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  8841. if (parsedLight.excludedMeshesIds) {
  8842. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  8843. }
  8844. // Parent
  8845. if (parsedLight.parentId) {
  8846. light._waitingParentId = parsedLight.parentId;
  8847. }
  8848. if (parsedLight.includedOnlyMeshesIds) {
  8849. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  8850. }
  8851. // Animations
  8852. if (parsedLight.animations) {
  8853. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  8854. var parsedAnimation = parsedLight.animations[animationIndex];
  8855. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  8856. }
  8857. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  8858. }
  8859. if (parsedLight.autoAnimate) {
  8860. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  8861. }
  8862. return light;
  8863. };
  8864. return Light;
  8865. })(BABYLON.Node);
  8866. BABYLON.Light = Light;
  8867. })(BABYLON || (BABYLON = {}));
  8868. var BABYLON;
  8869. (function (BABYLON) {
  8870. var PointLight = (function (_super) {
  8871. __extends(PointLight, _super);
  8872. function PointLight(name, position, scene) {
  8873. _super.call(this, name, scene);
  8874. this.position = position;
  8875. }
  8876. PointLight.prototype.getAbsolutePosition = function () {
  8877. return this.transformedPosition ? this.transformedPosition : this.position;
  8878. };
  8879. PointLight.prototype.computeTransformedPosition = function () {
  8880. if (this.parent && this.parent.getWorldMatrix) {
  8881. if (!this.transformedPosition) {
  8882. this.transformedPosition = BABYLON.Vector3.Zero();
  8883. }
  8884. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8885. return true;
  8886. }
  8887. return false;
  8888. };
  8889. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  8890. if (this.parent && this.parent.getWorldMatrix) {
  8891. this.computeTransformedPosition();
  8892. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
  8893. return;
  8894. }
  8895. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  8896. };
  8897. PointLight.prototype.needCube = function () {
  8898. return true;
  8899. };
  8900. PointLight.prototype.supportsVSM = function () {
  8901. return false;
  8902. };
  8903. PointLight.prototype.needRefreshPerFrame = function () {
  8904. return false;
  8905. };
  8906. PointLight.prototype.getShadowDirection = function (faceIndex) {
  8907. switch (faceIndex) {
  8908. case 0:
  8909. return new BABYLON.Vector3(1, 0, 0);
  8910. case 1:
  8911. return new BABYLON.Vector3(-1, 0, 0);
  8912. case 2:
  8913. return new BABYLON.Vector3(0, -1, 0);
  8914. case 3:
  8915. return new BABYLON.Vector3(0, 1, 0);
  8916. case 4:
  8917. return new BABYLON.Vector3(0, 0, 1);
  8918. case 5:
  8919. return new BABYLON.Vector3(0, 0, -1);
  8920. }
  8921. return BABYLON.Vector3.Zero();
  8922. };
  8923. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8924. var activeCamera = this.getScene().activeCamera;
  8925. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  8926. };
  8927. PointLight.prototype._getWorldMatrix = function () {
  8928. if (!this._worldMatrix) {
  8929. this._worldMatrix = BABYLON.Matrix.Identity();
  8930. }
  8931. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8932. return this._worldMatrix;
  8933. };
  8934. PointLight.prototype.serialize = function () {
  8935. var serializationObject = _super.prototype.serialize.call(this);
  8936. serializationObject.type = 0;
  8937. serializationObject.position = this.position.asArray();
  8938. return serializationObject;
  8939. };
  8940. return PointLight;
  8941. })(BABYLON.Light);
  8942. BABYLON.PointLight = PointLight;
  8943. })(BABYLON || (BABYLON = {}));
  8944. var BABYLON;
  8945. (function (BABYLON) {
  8946. var SpotLight = (function (_super) {
  8947. __extends(SpotLight, _super);
  8948. function SpotLight(name, position, direction, angle, exponent, scene) {
  8949. _super.call(this, name, scene);
  8950. this.position = position;
  8951. this.direction = direction;
  8952. this.angle = angle;
  8953. this.exponent = exponent;
  8954. }
  8955. SpotLight.prototype.getAbsolutePosition = function () {
  8956. return this.transformedPosition ? this.transformedPosition : this.position;
  8957. };
  8958. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8959. var activeCamera = this.getScene().activeCamera;
  8960. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  8961. };
  8962. SpotLight.prototype.needCube = function () {
  8963. return false;
  8964. };
  8965. SpotLight.prototype.supportsVSM = function () {
  8966. return true;
  8967. };
  8968. SpotLight.prototype.needRefreshPerFrame = function () {
  8969. return false;
  8970. };
  8971. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  8972. return this.direction;
  8973. };
  8974. SpotLight.prototype.setDirectionToTarget = function (target) {
  8975. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8976. return this.direction;
  8977. };
  8978. SpotLight.prototype.computeTransformedPosition = function () {
  8979. if (this.parent && this.parent.getWorldMatrix) {
  8980. if (!this.transformedPosition) {
  8981. this.transformedPosition = BABYLON.Vector3.Zero();
  8982. }
  8983. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8984. return true;
  8985. }
  8986. return false;
  8987. };
  8988. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  8989. var normalizeDirection;
  8990. if (this.parent && this.parent.getWorldMatrix) {
  8991. if (!this._transformedDirection) {
  8992. this._transformedDirection = BABYLON.Vector3.Zero();
  8993. }
  8994. this.computeTransformedPosition();
  8995. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8996. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  8997. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  8998. }
  8999. else {
  9000. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  9001. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  9002. }
  9003. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  9004. };
  9005. SpotLight.prototype._getWorldMatrix = function () {
  9006. if (!this._worldMatrix) {
  9007. this._worldMatrix = BABYLON.Matrix.Identity();
  9008. }
  9009. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  9010. return this._worldMatrix;
  9011. };
  9012. SpotLight.prototype.serialize = function () {
  9013. var serializationObject = _super.prototype.serialize.call(this);
  9014. serializationObject.type = 2;
  9015. serializationObject.position = this.position.asArray();
  9016. serializationObject.direction = this.position.asArray();
  9017. serializationObject.angle = this.angle;
  9018. serializationObject.exponent = this.exponent;
  9019. return serializationObject;
  9020. };
  9021. return SpotLight;
  9022. })(BABYLON.Light);
  9023. BABYLON.SpotLight = SpotLight;
  9024. })(BABYLON || (BABYLON = {}));
  9025. var BABYLON;
  9026. (function (BABYLON) {
  9027. var HemisphericLight = (function (_super) {
  9028. __extends(HemisphericLight, _super);
  9029. function HemisphericLight(name, direction, scene) {
  9030. _super.call(this, name, scene);
  9031. this.direction = direction;
  9032. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  9033. }
  9034. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  9035. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  9036. return this.direction;
  9037. };
  9038. HemisphericLight.prototype.getShadowGenerator = function () {
  9039. return null;
  9040. };
  9041. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  9042. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  9043. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  9044. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  9045. };
  9046. HemisphericLight.prototype._getWorldMatrix = function () {
  9047. if (!this._worldMatrix) {
  9048. this._worldMatrix = BABYLON.Matrix.Identity();
  9049. }
  9050. return this._worldMatrix;
  9051. };
  9052. HemisphericLight.prototype.serialize = function () {
  9053. var serializationObject = _super.prototype.serialize.call(this);
  9054. serializationObject.type = 3;
  9055. serializationObject.direction = this.direction.asArray();
  9056. serializationObject.groundColor = this.groundColor.asArray();
  9057. return serializationObject;
  9058. };
  9059. return HemisphericLight;
  9060. })(BABYLON.Light);
  9061. BABYLON.HemisphericLight = HemisphericLight;
  9062. })(BABYLON || (BABYLON = {}));
  9063. var BABYLON;
  9064. (function (BABYLON) {
  9065. var DirectionalLight = (function (_super) {
  9066. __extends(DirectionalLight, _super);
  9067. function DirectionalLight(name, direction, scene) {
  9068. _super.call(this, name, scene);
  9069. this.direction = direction;
  9070. this.shadowOrthoScale = 0.5;
  9071. this.autoUpdateExtends = true;
  9072. // Cache
  9073. this._orthoLeft = Number.MAX_VALUE;
  9074. this._orthoRight = Number.MIN_VALUE;
  9075. this._orthoTop = Number.MIN_VALUE;
  9076. this._orthoBottom = Number.MAX_VALUE;
  9077. this.position = direction.scale(-1);
  9078. }
  9079. DirectionalLight.prototype.getAbsolutePosition = function () {
  9080. return this.transformedPosition ? this.transformedPosition : this.position;
  9081. };
  9082. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  9083. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  9084. return this.direction;
  9085. };
  9086. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  9087. var activeCamera = this.getScene().activeCamera;
  9088. // Check extends
  9089. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  9090. var tempVector3 = BABYLON.Vector3.Zero();
  9091. this._orthoLeft = Number.MAX_VALUE;
  9092. this._orthoRight = Number.MIN_VALUE;
  9093. this._orthoTop = Number.MIN_VALUE;
  9094. this._orthoBottom = Number.MAX_VALUE;
  9095. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  9096. var mesh = renderList[meshIndex];
  9097. if (!mesh) {
  9098. continue;
  9099. }
  9100. var boundingInfo = mesh.getBoundingInfo();
  9101. if (!boundingInfo) {
  9102. continue;
  9103. }
  9104. var boundingBox = boundingInfo.boundingBox;
  9105. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  9106. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  9107. if (tempVector3.x < this._orthoLeft)
  9108. this._orthoLeft = tempVector3.x;
  9109. if (tempVector3.y < this._orthoBottom)
  9110. this._orthoBottom = tempVector3.y;
  9111. if (tempVector3.x > this._orthoRight)
  9112. this._orthoRight = tempVector3.x;
  9113. if (tempVector3.y > this._orthoTop)
  9114. this._orthoTop = tempVector3.y;
  9115. }
  9116. }
  9117. }
  9118. var xOffset = this._orthoRight - this._orthoLeft;
  9119. var yOffset = this._orthoTop - this._orthoBottom;
  9120. 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);
  9121. };
  9122. DirectionalLight.prototype.supportsVSM = function () {
  9123. return true;
  9124. };
  9125. DirectionalLight.prototype.needRefreshPerFrame = function () {
  9126. return true;
  9127. };
  9128. DirectionalLight.prototype.needCube = function () {
  9129. return false;
  9130. };
  9131. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  9132. return this.direction;
  9133. };
  9134. DirectionalLight.prototype.computeTransformedPosition = function () {
  9135. if (this.parent && this.parent.getWorldMatrix) {
  9136. if (!this.transformedPosition) {
  9137. this.transformedPosition = BABYLON.Vector3.Zero();
  9138. }
  9139. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  9140. return true;
  9141. }
  9142. return false;
  9143. };
  9144. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  9145. if (this.parent && this.parent.getWorldMatrix) {
  9146. if (!this._transformedDirection) {
  9147. this._transformedDirection = BABYLON.Vector3.Zero();
  9148. }
  9149. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  9150. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  9151. return;
  9152. }
  9153. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  9154. };
  9155. DirectionalLight.prototype._getWorldMatrix = function () {
  9156. if (!this._worldMatrix) {
  9157. this._worldMatrix = BABYLON.Matrix.Identity();
  9158. }
  9159. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  9160. return this._worldMatrix;
  9161. };
  9162. DirectionalLight.prototype.serialize = function () {
  9163. var serializationObject = _super.prototype.serialize.call(this);
  9164. serializationObject.type = 1;
  9165. serializationObject.position = this.position.asArray();
  9166. serializationObject.direction = this.direction.asArray();
  9167. return serializationObject;
  9168. };
  9169. return DirectionalLight;
  9170. })(BABYLON.Light);
  9171. BABYLON.DirectionalLight = DirectionalLight;
  9172. })(BABYLON || (BABYLON = {}));
  9173. var BABYLON;
  9174. (function (BABYLON) {
  9175. var ShadowGenerator = (function () {
  9176. function ShadowGenerator(mapSize, light) {
  9177. var _this = this;
  9178. // Members
  9179. this._filter = ShadowGenerator.FILTER_NONE;
  9180. this.blurScale = 2;
  9181. this._blurBoxOffset = 0;
  9182. this._bias = 0.00005;
  9183. this._lightDirection = BABYLON.Vector3.Zero();
  9184. this.forceBackFacesOnly = false;
  9185. this._darkness = 0;
  9186. this._transparencyShadow = false;
  9187. this._viewMatrix = BABYLON.Matrix.Zero();
  9188. this._projectionMatrix = BABYLON.Matrix.Zero();
  9189. this._transformMatrix = BABYLON.Matrix.Zero();
  9190. this._worldViewProjection = BABYLON.Matrix.Zero();
  9191. this._currentFaceIndex = 0;
  9192. this._currentFaceIndexCache = 0;
  9193. this._light = light;
  9194. this._scene = light.getScene();
  9195. this._mapSize = mapSize;
  9196. light._shadowGenerator = this;
  9197. // Render target
  9198. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, light.needCube());
  9199. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9200. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9201. this._shadowMap.anisotropicFilteringLevel = 1;
  9202. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9203. this._shadowMap.renderParticles = false;
  9204. this._shadowMap.onBeforeRender = function (faceIndex) {
  9205. _this._currentFaceIndex = faceIndex;
  9206. };
  9207. this._shadowMap.onAfterUnbind = function () {
  9208. if (!_this.useBlurVarianceShadowMap) {
  9209. return;
  9210. }
  9211. if (!_this._shadowMap2) {
  9212. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  9213. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9214. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9215. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  9216. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  9217. _this._downSamplePostprocess.onApply = function (effect) {
  9218. effect.setTexture("textureSampler", _this._shadowMap);
  9219. };
  9220. _this.blurBoxOffset = 1;
  9221. }
  9222. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  9223. };
  9224. // Custom render function
  9225. var renderSubMesh = function (subMesh) {
  9226. var mesh = subMesh.getRenderingMesh();
  9227. var scene = _this._scene;
  9228. var engine = scene.getEngine();
  9229. // Culling
  9230. engine.setState(subMesh.getMaterial().backFaceCulling);
  9231. // Managing instances
  9232. var batch = mesh._getInstancesRenderList(subMesh._id);
  9233. if (batch.mustReturn) {
  9234. return;
  9235. }
  9236. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  9237. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  9238. engine.enableEffect(_this._effect);
  9239. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  9240. var material = subMesh.getMaterial();
  9241. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  9242. _this._effect.setVector3("lightPosition", _this.getLight().position);
  9243. if (_this.getLight().needCube()) {
  9244. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  9245. }
  9246. // Alpha test
  9247. if (material && material.needAlphaTesting()) {
  9248. var alphaTexture = material.getAlphaTestTexture();
  9249. _this._effect.setTexture("diffuseSampler", alphaTexture);
  9250. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  9251. }
  9252. // Bones
  9253. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  9254. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  9255. }
  9256. if (_this.forceBackFacesOnly) {
  9257. engine.setState(true, 0, false, true);
  9258. }
  9259. // Draw
  9260. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  9261. if (_this.forceBackFacesOnly) {
  9262. engine.setState(true, 0, false, false);
  9263. }
  9264. }
  9265. else {
  9266. // Need to reset refresh rate of the shadowMap
  9267. _this._shadowMap.resetRefreshCounter();
  9268. }
  9269. };
  9270. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  9271. var index;
  9272. for (index = 0; index < opaqueSubMeshes.length; index++) {
  9273. renderSubMesh(opaqueSubMeshes.data[index]);
  9274. }
  9275. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  9276. renderSubMesh(alphaTestSubMeshes.data[index]);
  9277. }
  9278. if (_this._transparencyShadow) {
  9279. for (index = 0; index < transparentSubMeshes.length; index++) {
  9280. renderSubMesh(transparentSubMeshes.data[index]);
  9281. }
  9282. }
  9283. };
  9284. this._shadowMap.onClear = function (engine) {
  9285. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  9286. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  9287. }
  9288. else {
  9289. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  9290. }
  9291. };
  9292. }
  9293. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  9294. // Static
  9295. get: function () {
  9296. return ShadowGenerator._FILTER_NONE;
  9297. },
  9298. enumerable: true,
  9299. configurable: true
  9300. });
  9301. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  9302. get: function () {
  9303. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  9304. },
  9305. enumerable: true,
  9306. configurable: true
  9307. });
  9308. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  9309. get: function () {
  9310. return ShadowGenerator._FILTER_POISSONSAMPLING;
  9311. },
  9312. enumerable: true,
  9313. configurable: true
  9314. });
  9315. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  9316. get: function () {
  9317. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  9318. },
  9319. enumerable: true,
  9320. configurable: true
  9321. });
  9322. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  9323. get: function () {
  9324. return this._bias;
  9325. },
  9326. set: function (bias) {
  9327. this._bias = bias;
  9328. },
  9329. enumerable: true,
  9330. configurable: true
  9331. });
  9332. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  9333. get: function () {
  9334. return this._blurBoxOffset;
  9335. },
  9336. set: function (value) {
  9337. var _this = this;
  9338. if (this._blurBoxOffset === value) {
  9339. return;
  9340. }
  9341. this._blurBoxOffset = value;
  9342. if (this._boxBlurPostprocess) {
  9343. this._boxBlurPostprocess.dispose();
  9344. }
  9345. 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);
  9346. this._boxBlurPostprocess.onApply = function (effect) {
  9347. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  9348. };
  9349. },
  9350. enumerable: true,
  9351. configurable: true
  9352. });
  9353. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  9354. get: function () {
  9355. return this._filter;
  9356. },
  9357. set: function (value) {
  9358. if (this._filter === value) {
  9359. return;
  9360. }
  9361. this._filter = value;
  9362. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  9363. this._shadowMap.anisotropicFilteringLevel = 16;
  9364. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  9365. }
  9366. else {
  9367. this._shadowMap.anisotropicFilteringLevel = 1;
  9368. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9369. }
  9370. },
  9371. enumerable: true,
  9372. configurable: true
  9373. });
  9374. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  9375. get: function () {
  9376. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  9377. },
  9378. set: function (value) {
  9379. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  9380. },
  9381. enumerable: true,
  9382. configurable: true
  9383. });
  9384. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  9385. get: function () {
  9386. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  9387. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  9388. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  9389. },
  9390. set: function (value) {
  9391. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  9392. },
  9393. enumerable: true,
  9394. configurable: true
  9395. });
  9396. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  9397. get: function () {
  9398. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  9399. },
  9400. set: function (value) {
  9401. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  9402. },
  9403. enumerable: true,
  9404. configurable: true
  9405. });
  9406. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  9407. var defines = [];
  9408. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  9409. defines.push("#define VSM");
  9410. }
  9411. if (this.getLight().needCube()) {
  9412. defines.push("#define CUBEMAP");
  9413. }
  9414. var attribs = [BABYLON.VertexBuffer.PositionKind];
  9415. var mesh = subMesh.getMesh();
  9416. var material = subMesh.getMaterial();
  9417. // Alpha test
  9418. if (material && material.needAlphaTesting()) {
  9419. defines.push("#define ALPHATEST");
  9420. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  9421. attribs.push(BABYLON.VertexBuffer.UVKind);
  9422. defines.push("#define UV1");
  9423. }
  9424. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  9425. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  9426. defines.push("#define UV2");
  9427. }
  9428. }
  9429. // Bones
  9430. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  9431. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  9432. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  9433. if (mesh.numBoneInfluencers > 4) {
  9434. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  9435. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  9436. }
  9437. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  9438. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  9439. }
  9440. else {
  9441. defines.push("#define NUM_BONE_INFLUENCERS 0");
  9442. }
  9443. // Instances
  9444. if (useInstances) {
  9445. defines.push("#define INSTANCES");
  9446. attribs.push("world0");
  9447. attribs.push("world1");
  9448. attribs.push("world2");
  9449. attribs.push("world3");
  9450. }
  9451. // Get correct effect
  9452. var join = defines.join("\n");
  9453. if (this._cachedDefines !== join) {
  9454. this._cachedDefines = join;
  9455. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues"], ["diffuseSampler"], join);
  9456. }
  9457. return this._effect.isReady();
  9458. };
  9459. ShadowGenerator.prototype.getShadowMap = function () {
  9460. return this._shadowMap;
  9461. };
  9462. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  9463. if (this._shadowMap2) {
  9464. return this._shadowMap2;
  9465. }
  9466. return this._shadowMap;
  9467. };
  9468. ShadowGenerator.prototype.getLight = function () {
  9469. return this._light;
  9470. };
  9471. // Methods
  9472. ShadowGenerator.prototype.getTransformMatrix = function () {
  9473. var scene = this._scene;
  9474. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  9475. return this._transformMatrix;
  9476. }
  9477. this._currentRenderID = scene.getRenderId();
  9478. this._currentFaceIndexCache = this._currentFaceIndex;
  9479. var lightPosition = this._light.position;
  9480. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  9481. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  9482. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  9483. }
  9484. if (this._light.computeTransformedPosition()) {
  9485. lightPosition = this._light.transformedPosition;
  9486. }
  9487. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  9488. this._cachedPosition = lightPosition.clone();
  9489. this._cachedDirection = this._lightDirection.clone();
  9490. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  9491. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  9492. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  9493. }
  9494. return this._transformMatrix;
  9495. };
  9496. ShadowGenerator.prototype.getDarkness = function () {
  9497. return this._darkness;
  9498. };
  9499. ShadowGenerator.prototype.setDarkness = function (darkness) {
  9500. if (darkness >= 1.0)
  9501. this._darkness = 1.0;
  9502. else if (darkness <= 0.0)
  9503. this._darkness = 0.0;
  9504. else
  9505. this._darkness = darkness;
  9506. };
  9507. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  9508. this._transparencyShadow = hasShadow;
  9509. };
  9510. ShadowGenerator.prototype._packHalf = function (depth) {
  9511. var scale = depth * 255.0;
  9512. var fract = scale - Math.floor(scale);
  9513. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  9514. };
  9515. ShadowGenerator.prototype.dispose = function () {
  9516. this._shadowMap.dispose();
  9517. if (this._shadowMap2) {
  9518. this._shadowMap2.dispose();
  9519. }
  9520. if (this._downSamplePostprocess) {
  9521. this._downSamplePostprocess.dispose();
  9522. }
  9523. if (this._boxBlurPostprocess) {
  9524. this._boxBlurPostprocess.dispose();
  9525. }
  9526. };
  9527. ShadowGenerator.prototype.serialize = function () {
  9528. var serializationObject = {};
  9529. serializationObject.lightId = this._light.id;
  9530. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  9531. serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
  9532. serializationObject.usePoissonSampling = this.usePoissonSampling;
  9533. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  9534. serializationObject.renderList = [];
  9535. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  9536. var mesh = this.getShadowMap().renderList[meshIndex];
  9537. serializationObject.renderList.push(mesh.id);
  9538. }
  9539. return serializationObject;
  9540. };
  9541. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  9542. //casting to point light, as light is missing the position attr and typescript complains.
  9543. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  9544. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  9545. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  9546. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  9547. shadowGenerator.getShadowMap().renderList.push(mesh);
  9548. }
  9549. if (parsedShadowGenerator.usePoissonSampling) {
  9550. shadowGenerator.usePoissonSampling = true;
  9551. }
  9552. else if (parsedShadowGenerator.useVarianceShadowMap) {
  9553. shadowGenerator.useVarianceShadowMap = true;
  9554. }
  9555. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  9556. shadowGenerator.useBlurVarianceShadowMap = true;
  9557. if (parsedShadowGenerator.blurScale) {
  9558. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  9559. }
  9560. if (parsedShadowGenerator.blurBoxOffset) {
  9561. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  9562. }
  9563. }
  9564. if (parsedShadowGenerator.bias !== undefined) {
  9565. shadowGenerator.bias = parsedShadowGenerator.bias;
  9566. }
  9567. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  9568. return shadowGenerator;
  9569. };
  9570. ShadowGenerator._FILTER_NONE = 0;
  9571. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  9572. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  9573. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  9574. return ShadowGenerator;
  9575. })();
  9576. BABYLON.ShadowGenerator = ShadowGenerator;
  9577. })(BABYLON || (BABYLON = {}));
  9578. var BABYLON;
  9579. (function (BABYLON) {
  9580. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  9581. if (boxMin.x > sphereCenter.x + sphereRadius)
  9582. return false;
  9583. if (sphereCenter.x - sphereRadius > boxMax.x)
  9584. return false;
  9585. if (boxMin.y > sphereCenter.y + sphereRadius)
  9586. return false;
  9587. if (sphereCenter.y - sphereRadius > boxMax.y)
  9588. return false;
  9589. if (boxMin.z > sphereCenter.z + sphereRadius)
  9590. return false;
  9591. if (sphereCenter.z - sphereRadius > boxMax.z)
  9592. return false;
  9593. return true;
  9594. };
  9595. var getLowestRoot = function (a, b, c, maxR) {
  9596. var determinant = b * b - 4.0 * a * c;
  9597. var result = { root: 0, found: false };
  9598. if (determinant < 0)
  9599. return result;
  9600. var sqrtD = Math.sqrt(determinant);
  9601. var r1 = (-b - sqrtD) / (2.0 * a);
  9602. var r2 = (-b + sqrtD) / (2.0 * a);
  9603. if (r1 > r2) {
  9604. var temp = r2;
  9605. r2 = r1;
  9606. r1 = temp;
  9607. }
  9608. if (r1 > 0 && r1 < maxR) {
  9609. result.root = r1;
  9610. result.found = true;
  9611. return result;
  9612. }
  9613. if (r2 > 0 && r2 < maxR) {
  9614. result.root = r2;
  9615. result.found = true;
  9616. return result;
  9617. }
  9618. return result;
  9619. };
  9620. var Collider = (function () {
  9621. function Collider() {
  9622. this.radius = new BABYLON.Vector3(1, 1, 1);
  9623. this.retry = 0;
  9624. this.basePointWorld = BABYLON.Vector3.Zero();
  9625. this.velocityWorld = BABYLON.Vector3.Zero();
  9626. this.normalizedVelocity = BABYLON.Vector3.Zero();
  9627. this._collisionPoint = BABYLON.Vector3.Zero();
  9628. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  9629. this._tempVector = BABYLON.Vector3.Zero();
  9630. this._tempVector2 = BABYLON.Vector3.Zero();
  9631. this._tempVector3 = BABYLON.Vector3.Zero();
  9632. this._tempVector4 = BABYLON.Vector3.Zero();
  9633. this._edge = BABYLON.Vector3.Zero();
  9634. this._baseToVertex = BABYLON.Vector3.Zero();
  9635. this._destinationPoint = BABYLON.Vector3.Zero();
  9636. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  9637. this._displacementVector = BABYLON.Vector3.Zero();
  9638. }
  9639. // Methods
  9640. Collider.prototype._initialize = function (source, dir, e) {
  9641. this.velocity = dir;
  9642. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  9643. this.basePoint = source;
  9644. source.multiplyToRef(this.radius, this.basePointWorld);
  9645. dir.multiplyToRef(this.radius, this.velocityWorld);
  9646. this.velocityWorldLength = this.velocityWorld.length();
  9647. this.epsilon = e;
  9648. this.collisionFound = false;
  9649. };
  9650. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  9651. pa.subtractToRef(point, this._tempVector);
  9652. pb.subtractToRef(point, this._tempVector2);
  9653. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  9654. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9655. if (d < 0)
  9656. return false;
  9657. pc.subtractToRef(point, this._tempVector3);
  9658. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  9659. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9660. if (d < 0)
  9661. return false;
  9662. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  9663. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9664. return d >= 0;
  9665. };
  9666. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  9667. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  9668. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  9669. if (distance > this.velocityWorldLength + max + sphereRadius) {
  9670. return false;
  9671. }
  9672. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  9673. return false;
  9674. return true;
  9675. };
  9676. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  9677. var t0;
  9678. var embeddedInPlane = false;
  9679. //defensive programming, actually not needed.
  9680. if (!trianglePlaneArray) {
  9681. trianglePlaneArray = [];
  9682. }
  9683. if (!trianglePlaneArray[faceIndex]) {
  9684. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  9685. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  9686. }
  9687. var trianglePlane = trianglePlaneArray[faceIndex];
  9688. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  9689. return;
  9690. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  9691. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  9692. if (normalDotVelocity == 0) {
  9693. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  9694. return;
  9695. embeddedInPlane = true;
  9696. t0 = 0;
  9697. }
  9698. else {
  9699. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9700. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9701. if (t0 > t1) {
  9702. var temp = t1;
  9703. t1 = t0;
  9704. t0 = temp;
  9705. }
  9706. if (t0 > 1.0 || t1 < 0.0)
  9707. return;
  9708. if (t0 < 0)
  9709. t0 = 0;
  9710. if (t0 > 1.0)
  9711. t0 = 1.0;
  9712. }
  9713. this._collisionPoint.copyFromFloats(0, 0, 0);
  9714. var found = false;
  9715. var t = 1.0;
  9716. if (!embeddedInPlane) {
  9717. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  9718. this.velocity.scaleToRef(t0, this._tempVector);
  9719. this._planeIntersectionPoint.addInPlace(this._tempVector);
  9720. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  9721. found = true;
  9722. t = t0;
  9723. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  9724. }
  9725. }
  9726. if (!found) {
  9727. var velocitySquaredLength = this.velocity.lengthSquared();
  9728. var a = velocitySquaredLength;
  9729. this.basePoint.subtractToRef(p1, this._tempVector);
  9730. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9731. var c = this._tempVector.lengthSquared() - 1.0;
  9732. var lowestRoot = getLowestRoot(a, b, c, t);
  9733. if (lowestRoot.found) {
  9734. t = lowestRoot.root;
  9735. found = true;
  9736. this._collisionPoint.copyFrom(p1);
  9737. }
  9738. this.basePoint.subtractToRef(p2, this._tempVector);
  9739. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9740. c = this._tempVector.lengthSquared() - 1.0;
  9741. lowestRoot = getLowestRoot(a, b, c, t);
  9742. if (lowestRoot.found) {
  9743. t = lowestRoot.root;
  9744. found = true;
  9745. this._collisionPoint.copyFrom(p2);
  9746. }
  9747. this.basePoint.subtractToRef(p3, this._tempVector);
  9748. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9749. c = this._tempVector.lengthSquared() - 1.0;
  9750. lowestRoot = getLowestRoot(a, b, c, t);
  9751. if (lowestRoot.found) {
  9752. t = lowestRoot.root;
  9753. found = true;
  9754. this._collisionPoint.copyFrom(p3);
  9755. }
  9756. p2.subtractToRef(p1, this._edge);
  9757. p1.subtractToRef(this.basePoint, this._baseToVertex);
  9758. var edgeSquaredLength = this._edge.lengthSquared();
  9759. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9760. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9761. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9762. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9763. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9764. lowestRoot = getLowestRoot(a, b, c, t);
  9765. if (lowestRoot.found) {
  9766. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9767. if (f >= 0.0 && f <= 1.0) {
  9768. t = lowestRoot.root;
  9769. found = true;
  9770. this._edge.scaleInPlace(f);
  9771. p1.addToRef(this._edge, this._collisionPoint);
  9772. }
  9773. }
  9774. p3.subtractToRef(p2, this._edge);
  9775. p2.subtractToRef(this.basePoint, this._baseToVertex);
  9776. edgeSquaredLength = this._edge.lengthSquared();
  9777. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9778. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9779. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9780. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9781. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9782. lowestRoot = getLowestRoot(a, b, c, t);
  9783. if (lowestRoot.found) {
  9784. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9785. if (f >= 0.0 && f <= 1.0) {
  9786. t = lowestRoot.root;
  9787. found = true;
  9788. this._edge.scaleInPlace(f);
  9789. p2.addToRef(this._edge, this._collisionPoint);
  9790. }
  9791. }
  9792. p1.subtractToRef(p3, this._edge);
  9793. p3.subtractToRef(this.basePoint, this._baseToVertex);
  9794. edgeSquaredLength = this._edge.lengthSquared();
  9795. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9796. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9797. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9798. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9799. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9800. lowestRoot = getLowestRoot(a, b, c, t);
  9801. if (lowestRoot.found) {
  9802. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9803. if (f >= 0.0 && f <= 1.0) {
  9804. t = lowestRoot.root;
  9805. found = true;
  9806. this._edge.scaleInPlace(f);
  9807. p3.addToRef(this._edge, this._collisionPoint);
  9808. }
  9809. }
  9810. }
  9811. if (found) {
  9812. var distToCollision = t * this.velocity.length();
  9813. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  9814. if (!this.intersectionPoint) {
  9815. this.intersectionPoint = this._collisionPoint.clone();
  9816. }
  9817. else {
  9818. this.intersectionPoint.copyFrom(this._collisionPoint);
  9819. }
  9820. this.nearestDistance = distToCollision;
  9821. this.collisionFound = true;
  9822. }
  9823. }
  9824. };
  9825. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  9826. for (var i = indexStart; i < indexEnd; i += 3) {
  9827. var p1 = pts[indices[i] - decal];
  9828. var p2 = pts[indices[i + 1] - decal];
  9829. var p3 = pts[indices[i + 2] - decal];
  9830. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  9831. }
  9832. };
  9833. Collider.prototype._getResponse = function (pos, vel) {
  9834. pos.addToRef(vel, this._destinationPoint);
  9835. vel.scaleInPlace((this.nearestDistance / vel.length()));
  9836. this.basePoint.addToRef(vel, pos);
  9837. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  9838. this._slidePlaneNormal.normalize();
  9839. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  9840. pos.addInPlace(this._displacementVector);
  9841. this.intersectionPoint.addInPlace(this._displacementVector);
  9842. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  9843. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  9844. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  9845. };
  9846. return Collider;
  9847. })();
  9848. BABYLON.Collider = Collider;
  9849. })(BABYLON || (BABYLON = {}));
  9850. var BABYLON;
  9851. (function (BABYLON) {
  9852. //WebWorker code will be inserted to this variable.
  9853. BABYLON.CollisionWorker = "";
  9854. (function (WorkerTaskType) {
  9855. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  9856. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  9857. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  9858. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  9859. var WorkerTaskType = BABYLON.WorkerTaskType;
  9860. (function (WorkerReplyType) {
  9861. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  9862. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  9863. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  9864. var WorkerReplyType = BABYLON.WorkerReplyType;
  9865. var CollisionCoordinatorWorker = (function () {
  9866. function CollisionCoordinatorWorker() {
  9867. var _this = this;
  9868. this._scaledPosition = BABYLON.Vector3.Zero();
  9869. this._scaledVelocity = BABYLON.Vector3.Zero();
  9870. this.onMeshUpdated = function (mesh) {
  9871. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  9872. };
  9873. this.onGeometryUpdated = function (geometry) {
  9874. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  9875. };
  9876. this._afterRender = function () {
  9877. if (!_this._init)
  9878. return;
  9879. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  9880. return;
  9881. }
  9882. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  9883. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  9884. if (_this._runningUpdated > 4) {
  9885. return;
  9886. }
  9887. ++_this._runningUpdated;
  9888. var payload = {
  9889. updatedMeshes: _this._addUpdateMeshesList,
  9890. updatedGeometries: _this._addUpdateGeometriesList,
  9891. removedGeometries: _this._toRemoveGeometryArray,
  9892. removedMeshes: _this._toRemoveMeshesArray
  9893. };
  9894. var message = {
  9895. payload: payload,
  9896. taskType: WorkerTaskType.UPDATE
  9897. };
  9898. var serializable = [];
  9899. for (var id in payload.updatedGeometries) {
  9900. if (payload.updatedGeometries.hasOwnProperty(id)) {
  9901. //prepare transferables
  9902. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  9903. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  9904. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  9905. }
  9906. }
  9907. _this._worker.postMessage(message, serializable);
  9908. _this._addUpdateMeshesList = {};
  9909. _this._addUpdateGeometriesList = {};
  9910. _this._toRemoveGeometryArray = [];
  9911. _this._toRemoveMeshesArray = [];
  9912. };
  9913. this._onMessageFromWorker = function (e) {
  9914. var returnData = e.data;
  9915. if (returnData.error != WorkerReplyType.SUCCESS) {
  9916. //TODO what errors can be returned from the worker?
  9917. BABYLON.Tools.Warn("error returned from worker!");
  9918. return;
  9919. }
  9920. switch (returnData.taskType) {
  9921. case WorkerTaskType.INIT:
  9922. _this._init = true;
  9923. //Update the worked with ALL of the scene's current state
  9924. _this._scene.meshes.forEach(function (mesh) {
  9925. _this.onMeshAdded(mesh);
  9926. });
  9927. _this._scene.getGeometries().forEach(function (geometry) {
  9928. _this.onGeometryAdded(geometry);
  9929. });
  9930. break;
  9931. case WorkerTaskType.UPDATE:
  9932. _this._runningUpdated--;
  9933. break;
  9934. case WorkerTaskType.COLLIDE:
  9935. _this._runningCollisionTask = false;
  9936. var returnPayload = returnData.payload;
  9937. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  9938. return;
  9939. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  9940. //cleanup
  9941. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  9942. break;
  9943. }
  9944. };
  9945. this._collisionsCallbackArray = [];
  9946. this._init = false;
  9947. this._runningUpdated = 0;
  9948. this._runningCollisionTask = false;
  9949. this._addUpdateMeshesList = {};
  9950. this._addUpdateGeometriesList = {};
  9951. this._toRemoveGeometryArray = [];
  9952. this._toRemoveMeshesArray = [];
  9953. }
  9954. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9955. if (!this._init)
  9956. return;
  9957. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  9958. return;
  9959. position.divideToRef(collider.radius, this._scaledPosition);
  9960. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9961. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  9962. var payload = {
  9963. collider: {
  9964. position: this._scaledPosition.asArray(),
  9965. velocity: this._scaledVelocity.asArray(),
  9966. radius: collider.radius.asArray()
  9967. },
  9968. collisionId: collisionIndex,
  9969. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  9970. maximumRetry: maximumRetry
  9971. };
  9972. var message = {
  9973. payload: payload,
  9974. taskType: WorkerTaskType.COLLIDE
  9975. };
  9976. this._worker.postMessage(message);
  9977. };
  9978. CollisionCoordinatorWorker.prototype.init = function (scene) {
  9979. this._scene = scene;
  9980. this._scene.registerAfterRender(this._afterRender);
  9981. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  9982. this._worker = new Worker(workerUrl);
  9983. this._worker.onmessage = this._onMessageFromWorker;
  9984. var message = {
  9985. payload: {},
  9986. taskType: WorkerTaskType.INIT
  9987. };
  9988. this._worker.postMessage(message);
  9989. };
  9990. CollisionCoordinatorWorker.prototype.destroy = function () {
  9991. this._scene.unregisterAfterRender(this._afterRender);
  9992. this._worker.terminate();
  9993. };
  9994. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  9995. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  9996. this.onMeshUpdated(mesh);
  9997. };
  9998. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  9999. this._toRemoveMeshesArray.push(mesh.uniqueId);
  10000. };
  10001. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  10002. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  10003. geometry.onGeometryUpdated = this.onGeometryUpdated;
  10004. this.onGeometryUpdated(geometry);
  10005. };
  10006. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  10007. this._toRemoveGeometryArray.push(geometry.id);
  10008. };
  10009. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  10010. var submeshes = [];
  10011. if (mesh.subMeshes) {
  10012. submeshes = mesh.subMeshes.map(function (sm, idx) {
  10013. return {
  10014. position: idx,
  10015. verticesStart: sm.verticesStart,
  10016. verticesCount: sm.verticesCount,
  10017. indexStart: sm.indexStart,
  10018. indexCount: sm.indexCount,
  10019. hasMaterial: !!sm.getMaterial(),
  10020. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  10021. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  10022. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  10023. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  10024. };
  10025. });
  10026. }
  10027. var geometryId = null;
  10028. if (mesh instanceof BABYLON.Mesh) {
  10029. geometryId = mesh.geometry ? mesh.geometry.id : null;
  10030. }
  10031. else if (mesh instanceof BABYLON.InstancedMesh) {
  10032. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  10033. }
  10034. return {
  10035. uniqueId: mesh.uniqueId,
  10036. id: mesh.id,
  10037. name: mesh.name,
  10038. geometryId: geometryId,
  10039. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  10040. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  10041. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  10042. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  10043. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  10044. subMeshes: submeshes,
  10045. checkCollisions: mesh.checkCollisions
  10046. };
  10047. };
  10048. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  10049. return {
  10050. id: geometry.id,
  10051. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  10052. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  10053. indices: new Int32Array(geometry.getIndices() || []),
  10054. };
  10055. };
  10056. return CollisionCoordinatorWorker;
  10057. })();
  10058. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  10059. var CollisionCoordinatorLegacy = (function () {
  10060. function CollisionCoordinatorLegacy() {
  10061. this._scaledPosition = BABYLON.Vector3.Zero();
  10062. this._scaledVelocity = BABYLON.Vector3.Zero();
  10063. this._finalPosition = BABYLON.Vector3.Zero();
  10064. }
  10065. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  10066. position.divideToRef(collider.radius, this._scaledPosition);
  10067. velocity.divideToRef(collider.radius, this._scaledVelocity);
  10068. collider.collidedMesh = null;
  10069. collider.retry = 0;
  10070. collider.initialVelocity = this._scaledVelocity;
  10071. collider.initialPosition = this._scaledPosition;
  10072. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  10073. this._finalPosition.multiplyInPlace(collider.radius);
  10074. //run the callback
  10075. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  10076. };
  10077. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  10078. this._scene = scene;
  10079. };
  10080. CollisionCoordinatorLegacy.prototype.destroy = function () {
  10081. //Legacy need no destruction method.
  10082. };
  10083. //No update in legacy mode
  10084. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  10085. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  10086. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  10087. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  10088. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  10089. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  10090. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  10091. if (excludedMesh === void 0) { excludedMesh = null; }
  10092. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  10093. if (collider.retry >= maximumRetry) {
  10094. finalPosition.copyFrom(position);
  10095. return;
  10096. }
  10097. collider._initialize(position, velocity, closeDistance);
  10098. // Check all meshes
  10099. for (var index = 0; index < this._scene.meshes.length; index++) {
  10100. var mesh = this._scene.meshes[index];
  10101. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  10102. mesh._checkCollision(collider);
  10103. }
  10104. }
  10105. if (!collider.collisionFound) {
  10106. position.addToRef(velocity, finalPosition);
  10107. return;
  10108. }
  10109. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  10110. collider._getResponse(position, velocity);
  10111. }
  10112. if (velocity.length() <= closeDistance) {
  10113. finalPosition.copyFrom(position);
  10114. return;
  10115. }
  10116. collider.retry++;
  10117. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  10118. };
  10119. return CollisionCoordinatorLegacy;
  10120. })();
  10121. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  10122. })(BABYLON || (BABYLON = {}));
  10123. var BABYLON;
  10124. (function (BABYLON) {
  10125. var VRCameraMetrics = (function () {
  10126. function VRCameraMetrics() {
  10127. this.compensateDistortion = true;
  10128. }
  10129. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  10130. get: function () {
  10131. return this.hResolution / (2 * this.vResolution);
  10132. },
  10133. enumerable: true,
  10134. configurable: true
  10135. });
  10136. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  10137. get: function () {
  10138. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  10139. },
  10140. enumerable: true,
  10141. configurable: true
  10142. });
  10143. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  10144. get: function () {
  10145. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  10146. var h = (4 * meters) / this.hScreenSize;
  10147. return BABYLON.Matrix.Translation(h, 0, 0);
  10148. },
  10149. enumerable: true,
  10150. configurable: true
  10151. });
  10152. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  10153. get: function () {
  10154. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  10155. var h = (4 * meters) / this.hScreenSize;
  10156. return BABYLON.Matrix.Translation(-h, 0, 0);
  10157. },
  10158. enumerable: true,
  10159. configurable: true
  10160. });
  10161. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  10162. get: function () {
  10163. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  10164. },
  10165. enumerable: true,
  10166. configurable: true
  10167. });
  10168. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  10169. get: function () {
  10170. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  10171. },
  10172. enumerable: true,
  10173. configurable: true
  10174. });
  10175. VRCameraMetrics.GetDefault = function () {
  10176. var result = new VRCameraMetrics();
  10177. result.hResolution = 1280;
  10178. result.vResolution = 800;
  10179. result.hScreenSize = 0.149759993;
  10180. result.vScreenSize = 0.0935999975;
  10181. result.vScreenCenter = 0.0467999987,
  10182. result.eyeToScreenDistance = 0.0410000011;
  10183. result.lensSeparationDistance = 0.0635000020;
  10184. result.interpupillaryDistance = 0.0640000030;
  10185. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  10186. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  10187. result.postProcessScaleFactor = 1.714605507808412;
  10188. result.lensCenterOffset = 0.151976421;
  10189. return result;
  10190. };
  10191. return VRCameraMetrics;
  10192. })();
  10193. BABYLON.VRCameraMetrics = VRCameraMetrics;
  10194. var Camera = (function (_super) {
  10195. __extends(Camera, _super);
  10196. function Camera(name, position, scene) {
  10197. _super.call(this, name, scene);
  10198. this.position = position;
  10199. // Members
  10200. this.upVector = BABYLON.Vector3.Up();
  10201. this.orthoLeft = null;
  10202. this.orthoRight = null;
  10203. this.orthoBottom = null;
  10204. this.orthoTop = null;
  10205. this.fov = 0.8;
  10206. this.minZ = 1.0;
  10207. this.maxZ = 10000.0;
  10208. this.inertia = 0.9;
  10209. this.mode = Camera.PERSPECTIVE_CAMERA;
  10210. this.isIntermediate = false;
  10211. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  10212. this.layerMask = 0x0FFFFFFF;
  10213. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  10214. // Camera rig members
  10215. this.cameraRigMode = Camera.RIG_MODE_NONE;
  10216. this._rigCameras = new Array();
  10217. // Cache
  10218. this._computedViewMatrix = BABYLON.Matrix.Identity();
  10219. this._projectionMatrix = new BABYLON.Matrix();
  10220. this._postProcesses = new Array();
  10221. this._postProcessesTakenIndices = [];
  10222. this._activeMeshes = new BABYLON.SmartArray(256);
  10223. this._globalPosition = BABYLON.Vector3.Zero();
  10224. scene.addCamera(this);
  10225. if (!scene.activeCamera) {
  10226. scene.activeCamera = this;
  10227. }
  10228. }
  10229. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  10230. get: function () {
  10231. return Camera._PERSPECTIVE_CAMERA;
  10232. },
  10233. enumerable: true,
  10234. configurable: true
  10235. });
  10236. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  10237. get: function () {
  10238. return Camera._ORTHOGRAPHIC_CAMERA;
  10239. },
  10240. enumerable: true,
  10241. configurable: true
  10242. });
  10243. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  10244. get: function () {
  10245. return Camera._FOVMODE_VERTICAL_FIXED;
  10246. },
  10247. enumerable: true,
  10248. configurable: true
  10249. });
  10250. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  10251. get: function () {
  10252. return Camera._FOVMODE_HORIZONTAL_FIXED;
  10253. },
  10254. enumerable: true,
  10255. configurable: true
  10256. });
  10257. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  10258. get: function () {
  10259. return Camera._RIG_MODE_NONE;
  10260. },
  10261. enumerable: true,
  10262. configurable: true
  10263. });
  10264. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  10265. get: function () {
  10266. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  10267. },
  10268. enumerable: true,
  10269. configurable: true
  10270. });
  10271. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  10272. get: function () {
  10273. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  10274. },
  10275. enumerable: true,
  10276. configurable: true
  10277. });
  10278. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  10279. get: function () {
  10280. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  10281. },
  10282. enumerable: true,
  10283. configurable: true
  10284. });
  10285. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  10286. get: function () {
  10287. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  10288. },
  10289. enumerable: true,
  10290. configurable: true
  10291. });
  10292. Object.defineProperty(Camera, "RIG_MODE_VR", {
  10293. get: function () {
  10294. return Camera._RIG_MODE_VR;
  10295. },
  10296. enumerable: true,
  10297. configurable: true
  10298. });
  10299. Object.defineProperty(Camera.prototype, "globalPosition", {
  10300. get: function () {
  10301. return this._globalPosition;
  10302. },
  10303. enumerable: true,
  10304. configurable: true
  10305. });
  10306. Camera.prototype.getActiveMeshes = function () {
  10307. return this._activeMeshes;
  10308. };
  10309. Camera.prototype.isActiveMesh = function (mesh) {
  10310. return (this._activeMeshes.indexOf(mesh) !== -1);
  10311. };
  10312. //Cache
  10313. Camera.prototype._initCache = function () {
  10314. _super.prototype._initCache.call(this);
  10315. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10316. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10317. this._cache.mode = undefined;
  10318. this._cache.minZ = undefined;
  10319. this._cache.maxZ = undefined;
  10320. this._cache.fov = undefined;
  10321. this._cache.aspectRatio = undefined;
  10322. this._cache.orthoLeft = undefined;
  10323. this._cache.orthoRight = undefined;
  10324. this._cache.orthoBottom = undefined;
  10325. this._cache.orthoTop = undefined;
  10326. this._cache.renderWidth = undefined;
  10327. this._cache.renderHeight = undefined;
  10328. };
  10329. Camera.prototype._updateCache = function (ignoreParentClass) {
  10330. if (!ignoreParentClass) {
  10331. _super.prototype._updateCache.call(this);
  10332. }
  10333. var engine = this.getEngine();
  10334. this._cache.position.copyFrom(this.position);
  10335. this._cache.upVector.copyFrom(this.upVector);
  10336. this._cache.mode = this.mode;
  10337. this._cache.minZ = this.minZ;
  10338. this._cache.maxZ = this.maxZ;
  10339. this._cache.fov = this.fov;
  10340. this._cache.aspectRatio = engine.getAspectRatio(this);
  10341. this._cache.orthoLeft = this.orthoLeft;
  10342. this._cache.orthoRight = this.orthoRight;
  10343. this._cache.orthoBottom = this.orthoBottom;
  10344. this._cache.orthoTop = this.orthoTop;
  10345. this._cache.renderWidth = engine.getRenderWidth();
  10346. this._cache.renderHeight = engine.getRenderHeight();
  10347. };
  10348. Camera.prototype._updateFromScene = function () {
  10349. this.updateCache();
  10350. this._update();
  10351. };
  10352. // Synchronized
  10353. Camera.prototype._isSynchronized = function () {
  10354. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  10355. };
  10356. Camera.prototype._isSynchronizedViewMatrix = function () {
  10357. if (!_super.prototype._isSynchronized.call(this))
  10358. return false;
  10359. return this._cache.position.equals(this.position)
  10360. && this._cache.upVector.equals(this.upVector)
  10361. && this.isSynchronizedWithParent();
  10362. };
  10363. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  10364. var check = this._cache.mode === this.mode
  10365. && this._cache.minZ === this.minZ
  10366. && this._cache.maxZ === this.maxZ;
  10367. if (!check) {
  10368. return false;
  10369. }
  10370. var engine = this.getEngine();
  10371. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  10372. check = this._cache.fov === this.fov
  10373. && this._cache.aspectRatio === engine.getAspectRatio(this);
  10374. }
  10375. else {
  10376. check = this._cache.orthoLeft === this.orthoLeft
  10377. && this._cache.orthoRight === this.orthoRight
  10378. && this._cache.orthoBottom === this.orthoBottom
  10379. && this._cache.orthoTop === this.orthoTop
  10380. && this._cache.renderWidth === engine.getRenderWidth()
  10381. && this._cache.renderHeight === engine.getRenderHeight();
  10382. }
  10383. return check;
  10384. };
  10385. // Controls
  10386. Camera.prototype.attachControl = function (element) {
  10387. };
  10388. Camera.prototype.detachControl = function (element) {
  10389. };
  10390. Camera.prototype._update = function () {
  10391. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  10392. this._updateRigCameras();
  10393. }
  10394. this._checkInputs();
  10395. };
  10396. Camera.prototype._checkInputs = function () {
  10397. };
  10398. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  10399. if (insertAt === void 0) { insertAt = null; }
  10400. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  10401. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  10402. return 0;
  10403. }
  10404. if (insertAt == null || insertAt < 0) {
  10405. this._postProcesses.push(postProcess);
  10406. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  10407. return this._postProcesses.length - 1;
  10408. }
  10409. var add = 0;
  10410. var i;
  10411. var start;
  10412. if (this._postProcesses[insertAt]) {
  10413. start = this._postProcesses.length - 1;
  10414. for (i = start; i >= insertAt + 1; --i) {
  10415. this._postProcesses[i + 1] = this._postProcesses[i];
  10416. }
  10417. add = 1;
  10418. }
  10419. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  10420. if (this._postProcessesTakenIndices[i] < insertAt) {
  10421. continue;
  10422. }
  10423. start = this._postProcessesTakenIndices.length - 1;
  10424. for (var j = start; j >= i; --j) {
  10425. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  10426. }
  10427. this._postProcessesTakenIndices[i] = insertAt;
  10428. break;
  10429. }
  10430. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) === -1) {
  10431. this._postProcessesTakenIndices.push(insertAt);
  10432. }
  10433. var result = insertAt + add;
  10434. this._postProcesses[result] = postProcess;
  10435. return result;
  10436. };
  10437. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  10438. if (atIndices === void 0) { atIndices = null; }
  10439. var result = [];
  10440. var i;
  10441. var index;
  10442. if (!atIndices) {
  10443. var length = this._postProcesses.length;
  10444. for (i = 0; i < length; i++) {
  10445. if (this._postProcesses[i] !== postProcess) {
  10446. continue;
  10447. }
  10448. delete this._postProcesses[i];
  10449. index = this._postProcessesTakenIndices.indexOf(i);
  10450. this._postProcessesTakenIndices.splice(index, 1);
  10451. }
  10452. }
  10453. else {
  10454. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  10455. for (i = 0; i < atIndices.length; i++) {
  10456. var foundPostProcess = this._postProcesses[atIndices[i]];
  10457. if (foundPostProcess !== postProcess) {
  10458. result.push(i);
  10459. continue;
  10460. }
  10461. delete this._postProcesses[atIndices[i]];
  10462. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  10463. this._postProcessesTakenIndices.splice(index, 1);
  10464. }
  10465. }
  10466. return result;
  10467. };
  10468. Camera.prototype.getWorldMatrix = function () {
  10469. if (!this._worldMatrix) {
  10470. this._worldMatrix = BABYLON.Matrix.Identity();
  10471. }
  10472. var viewMatrix = this.getViewMatrix();
  10473. viewMatrix.invertToRef(this._worldMatrix);
  10474. return this._worldMatrix;
  10475. };
  10476. Camera.prototype._getViewMatrix = function () {
  10477. return BABYLON.Matrix.Identity();
  10478. };
  10479. Camera.prototype.getViewMatrix = function (force) {
  10480. this._computedViewMatrix = this._computeViewMatrix(force);
  10481. if (!force && this._isSynchronizedViewMatrix()) {
  10482. return this._computedViewMatrix;
  10483. }
  10484. if (!this.parent || !this.parent.getWorldMatrix) {
  10485. this._globalPosition.copyFrom(this.position);
  10486. }
  10487. else {
  10488. if (!this._worldMatrix) {
  10489. this._worldMatrix = BABYLON.Matrix.Identity();
  10490. }
  10491. this._computedViewMatrix.invertToRef(this._worldMatrix);
  10492. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  10493. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  10494. this._computedViewMatrix.invert();
  10495. this._markSyncedWithParent();
  10496. }
  10497. this._currentRenderId = this.getScene().getRenderId();
  10498. return this._computedViewMatrix;
  10499. };
  10500. Camera.prototype._computeViewMatrix = function (force) {
  10501. if (!force && this._isSynchronizedViewMatrix()) {
  10502. return this._computedViewMatrix;
  10503. }
  10504. this._computedViewMatrix = this._getViewMatrix();
  10505. this._currentRenderId = this.getScene().getRenderId();
  10506. return this._computedViewMatrix;
  10507. };
  10508. Camera.prototype.getProjectionMatrix = function (force) {
  10509. if (!force && this._isSynchronizedProjectionMatrix()) {
  10510. return this._projectionMatrix;
  10511. }
  10512. var engine = this.getEngine();
  10513. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  10514. if (this.minZ <= 0) {
  10515. this.minZ = 0.1;
  10516. }
  10517. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
  10518. return this._projectionMatrix;
  10519. }
  10520. var halfWidth = engine.getRenderWidth() / 2.0;
  10521. var halfHeight = engine.getRenderHeight() / 2.0;
  10522. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  10523. return this._projectionMatrix;
  10524. };
  10525. Camera.prototype.dispose = function () {
  10526. // Animations
  10527. this.getScene().stopAnimation(this);
  10528. // Remove from scene
  10529. this.getScene().removeCamera(this);
  10530. while (this._rigCameras.length > 0) {
  10531. this._rigCameras.pop().dispose();
  10532. }
  10533. // Postprocesses
  10534. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  10535. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  10536. }
  10537. };
  10538. // ---- Camera rigs section ----
  10539. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  10540. while (this._rigCameras.length > 0) {
  10541. this._rigCameras.pop().dispose();
  10542. }
  10543. this.cameraRigMode = mode;
  10544. this._cameraRigParams = {};
  10545. switch (this.cameraRigMode) {
  10546. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10547. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10548. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10549. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10550. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  10551. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  10552. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  10553. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  10554. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10555. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10556. break;
  10557. }
  10558. var postProcesses = new Array();
  10559. switch (this.cameraRigMode) {
  10560. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10561. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]));
  10562. this._rigCameras[0].isIntermediate = true;
  10563. postProcesses.push(new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras[1]));
  10564. postProcesses[1].onApply = function (effect) {
  10565. effect.setTextureFromPostProcess("leftSampler", postProcesses[0]);
  10566. };
  10567. break;
  10568. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10569. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10570. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10571. var isStereoscopicHoriz = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED);
  10572. var firstCamIndex = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : 0;
  10573. var secondCamIndex = 1 - firstCamIndex;
  10574. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[firstCamIndex]));
  10575. this._rigCameras[firstCamIndex].isIntermediate = true;
  10576. postProcesses.push(new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras[secondCamIndex], postProcesses[0], isStereoscopicHoriz));
  10577. break;
  10578. case Camera.RIG_MODE_VR:
  10579. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10580. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10581. var metrics = rigParams.vrCameraMetrics || VRCameraMetrics.GetDefault();
  10582. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  10583. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  10584. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10585. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  10586. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  10587. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  10588. if (metrics.compensateDistortion) {
  10589. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics));
  10590. }
  10591. this._rigCameras[1]._cameraRigParams.vrMetrics = this._rigCameras[0]._cameraRigParams.vrMetrics;
  10592. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  10593. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10594. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  10595. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  10596. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  10597. if (metrics.compensateDistortion) {
  10598. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics));
  10599. }
  10600. break;
  10601. }
  10602. this._update();
  10603. };
  10604. Camera.prototype._getVRProjectionMatrix = function () {
  10605. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  10606. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  10607. return this._projectionMatrix;
  10608. };
  10609. Camera.prototype.setCameraRigParameter = function (name, value) {
  10610. this._cameraRigParams[name] = value;
  10611. //provisionnally:
  10612. if (name === "interaxialDistance") {
  10613. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  10614. }
  10615. };
  10616. /**
  10617. * May needs to be overridden by children so sub has required properties to be copied
  10618. */
  10619. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  10620. return null;
  10621. };
  10622. /**
  10623. * May needs to be overridden by children
  10624. */
  10625. Camera.prototype._updateRigCameras = function () {
  10626. for (var i = 0; i < this._rigCameras.length; i++) {
  10627. this._rigCameras[i].minZ = this.minZ;
  10628. this._rigCameras[i].maxZ = this.maxZ;
  10629. this._rigCameras[i].fov = this.fov;
  10630. }
  10631. // only update viewport when ANAGLYPH
  10632. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  10633. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  10634. }
  10635. };
  10636. Camera.prototype.serialize = function () {
  10637. var serializationObject = {};
  10638. serializationObject.name = this.name;
  10639. serializationObject.tags = BABYLON.Tags.GetTags(this);
  10640. serializationObject.id = this.id;
  10641. serializationObject.position = this.position.asArray();
  10642. serializationObject.type = BABYLON.Tools.GetConstructorName(this);
  10643. // Parent
  10644. if (this.parent) {
  10645. serializationObject.parentId = this.parent.id;
  10646. }
  10647. serializationObject.fov = this.fov;
  10648. serializationObject.minZ = this.minZ;
  10649. serializationObject.maxZ = this.maxZ;
  10650. serializationObject.inertia = this.inertia;
  10651. // Animations
  10652. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  10653. serializationObject.ranges = this.serializeAnimationRanges();
  10654. // Layer mask
  10655. serializationObject.layerMask = this.layerMask;
  10656. return serializationObject;
  10657. };
  10658. Camera.Parse = function (parsedCamera, scene) {
  10659. var camera;
  10660. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  10661. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  10662. var interaxial_distance;
  10663. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  10664. var alpha = parsedCamera.alpha;
  10665. var beta = parsedCamera.beta;
  10666. var radius = parsedCamera.radius;
  10667. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  10668. interaxial_distance = parsedCamera.interaxial_distance;
  10669. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, interaxial_distance, scene);
  10670. }
  10671. else {
  10672. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  10673. }
  10674. }
  10675. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  10676. interaxial_distance = parsedCamera.interaxial_distance;
  10677. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, interaxial_distance, scene);
  10678. }
  10679. else if (parsedCamera.type === "DeviceOrientationCamera") {
  10680. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  10681. }
  10682. else if (parsedCamera.type === "FollowCamera") {
  10683. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  10684. camera.heightOffset = parsedCamera.heightOffset;
  10685. camera.radius = parsedCamera.radius;
  10686. camera.rotationOffset = parsedCamera.rotationOffset;
  10687. if (lockedTargetMesh)
  10688. camera.target = lockedTargetMesh;
  10689. }
  10690. else if (parsedCamera.type === "GamepadCamera") {
  10691. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  10692. }
  10693. else if (parsedCamera.type === "TouchCamera") {
  10694. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  10695. }
  10696. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  10697. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  10698. }
  10699. else if (parsedCamera.type === "WebVRFreeCamera") {
  10700. camera = new BABYLON.WebVRFreeCamera(parsedCamera.name, position, scene);
  10701. }
  10702. else if (parsedCamera.type === "VRDeviceOrientationFreeCamera") {
  10703. camera = new BABYLON.VRDeviceOrientationFreeCamera(parsedCamera.name, position, scene);
  10704. }
  10705. else if (parsedCamera.type === "FreeCamera") {
  10706. camera = new BABYLON.UniversalCamera(parsedCamera.name, position, scene); // Forcing Universal here
  10707. }
  10708. else {
  10709. // Universal Camera is the default value
  10710. camera = new BABYLON.UniversalCamera(parsedCamera.name, position, scene);
  10711. }
  10712. // apply 3d rig, when found
  10713. if (parsedCamera.cameraRigMode) {
  10714. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  10715. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  10716. }
  10717. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  10718. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  10719. camera.lockedTarget = lockedTargetMesh;
  10720. }
  10721. camera.id = parsedCamera.id;
  10722. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  10723. // Parent
  10724. if (parsedCamera.parentId) {
  10725. camera._waitingParentId = parsedCamera.parentId;
  10726. }
  10727. // Target
  10728. if (parsedCamera.target) {
  10729. if (camera.setTarget) {
  10730. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  10731. }
  10732. else {
  10733. //For ArcRotate
  10734. camera.target = BABYLON.Vector3.FromArray(parsedCamera.target);
  10735. }
  10736. }
  10737. else {
  10738. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  10739. }
  10740. camera.fov = parsedCamera.fov;
  10741. camera.minZ = parsedCamera.minZ;
  10742. camera.maxZ = parsedCamera.maxZ;
  10743. camera.speed = parsedCamera.speed;
  10744. camera.inertia = parsedCamera.inertia;
  10745. camera.checkCollisions = parsedCamera.checkCollisions;
  10746. camera.applyGravity = parsedCamera.applyGravity;
  10747. if (parsedCamera.ellipsoid) {
  10748. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  10749. }
  10750. // Animations
  10751. if (parsedCamera.animations) {
  10752. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  10753. var parsedAnimation = parsedCamera.animations[animationIndex];
  10754. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  10755. }
  10756. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  10757. }
  10758. if (parsedCamera.autoAnimate) {
  10759. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  10760. }
  10761. // Layer Mask
  10762. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  10763. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  10764. }
  10765. else {
  10766. camera.layerMask = 0x0FFFFFFF;
  10767. }
  10768. return camera;
  10769. };
  10770. // Statics
  10771. Camera._PERSPECTIVE_CAMERA = 0;
  10772. Camera._ORTHOGRAPHIC_CAMERA = 1;
  10773. Camera._FOVMODE_VERTICAL_FIXED = 0;
  10774. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  10775. Camera._RIG_MODE_NONE = 0;
  10776. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  10777. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  10778. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  10779. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  10780. Camera._RIG_MODE_VR = 20;
  10781. return Camera;
  10782. })(BABYLON.Node);
  10783. BABYLON.Camera = Camera;
  10784. })(BABYLON || (BABYLON = {}));
  10785. var BABYLON;
  10786. (function (BABYLON) {
  10787. var TargetCamera = (function (_super) {
  10788. __extends(TargetCamera, _super);
  10789. function TargetCamera(name, position, scene) {
  10790. _super.call(this, name, position, scene);
  10791. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10792. this.cameraRotation = new BABYLON.Vector2(0, 0);
  10793. this.rotation = new BABYLON.Vector3(0, 0, 0);
  10794. this.speed = 2.0;
  10795. this.noRotationConstraint = false;
  10796. this.lockedTarget = null;
  10797. this._currentTarget = BABYLON.Vector3.Zero();
  10798. this._viewMatrix = BABYLON.Matrix.Zero();
  10799. this._camMatrix = BABYLON.Matrix.Zero();
  10800. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  10801. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  10802. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  10803. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  10804. this._lookAtTemp = BABYLON.Matrix.Zero();
  10805. this._tempMatrix = BABYLON.Matrix.Zero();
  10806. }
  10807. TargetCamera.prototype.getFrontPosition = function (distance) {
  10808. var direction = this.getTarget().subtract(this.position);
  10809. direction.normalize();
  10810. direction.scaleInPlace(distance);
  10811. return this.globalPosition.add(direction);
  10812. };
  10813. TargetCamera.prototype._getLockedTargetPosition = function () {
  10814. if (!this.lockedTarget) {
  10815. return null;
  10816. }
  10817. return this.lockedTarget.position || this.lockedTarget;
  10818. };
  10819. // Cache
  10820. TargetCamera.prototype._initCache = function () {
  10821. _super.prototype._initCache.call(this);
  10822. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10823. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10824. };
  10825. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  10826. if (!ignoreParentClass) {
  10827. _super.prototype._updateCache.call(this);
  10828. }
  10829. var lockedTargetPosition = this._getLockedTargetPosition();
  10830. if (!lockedTargetPosition) {
  10831. this._cache.lockedTarget = null;
  10832. }
  10833. else {
  10834. if (!this._cache.lockedTarget) {
  10835. this._cache.lockedTarget = lockedTargetPosition.clone();
  10836. }
  10837. else {
  10838. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  10839. }
  10840. }
  10841. this._cache.rotation.copyFrom(this.rotation);
  10842. };
  10843. // Synchronized
  10844. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  10845. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  10846. return false;
  10847. }
  10848. var lockedTargetPosition = this._getLockedTargetPosition();
  10849. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  10850. && this._cache.rotation.equals(this.rotation);
  10851. };
  10852. // Methods
  10853. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  10854. var engine = this.getEngine();
  10855. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  10856. };
  10857. // Target
  10858. TargetCamera.prototype.setTarget = function (target) {
  10859. this.upVector.normalize();
  10860. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  10861. this._camMatrix.invert();
  10862. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  10863. var vDir = target.subtract(this.position);
  10864. if (vDir.x >= 0.0) {
  10865. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  10866. }
  10867. else {
  10868. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  10869. }
  10870. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  10871. if (isNaN(this.rotation.x)) {
  10872. this.rotation.x = 0;
  10873. }
  10874. if (isNaN(this.rotation.y)) {
  10875. this.rotation.y = 0;
  10876. }
  10877. if (isNaN(this.rotation.z)) {
  10878. this.rotation.z = 0;
  10879. }
  10880. };
  10881. TargetCamera.prototype.getTarget = function () {
  10882. return this._currentTarget;
  10883. };
  10884. TargetCamera.prototype._decideIfNeedsToMove = function () {
  10885. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10886. };
  10887. TargetCamera.prototype._updatePosition = function () {
  10888. this.position.addInPlace(this.cameraDirection);
  10889. };
  10890. TargetCamera.prototype._checkInputs = function () {
  10891. var needToMove = this._decideIfNeedsToMove();
  10892. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  10893. // Move
  10894. if (needToMove) {
  10895. this._updatePosition();
  10896. }
  10897. // Rotate
  10898. if (needToRotate) {
  10899. this.rotation.x += this.cameraRotation.x;
  10900. this.rotation.y += this.cameraRotation.y;
  10901. if (!this.noRotationConstraint) {
  10902. var limit = (Math.PI / 2) * 0.95;
  10903. if (this.rotation.x > limit)
  10904. this.rotation.x = limit;
  10905. if (this.rotation.x < -limit)
  10906. this.rotation.x = -limit;
  10907. }
  10908. }
  10909. // Inertia
  10910. if (needToMove) {
  10911. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  10912. this.cameraDirection.x = 0;
  10913. }
  10914. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  10915. this.cameraDirection.y = 0;
  10916. }
  10917. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  10918. this.cameraDirection.z = 0;
  10919. }
  10920. this.cameraDirection.scaleInPlace(this.inertia);
  10921. }
  10922. if (needToRotate) {
  10923. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  10924. this.cameraRotation.x = 0;
  10925. }
  10926. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  10927. this.cameraRotation.y = 0;
  10928. }
  10929. this.cameraRotation.scaleInPlace(this.inertia);
  10930. }
  10931. _super.prototype._checkInputs.call(this);
  10932. };
  10933. TargetCamera.prototype._getViewMatrix = function () {
  10934. if (!this.lockedTarget) {
  10935. // Compute
  10936. if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
  10937. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  10938. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10939. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  10940. this._lookAtTemp.invert();
  10941. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  10942. }
  10943. else {
  10944. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10945. }
  10946. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10947. // Computing target and final matrix
  10948. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10949. }
  10950. else {
  10951. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  10952. }
  10953. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  10954. return this._viewMatrix;
  10955. };
  10956. TargetCamera.prototype._getVRViewMatrix = function () {
  10957. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10958. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10959. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._cameraRigParams.vrActualUp);
  10960. // Computing target and final matrix
  10961. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10962. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._cameraRigParams.vrActualUp, this._cameraRigParams.vrWorkMatrix);
  10963. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._viewMatrix);
  10964. return this._viewMatrix;
  10965. };
  10966. /**
  10967. * @override
  10968. * Override Camera.createRigCamera
  10969. */
  10970. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  10971. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  10972. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  10973. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  10974. rigCamera._cameraRigParams = {};
  10975. rigCamera._cameraRigParams.vrActualUp = new BABYLON.Vector3(0, 0, 0);
  10976. rigCamera._getViewMatrix = rigCamera._getVRViewMatrix;
  10977. }
  10978. return rigCamera;
  10979. }
  10980. return null;
  10981. };
  10982. /**
  10983. * @override
  10984. * Override Camera._updateRigCameras
  10985. */
  10986. TargetCamera.prototype._updateRigCameras = function () {
  10987. switch (this.cameraRigMode) {
  10988. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10989. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10990. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10991. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10992. case BABYLON.Camera.RIG_MODE_VR:
  10993. var camLeft = this._rigCameras[0];
  10994. var camRight = this._rigCameras[1];
  10995. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  10996. camLeft.rotation.x = camRight.rotation.x = this.rotation.x;
  10997. camLeft.rotation.y = camRight.rotation.y = this.rotation.y;
  10998. camLeft.rotation.z = camRight.rotation.z = this.rotation.z;
  10999. camLeft.position.copyFrom(this.position);
  11000. camRight.position.copyFrom(this.position);
  11001. }
  11002. else {
  11003. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  11004. this._getRigCamPosition(-this._cameraRigParams.stereoHalfAngle, camLeft.position);
  11005. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle, camRight.position);
  11006. camLeft.setTarget(this.getTarget());
  11007. camRight.setTarget(this.getTarget());
  11008. }
  11009. break;
  11010. }
  11011. _super.prototype._updateRigCameras.call(this);
  11012. };
  11013. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  11014. if (!this._rigCamTransformMatrix) {
  11015. this._rigCamTransformMatrix = new BABYLON.Matrix();
  11016. }
  11017. var target = this.getTarget();
  11018. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  11019. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  11020. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  11021. };
  11022. TargetCamera.prototype.serialize = function () {
  11023. var serializationObject = _super.prototype.serialize.call(this);
  11024. serializationObject.speed = this.speed;
  11025. if (this.rotation) {
  11026. serializationObject.rotation = this.rotation.asArray();
  11027. }
  11028. if (this.lockedTarget && this.lockedTarget.id) {
  11029. serializationObject.lockedTargetId = this.lockedTarget.id;
  11030. }
  11031. return serializationObject;
  11032. };
  11033. return TargetCamera;
  11034. })(BABYLON.Camera);
  11035. BABYLON.TargetCamera = TargetCamera;
  11036. })(BABYLON || (BABYLON = {}));
  11037. var BABYLON;
  11038. (function (BABYLON) {
  11039. var FreeCamera = (function (_super) {
  11040. __extends(FreeCamera, _super);
  11041. function FreeCamera(name, position, scene) {
  11042. var _this = this;
  11043. _super.call(this, name, position, scene);
  11044. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  11045. this.keysUp = [38];
  11046. this.keysDown = [40];
  11047. this.keysLeft = [37];
  11048. this.keysRight = [39];
  11049. this.checkCollisions = false;
  11050. this.applyGravity = false;
  11051. this.angularSensibility = 2000.0;
  11052. this._keys = [];
  11053. this._collider = new BABYLON.Collider();
  11054. this._needMoveForGravity = false;
  11055. this._oldPosition = BABYLON.Vector3.Zero();
  11056. this._diffPosition = BABYLON.Vector3.Zero();
  11057. this._newPosition = BABYLON.Vector3.Zero();
  11058. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  11059. if (collidedMesh === void 0) { collidedMesh = null; }
  11060. //TODO move this to the collision coordinator!
  11061. if (_this.getScene().workerCollisions)
  11062. newPosition.multiplyInPlace(_this._collider.radius);
  11063. var updatePosition = function (newPos) {
  11064. _this._newPosition.copyFrom(newPos);
  11065. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  11066. var oldPosition = _this.position.clone();
  11067. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  11068. _this.position.addInPlace(_this._diffPosition);
  11069. if (_this.onCollide && collidedMesh) {
  11070. _this.onCollide(collidedMesh);
  11071. }
  11072. }
  11073. };
  11074. updatePosition(newPosition);
  11075. };
  11076. }
  11077. FreeCamera.prototype._onLostFocus = function (e) {
  11078. this._keys = [];
  11079. };
  11080. // Controls
  11081. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  11082. var _this = this;
  11083. var previousPosition;
  11084. var engine = this.getEngine();
  11085. if (this._attachedElement) {
  11086. return;
  11087. }
  11088. this._attachedElement = element;
  11089. if (this._onMouseDown === undefined) {
  11090. this._onMouseDown = function (evt) {
  11091. previousPosition = {
  11092. x: evt.clientX,
  11093. y: evt.clientY
  11094. };
  11095. if (!noPreventDefault) {
  11096. evt.preventDefault();
  11097. }
  11098. };
  11099. this._onMouseUp = function (evt) {
  11100. previousPosition = null;
  11101. if (!noPreventDefault) {
  11102. evt.preventDefault();
  11103. }
  11104. };
  11105. this._onMouseOut = function (evt) {
  11106. previousPosition = null;
  11107. _this._keys = [];
  11108. if (!noPreventDefault) {
  11109. evt.preventDefault();
  11110. }
  11111. };
  11112. this._onMouseMove = function (evt) {
  11113. if (!previousPosition && !engine.isPointerLock) {
  11114. return;
  11115. }
  11116. var offsetX;
  11117. var offsetY;
  11118. if (!engine.isPointerLock) {
  11119. offsetX = evt.clientX - previousPosition.x;
  11120. offsetY = evt.clientY - previousPosition.y;
  11121. }
  11122. else {
  11123. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  11124. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  11125. }
  11126. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  11127. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  11128. previousPosition = {
  11129. x: evt.clientX,
  11130. y: evt.clientY
  11131. };
  11132. if (!noPreventDefault) {
  11133. evt.preventDefault();
  11134. }
  11135. };
  11136. this._onKeyDown = function (evt) {
  11137. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11138. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11139. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11140. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11141. var index = _this._keys.indexOf(evt.keyCode);
  11142. if (index === -1) {
  11143. _this._keys.push(evt.keyCode);
  11144. }
  11145. if (!noPreventDefault) {
  11146. evt.preventDefault();
  11147. }
  11148. }
  11149. };
  11150. this._onKeyUp = function (evt) {
  11151. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11152. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11153. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11154. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11155. var index = _this._keys.indexOf(evt.keyCode);
  11156. if (index >= 0) {
  11157. _this._keys.splice(index, 1);
  11158. }
  11159. if (!noPreventDefault) {
  11160. evt.preventDefault();
  11161. }
  11162. }
  11163. };
  11164. this._reset = function () {
  11165. _this._keys = [];
  11166. previousPosition = null;
  11167. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  11168. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  11169. };
  11170. }
  11171. element.addEventListener("mousedown", this._onMouseDown, false);
  11172. element.addEventListener("mouseup", this._onMouseUp, false);
  11173. element.addEventListener("mouseout", this._onMouseOut, false);
  11174. element.addEventListener("mousemove", this._onMouseMove, false);
  11175. BABYLON.Tools.RegisterTopRootEvents([
  11176. { name: "keydown", handler: this._onKeyDown },
  11177. { name: "keyup", handler: this._onKeyUp },
  11178. { name: "blur", handler: this._onLostFocus }
  11179. ]);
  11180. };
  11181. FreeCamera.prototype.detachControl = function (element) {
  11182. if (this._attachedElement !== element) {
  11183. return;
  11184. }
  11185. element.removeEventListener("mousedown", this._onMouseDown);
  11186. element.removeEventListener("mouseup", this._onMouseUp);
  11187. element.removeEventListener("mouseout", this._onMouseOut);
  11188. element.removeEventListener("mousemove", this._onMouseMove);
  11189. BABYLON.Tools.UnregisterTopRootEvents([
  11190. { name: "keydown", handler: this._onKeyDown },
  11191. { name: "keyup", handler: this._onKeyUp },
  11192. { name: "blur", handler: this._onLostFocus }
  11193. ]);
  11194. this._attachedElement = null;
  11195. if (this._reset) {
  11196. this._reset();
  11197. }
  11198. };
  11199. FreeCamera.prototype._collideWithWorld = function (velocity) {
  11200. var globalPosition;
  11201. if (this.parent) {
  11202. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  11203. }
  11204. else {
  11205. globalPosition = this.position;
  11206. }
  11207. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  11208. this._collider.radius = this.ellipsoid;
  11209. //no need for clone, as long as gravity is not on.
  11210. var actualVelocity = velocity;
  11211. //add gravity to the velocity to prevent the dual-collision checking
  11212. if (this.applyGravity) {
  11213. //this prevents mending with cameraDirection, a global variable of the free camera class.
  11214. actualVelocity = velocity.add(this.getScene().gravity);
  11215. }
  11216. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  11217. };
  11218. FreeCamera.prototype._checkInputs = function () {
  11219. if (!this._localDirection) {
  11220. this._localDirection = BABYLON.Vector3.Zero();
  11221. this._transformedDirection = BABYLON.Vector3.Zero();
  11222. }
  11223. // Keyboard
  11224. for (var index = 0; index < this._keys.length; index++) {
  11225. var keyCode = this._keys[index];
  11226. var speed = this._computeLocalCameraSpeed();
  11227. if (this.keysLeft.indexOf(keyCode) !== -1) {
  11228. this._localDirection.copyFromFloats(-speed, 0, 0);
  11229. }
  11230. else if (this.keysUp.indexOf(keyCode) !== -1) {
  11231. this._localDirection.copyFromFloats(0, 0, speed);
  11232. }
  11233. else if (this.keysRight.indexOf(keyCode) !== -1) {
  11234. this._localDirection.copyFromFloats(speed, 0, 0);
  11235. }
  11236. else if (this.keysDown.indexOf(keyCode) !== -1) {
  11237. this._localDirection.copyFromFloats(0, 0, -speed);
  11238. }
  11239. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  11240. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  11241. this.cameraDirection.addInPlace(this._transformedDirection);
  11242. }
  11243. _super.prototype._checkInputs.call(this);
  11244. };
  11245. FreeCamera.prototype._decideIfNeedsToMove = function () {
  11246. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  11247. };
  11248. FreeCamera.prototype._updatePosition = function () {
  11249. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  11250. this._collideWithWorld(this.cameraDirection);
  11251. }
  11252. else {
  11253. this.position.addInPlace(this.cameraDirection);
  11254. }
  11255. };
  11256. FreeCamera.prototype.serialize = function () {
  11257. var serializationObject = _super.prototype.serialize.call(this);
  11258. serializationObject.checkCollisions = this.checkCollisions;
  11259. serializationObject.applyGravity = this.applyGravity;
  11260. serializationObject.ellipsoid = this.ellipsoid.asArray();
  11261. return serializationObject;
  11262. };
  11263. return FreeCamera;
  11264. })(BABYLON.TargetCamera);
  11265. BABYLON.FreeCamera = FreeCamera;
  11266. })(BABYLON || (BABYLON = {}));
  11267. var BABYLON;
  11268. (function (BABYLON) {
  11269. var FollowCamera = (function (_super) {
  11270. __extends(FollowCamera, _super);
  11271. function FollowCamera(name, position, scene) {
  11272. _super.call(this, name, position, scene);
  11273. this.radius = 12;
  11274. this.rotationOffset = 0;
  11275. this.heightOffset = 4;
  11276. this.cameraAcceleration = 0.05;
  11277. this.maxCameraSpeed = 20;
  11278. }
  11279. FollowCamera.prototype.getRadians = function (degrees) {
  11280. return degrees * Math.PI / 180;
  11281. };
  11282. FollowCamera.prototype.follow = function (cameraTarget) {
  11283. if (!cameraTarget)
  11284. return;
  11285. var yRotation;
  11286. if (cameraTarget.rotationQuaternion) {
  11287. var rotMatrix = new BABYLON.Matrix();
  11288. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  11289. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  11290. }
  11291. else {
  11292. yRotation = cameraTarget.rotation.y;
  11293. }
  11294. var radians = this.getRadians(this.rotationOffset) + yRotation;
  11295. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  11296. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  11297. var dx = targetX - this.position.x;
  11298. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  11299. var dz = (targetZ) - this.position.z;
  11300. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  11301. var vy = dy * this.cameraAcceleration;
  11302. var vz = dz * this.cameraAcceleration * 2;
  11303. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  11304. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  11305. }
  11306. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  11307. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  11308. }
  11309. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  11310. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  11311. }
  11312. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  11313. this.setTarget(cameraTarget.position);
  11314. };
  11315. FollowCamera.prototype._checkInputs = function () {
  11316. _super.prototype._checkInputs.call(this);
  11317. this.follow(this.target);
  11318. };
  11319. FollowCamera.prototype.serialize = function () {
  11320. var serializationObject = _super.prototype.serialize.call(this);
  11321. serializationObject.radius = this.radius;
  11322. serializationObject.heightOffset = this.heightOffset;
  11323. serializationObject.rotationOffset = this.rotationOffset;
  11324. return serializationObject;
  11325. };
  11326. return FollowCamera;
  11327. })(BABYLON.TargetCamera);
  11328. BABYLON.FollowCamera = FollowCamera;
  11329. var ArcFollowCamera = (function (_super) {
  11330. __extends(ArcFollowCamera, _super);
  11331. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  11332. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  11333. this.alpha = alpha;
  11334. this.beta = beta;
  11335. this.radius = radius;
  11336. this.target = target;
  11337. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  11338. this.follow();
  11339. }
  11340. ArcFollowCamera.prototype.follow = function () {
  11341. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  11342. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  11343. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  11344. this.position = this.target.position.add(this._cartesianCoordinates);
  11345. this.setTarget(this.target.position);
  11346. };
  11347. ArcFollowCamera.prototype._checkInputs = function () {
  11348. _super.prototype._checkInputs.call(this);
  11349. this.follow();
  11350. };
  11351. ArcFollowCamera.prototype.serialize = function () {
  11352. var serializationObject = _super.prototype.serialize.call(this);
  11353. serializationObject.radius = this.radius;
  11354. return serializationObject;
  11355. };
  11356. return ArcFollowCamera;
  11357. })(BABYLON.TargetCamera);
  11358. BABYLON.ArcFollowCamera = ArcFollowCamera;
  11359. })(BABYLON || (BABYLON = {}));
  11360. var BABYLON;
  11361. (function (BABYLON) {
  11362. // We're mainly based on the logic defined into the FreeCamera code
  11363. var TouchCamera = (function (_super) {
  11364. __extends(TouchCamera, _super);
  11365. function TouchCamera(name, position, scene) {
  11366. _super.call(this, name, position, scene);
  11367. this._offsetX = null;
  11368. this._offsetY = null;
  11369. this._pointerCount = 0;
  11370. this._pointerPressed = [];
  11371. this.touchAngularSensibility = 200000.0;
  11372. this.touchMoveSensibility = 250.0;
  11373. }
  11374. TouchCamera.prototype._onLostFocus = function (e) {
  11375. this._offsetX = null;
  11376. this._offsetY = null;
  11377. _super.prototype._onLostFocus.call(this, e);
  11378. };
  11379. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  11380. var _this = this;
  11381. var previousPosition;
  11382. if (this._attachedCanvas) {
  11383. return;
  11384. }
  11385. if (this._onPointerDown === undefined) {
  11386. this._onPointerDown = function (evt) {
  11387. if (evt.pointerType === "mouse") {
  11388. return;
  11389. }
  11390. if (!noPreventDefault) {
  11391. evt.preventDefault();
  11392. }
  11393. _this._pointerPressed.push(evt.pointerId);
  11394. if (_this._pointerPressed.length !== 1) {
  11395. return;
  11396. }
  11397. previousPosition = {
  11398. x: evt.clientX,
  11399. y: evt.clientY
  11400. };
  11401. };
  11402. this._onPointerUp = function (evt) {
  11403. if (evt.pointerType === "mouse") {
  11404. return;
  11405. }
  11406. if (!noPreventDefault) {
  11407. evt.preventDefault();
  11408. }
  11409. var index = _this._pointerPressed.indexOf(evt.pointerId);
  11410. if (index === -1) {
  11411. return;
  11412. }
  11413. _this._pointerPressed.splice(index, 1);
  11414. if (index != 0) {
  11415. return;
  11416. }
  11417. previousPosition = null;
  11418. _this._offsetX = null;
  11419. _this._offsetY = null;
  11420. };
  11421. this._onPointerMove = function (evt) {
  11422. if (evt.pointerType === "mouse") {
  11423. return;
  11424. }
  11425. if (!noPreventDefault) {
  11426. evt.preventDefault();
  11427. }
  11428. if (!previousPosition) {
  11429. return;
  11430. }
  11431. var index = _this._pointerPressed.indexOf(evt.pointerId);
  11432. if (index != 0) {
  11433. return;
  11434. }
  11435. _this._offsetX = evt.clientX - previousPosition.x;
  11436. _this._offsetY = -(evt.clientY - previousPosition.y);
  11437. };
  11438. }
  11439. canvas.addEventListener("pointerdown", this._onPointerDown);
  11440. canvas.addEventListener("pointerup", this._onPointerUp);
  11441. canvas.addEventListener("pointerout", this._onPointerUp);
  11442. canvas.addEventListener("pointermove", this._onPointerMove);
  11443. _super.prototype.attachControl.call(this, canvas);
  11444. };
  11445. TouchCamera.prototype.detachControl = function (canvas) {
  11446. if (this._attachedCanvas !== canvas) {
  11447. return;
  11448. }
  11449. canvas.removeEventListener("pointerdown", this._onPointerDown);
  11450. canvas.removeEventListener("pointerup", this._onPointerUp);
  11451. canvas.removeEventListener("pointerout", this._onPointerUp);
  11452. canvas.removeEventListener("pointermove", this._onPointerMove);
  11453. _super.prototype.detachControl.call(this, canvas);
  11454. };
  11455. TouchCamera.prototype._checkInputs = function () {
  11456. if (this._offsetX) {
  11457. this.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  11458. if (this._pointerPressed.length > 1) {
  11459. this.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  11460. }
  11461. else {
  11462. var speed = this._computeLocalCameraSpeed();
  11463. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  11464. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  11465. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  11466. }
  11467. }
  11468. _super.prototype._checkInputs.call(this);
  11469. };
  11470. return TouchCamera;
  11471. })(BABYLON.FreeCamera);
  11472. BABYLON.TouchCamera = TouchCamera;
  11473. })(BABYLON || (BABYLON = {}));
  11474. var BABYLON;
  11475. (function (BABYLON) {
  11476. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  11477. var ArcRotateCamera = (function (_super) {
  11478. __extends(ArcRotateCamera, _super);
  11479. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  11480. var _this = this;
  11481. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  11482. this.alpha = alpha;
  11483. this.beta = beta;
  11484. this.radius = radius;
  11485. this.target = target;
  11486. this.inertialAlphaOffset = 0;
  11487. this.inertialBetaOffset = 0;
  11488. this.inertialRadiusOffset = 0;
  11489. this.lowerAlphaLimit = null;
  11490. this.upperAlphaLimit = null;
  11491. this.lowerBetaLimit = 0.01;
  11492. this.upperBetaLimit = Math.PI;
  11493. this.lowerRadiusLimit = null;
  11494. this.upperRadiusLimit = null;
  11495. this.angularSensibilityX = 1000.0;
  11496. this.angularSensibilityY = 1000.0;
  11497. this.wheelPrecision = 3.0;
  11498. this.pinchPrecision = 2.0;
  11499. this.panningSensibility = 50.0;
  11500. this.inertialPanningX = 0;
  11501. this.inertialPanningY = 0;
  11502. this.keysUp = [38];
  11503. this.keysDown = [40];
  11504. this.keysLeft = [37];
  11505. this.keysRight = [39];
  11506. this.zoomOnFactor = 1;
  11507. this.targetScreenOffset = BABYLON.Vector2.Zero();
  11508. this.pinchInwards = true;
  11509. this.allowUpsideDown = true;
  11510. this._keys = [];
  11511. this._viewMatrix = new BABYLON.Matrix();
  11512. // Panning
  11513. this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  11514. this._isRightClick = false;
  11515. this._isCtrlPushed = false;
  11516. this.checkCollisions = false;
  11517. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  11518. this._collider = new BABYLON.Collider();
  11519. this._previousPosition = BABYLON.Vector3.Zero();
  11520. this._collisionVelocity = BABYLON.Vector3.Zero();
  11521. this._newPosition = BABYLON.Vector3.Zero();
  11522. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  11523. if (collidedMesh === void 0) { collidedMesh = null; }
  11524. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  11525. newPosition.multiplyInPlace(_this._collider.radius);
  11526. }
  11527. if (!collidedMesh) {
  11528. _this._previousPosition.copyFrom(_this.position);
  11529. }
  11530. else {
  11531. _this.setPosition(newPosition);
  11532. if (_this.onCollide) {
  11533. _this.onCollide(collidedMesh);
  11534. }
  11535. }
  11536. // Recompute because of constraints
  11537. var cosa = Math.cos(_this.alpha);
  11538. var sina = Math.sin(_this.alpha);
  11539. var cosb = Math.cos(_this.beta);
  11540. var sinb = Math.sin(_this.beta);
  11541. var target = _this._getTargetPosition();
  11542. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  11543. _this.position.copyFrom(_this._newPosition);
  11544. var up = _this.upVector;
  11545. if (_this.allowUpsideDown && _this.beta < 0) {
  11546. up = up.clone();
  11547. up = up.negate();
  11548. }
  11549. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  11550. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  11551. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  11552. _this._collisionTriggered = false;
  11553. };
  11554. if (!this.target) {
  11555. this.target = BABYLON.Vector3.Zero();
  11556. }
  11557. this.getViewMatrix();
  11558. }
  11559. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibility", {
  11560. //deprecated angularSensibility support
  11561. get: function () {
  11562. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  11563. return Math.max(this.angularSensibilityX, this.angularSensibilityY);
  11564. },
  11565. //deprecated angularSensibility support
  11566. set: function (value) {
  11567. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  11568. this.angularSensibilityX = value;
  11569. this.angularSensibilityY = value;
  11570. },
  11571. enumerable: true,
  11572. configurable: true
  11573. });
  11574. ArcRotateCamera.prototype._getTargetPosition = function () {
  11575. return this.target.getAbsolutePosition ? this.target.getAbsolutePosition() : this.target;
  11576. };
  11577. // Cache
  11578. ArcRotateCamera.prototype._initCache = function () {
  11579. _super.prototype._initCache.call(this);
  11580. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  11581. this._cache.alpha = undefined;
  11582. this._cache.beta = undefined;
  11583. this._cache.radius = undefined;
  11584. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  11585. };
  11586. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  11587. if (!ignoreParentClass) {
  11588. _super.prototype._updateCache.call(this);
  11589. }
  11590. this._cache.target.copyFrom(this._getTargetPosition());
  11591. this._cache.alpha = this.alpha;
  11592. this._cache.beta = this.beta;
  11593. this._cache.radius = this.radius;
  11594. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  11595. };
  11596. // Synchronized
  11597. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  11598. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  11599. return false;
  11600. return this._cache.target.equals(this._getTargetPosition())
  11601. && this._cache.alpha === this.alpha
  11602. && this._cache.beta === this.beta
  11603. && this._cache.radius === this.radius
  11604. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  11605. };
  11606. // Methods
  11607. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning) {
  11608. var _this = this;
  11609. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  11610. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  11611. var previousPinchDistance = 0;
  11612. var pointers = new BABYLON.SmartCollection();
  11613. if (this._attachedElement) {
  11614. return;
  11615. }
  11616. this._attachedElement = element;
  11617. var engine = this.getEngine();
  11618. if (this._onPointerDown === undefined) {
  11619. this._onPointerDown = function (evt) {
  11620. // Manage panning with right click
  11621. _this._isRightClick = evt.button === 2;
  11622. // manage pointers
  11623. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  11624. cacheSoloPointer = pointers.item(evt.pointerId);
  11625. if (!noPreventDefault) {
  11626. evt.preventDefault();
  11627. }
  11628. };
  11629. this._onPointerUp = function (evt) {
  11630. cacheSoloPointer = null;
  11631. previousPinchDistance = 0;
  11632. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  11633. //but emptying completly pointers collection is required to fix a bug on iPhone :
  11634. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  11635. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  11636. pointers.empty();
  11637. if (!noPreventDefault) {
  11638. evt.preventDefault();
  11639. }
  11640. };
  11641. this._onContextMenu = function (evt) {
  11642. evt.preventDefault();
  11643. };
  11644. this._onPointerMove = function (evt) {
  11645. if (!noPreventDefault) {
  11646. evt.preventDefault();
  11647. }
  11648. switch (pointers.count) {
  11649. case 1:
  11650. if (_this.panningSensibility !== 0 && ((_this._isCtrlPushed && useCtrlForPanning) || (!useCtrlForPanning && _this._isRightClick))) {
  11651. _this.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  11652. _this.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  11653. }
  11654. else {
  11655. var offsetX = evt.clientX - cacheSoloPointer.x;
  11656. var offsetY = evt.clientY - cacheSoloPointer.y;
  11657. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  11658. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  11659. }
  11660. cacheSoloPointer.x = evt.clientX;
  11661. cacheSoloPointer.y = evt.clientY;
  11662. break;
  11663. case 2:
  11664. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  11665. pointers.item(evt.pointerId).x = evt.clientX;
  11666. pointers.item(evt.pointerId).y = evt.clientY;
  11667. var direction = _this.pinchInwards ? 1 : -1;
  11668. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  11669. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  11670. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  11671. if (previousPinchDistance === 0) {
  11672. previousPinchDistance = pinchSquaredDistance;
  11673. return;
  11674. }
  11675. if (pinchSquaredDistance !== previousPinchDistance) {
  11676. _this.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (_this.pinchPrecision * _this.wheelPrecision * ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) * direction);
  11677. previousPinchDistance = pinchSquaredDistance;
  11678. }
  11679. break;
  11680. default:
  11681. if (pointers.item(evt.pointerId)) {
  11682. pointers.item(evt.pointerId).x = evt.clientX;
  11683. pointers.item(evt.pointerId).y = evt.clientY;
  11684. }
  11685. }
  11686. };
  11687. this._onMouseMove = function (evt) {
  11688. if (!engine.isPointerLock) {
  11689. return;
  11690. }
  11691. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  11692. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  11693. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  11694. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  11695. if (!noPreventDefault) {
  11696. evt.preventDefault();
  11697. }
  11698. };
  11699. this._wheel = function (event) {
  11700. var delta = 0;
  11701. if (event.wheelDelta) {
  11702. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  11703. }
  11704. else if (event.detail) {
  11705. delta = -event.detail / _this.wheelPrecision;
  11706. }
  11707. if (delta)
  11708. _this.inertialRadiusOffset += delta;
  11709. if (event.preventDefault) {
  11710. if (!noPreventDefault) {
  11711. event.preventDefault();
  11712. }
  11713. }
  11714. };
  11715. this._onKeyDown = function (evt) {
  11716. _this._isCtrlPushed = evt.ctrlKey;
  11717. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11718. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11719. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11720. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11721. var index = _this._keys.indexOf(evt.keyCode);
  11722. if (index === -1) {
  11723. _this._keys.push(evt.keyCode);
  11724. }
  11725. if (evt.preventDefault) {
  11726. if (!noPreventDefault) {
  11727. evt.preventDefault();
  11728. }
  11729. }
  11730. }
  11731. };
  11732. this._onKeyUp = function (evt) {
  11733. _this._isCtrlPushed = evt.ctrlKey;
  11734. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11735. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11736. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11737. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11738. var index = _this._keys.indexOf(evt.keyCode);
  11739. if (index >= 0) {
  11740. _this._keys.splice(index, 1);
  11741. }
  11742. if (evt.preventDefault) {
  11743. if (!noPreventDefault) {
  11744. evt.preventDefault();
  11745. }
  11746. }
  11747. }
  11748. };
  11749. this._onLostFocus = function () {
  11750. _this._keys = [];
  11751. pointers.empty();
  11752. previousPinchDistance = 0;
  11753. cacheSoloPointer = null;
  11754. };
  11755. this._onGestureStart = function (e) {
  11756. if (window.MSGesture === undefined) {
  11757. return;
  11758. }
  11759. if (!_this._MSGestureHandler) {
  11760. _this._MSGestureHandler = new MSGesture();
  11761. _this._MSGestureHandler.target = element;
  11762. }
  11763. _this._MSGestureHandler.addPointer(e.pointerId);
  11764. };
  11765. this._onGesture = function (e) {
  11766. _this.radius *= e.scale;
  11767. if (e.preventDefault) {
  11768. if (!noPreventDefault) {
  11769. e.stopPropagation();
  11770. e.preventDefault();
  11771. }
  11772. }
  11773. };
  11774. this._reset = function () {
  11775. _this._keys = [];
  11776. _this.inertialAlphaOffset = 0;
  11777. _this.inertialBetaOffset = 0;
  11778. _this.inertialRadiusOffset = 0;
  11779. pointers.empty();
  11780. previousPinchDistance = 0;
  11781. cacheSoloPointer = null;
  11782. };
  11783. }
  11784. if (!useCtrlForPanning) {
  11785. element.addEventListener("contextmenu", this._onContextMenu, false);
  11786. }
  11787. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  11788. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  11789. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  11790. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  11791. element.addEventListener("mousemove", this._onMouseMove, false);
  11792. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  11793. element.addEventListener("MSGestureChange", this._onGesture, false);
  11794. element.addEventListener('mousewheel', this._wheel, false);
  11795. element.addEventListener('DOMMouseScroll', this._wheel, false);
  11796. BABYLON.Tools.RegisterTopRootEvents([
  11797. { name: "keydown", handler: this._onKeyDown },
  11798. { name: "keyup", handler: this._onKeyUp },
  11799. { name: "blur", handler: this._onLostFocus }
  11800. ]);
  11801. };
  11802. ArcRotateCamera.prototype.detachControl = function (element) {
  11803. if (this._attachedElement !== element) {
  11804. return;
  11805. }
  11806. element.removeEventListener("contextmenu", this._onContextMenu);
  11807. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  11808. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  11809. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  11810. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  11811. element.removeEventListener("mousemove", this._onMouseMove);
  11812. element.removeEventListener("MSPointerDown", this._onGestureStart);
  11813. element.removeEventListener("MSGestureChange", this._onGesture);
  11814. element.removeEventListener('mousewheel', this._wheel);
  11815. element.removeEventListener('DOMMouseScroll', this._wheel);
  11816. BABYLON.Tools.UnregisterTopRootEvents([
  11817. { name: "keydown", handler: this._onKeyDown },
  11818. { name: "keyup", handler: this._onKeyUp },
  11819. { name: "blur", handler: this._onLostFocus }
  11820. ]);
  11821. this._MSGestureHandler = null;
  11822. this._attachedElement = null;
  11823. if (this._reset) {
  11824. this._reset();
  11825. }
  11826. };
  11827. ArcRotateCamera.prototype._checkInputs = function () {
  11828. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  11829. if (this._collisionTriggered) {
  11830. return;
  11831. }
  11832. // Keyboard
  11833. for (var index = 0; index < this._keys.length; index++) {
  11834. var keyCode = this._keys[index];
  11835. if (this.keysLeft.indexOf(keyCode) !== -1) {
  11836. this.inertialAlphaOffset -= 0.01;
  11837. }
  11838. else if (this.keysUp.indexOf(keyCode) !== -1) {
  11839. this.inertialBetaOffset -= 0.01;
  11840. }
  11841. else if (this.keysRight.indexOf(keyCode) !== -1) {
  11842. this.inertialAlphaOffset += 0.01;
  11843. }
  11844. else if (this.keysDown.indexOf(keyCode) !== -1) {
  11845. this.inertialBetaOffset += 0.01;
  11846. }
  11847. }
  11848. // Inertia
  11849. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  11850. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  11851. this.beta += this.inertialBetaOffset;
  11852. this.radius -= this.inertialRadiusOffset;
  11853. this.inertialAlphaOffset *= this.inertia;
  11854. this.inertialBetaOffset *= this.inertia;
  11855. this.inertialRadiusOffset *= this.inertia;
  11856. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  11857. this.inertialAlphaOffset = 0;
  11858. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  11859. this.inertialBetaOffset = 0;
  11860. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  11861. this.inertialRadiusOffset = 0;
  11862. }
  11863. // Panning inertia
  11864. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  11865. if (!this._localDirection) {
  11866. this._localDirection = BABYLON.Vector3.Zero();
  11867. this._transformedDirection = BABYLON.Vector3.Zero();
  11868. }
  11869. this.inertialPanningX *= this.inertia;
  11870. this.inertialPanningY *= this.inertia;
  11871. if (Math.abs(this.inertialPanningX) < BABYLON.Engine.Epsilon)
  11872. this.inertialPanningX = 0;
  11873. if (Math.abs(this.inertialPanningY) < BABYLON.Engine.Epsilon)
  11874. this.inertialPanningY = 0;
  11875. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  11876. this._localDirection.multiplyInPlace(this.panningAxis);
  11877. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  11878. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  11879. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  11880. if (!this.panningAxis.y) {
  11881. this._transformedDirection.y = 0;
  11882. }
  11883. this.target.addInPlace(this._transformedDirection);
  11884. }
  11885. // Limits
  11886. this._checkLimits();
  11887. _super.prototype._checkInputs.call(this);
  11888. };
  11889. ArcRotateCamera.prototype._checkLimits = function () {
  11890. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  11891. if (this.allowUpsideDown && this.beta > Math.PI) {
  11892. this.beta = this.beta - (2 * Math.PI);
  11893. }
  11894. }
  11895. else {
  11896. if (this.beta < this.lowerBetaLimit) {
  11897. this.beta = this.lowerBetaLimit;
  11898. }
  11899. }
  11900. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  11901. if (this.allowUpsideDown && this.beta < -Math.PI) {
  11902. this.beta = this.beta + (2 * Math.PI);
  11903. }
  11904. }
  11905. else {
  11906. if (this.beta > this.upperBetaLimit) {
  11907. this.beta = this.upperBetaLimit;
  11908. }
  11909. }
  11910. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  11911. this.alpha = this.lowerAlphaLimit;
  11912. }
  11913. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  11914. this.alpha = this.upperAlphaLimit;
  11915. }
  11916. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  11917. this.radius = this.lowerRadiusLimit;
  11918. }
  11919. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  11920. this.radius = this.upperRadiusLimit;
  11921. }
  11922. };
  11923. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  11924. var radiusv3 = this.position.subtract(this._getTargetPosition());
  11925. this.radius = radiusv3.length();
  11926. // Alpha
  11927. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  11928. if (radiusv3.z < 0) {
  11929. this.alpha = 2 * Math.PI - this.alpha;
  11930. }
  11931. // Beta
  11932. this.beta = Math.acos(radiusv3.y / this.radius);
  11933. this._checkLimits();
  11934. };
  11935. ArcRotateCamera.prototype.setPosition = function (position) {
  11936. if (this.position.equals(position)) {
  11937. return;
  11938. }
  11939. this.position = position;
  11940. this.rebuildAnglesAndRadius();
  11941. };
  11942. ArcRotateCamera.prototype.setTarget = function (target) {
  11943. if (this.target.equals(target)) {
  11944. return;
  11945. }
  11946. this.target = target;
  11947. this.rebuildAnglesAndRadius();
  11948. };
  11949. ArcRotateCamera.prototype._getViewMatrix = function () {
  11950. // Compute
  11951. var cosa = Math.cos(this.alpha);
  11952. var sina = Math.sin(this.alpha);
  11953. var cosb = Math.cos(this.beta);
  11954. var sinb = Math.sin(this.beta);
  11955. var target = this._getTargetPosition();
  11956. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  11957. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  11958. this._collider.radius = this.collisionRadius;
  11959. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  11960. this._collisionTriggered = true;
  11961. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  11962. }
  11963. else {
  11964. this.position.copyFrom(this._newPosition);
  11965. var up = this.upVector;
  11966. if (this.allowUpsideDown && this.beta < 0) {
  11967. up = up.clone();
  11968. up = up.negate();
  11969. }
  11970. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  11971. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  11972. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  11973. }
  11974. return this._viewMatrix;
  11975. };
  11976. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  11977. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  11978. meshes = meshes || this.getScene().meshes;
  11979. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  11980. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  11981. this.radius = distance * this.zoomOnFactor;
  11982. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  11983. };
  11984. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  11985. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  11986. var meshesOrMinMaxVector;
  11987. var distance;
  11988. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  11989. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  11990. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  11991. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  11992. }
  11993. else {
  11994. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  11995. distance = meshesOrMinMaxVectorAndDistance.distance;
  11996. }
  11997. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  11998. if (!doNotUpdateMaxZ) {
  11999. this.maxZ = distance * 2;
  12000. }
  12001. };
  12002. /**
  12003. * @override
  12004. * Override Camera.createRigCamera
  12005. */
  12006. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  12007. switch (this.cameraRigMode) {
  12008. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  12009. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  12010. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  12011. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  12012. case BABYLON.Camera.RIG_MODE_VR:
  12013. var alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  12014. return new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  12015. }
  12016. return null;
  12017. };
  12018. /**
  12019. * @override
  12020. * Override Camera._updateRigCameras
  12021. */
  12022. ArcRotateCamera.prototype._updateRigCameras = function () {
  12023. switch (this.cameraRigMode) {
  12024. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  12025. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  12026. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  12027. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  12028. case BABYLON.Camera.RIG_MODE_VR:
  12029. var camLeft = this._rigCameras[0];
  12030. var camRight = this._rigCameras[1];
  12031. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  12032. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  12033. camLeft.beta = camRight.beta = this.beta;
  12034. camLeft.radius = camRight.radius = this.radius;
  12035. break;
  12036. }
  12037. _super.prototype._updateRigCameras.call(this);
  12038. };
  12039. ArcRotateCamera.prototype.serialize = function () {
  12040. var serializationObject = _super.prototype.serialize.call(this);
  12041. if (this.target instanceof BABYLON.Vector3) {
  12042. serializationObject.target = this.target.asArray();
  12043. }
  12044. if (this.target && this.target.id) {
  12045. serializationObject.lockedTargetId = this.target.id;
  12046. }
  12047. serializationObject.checkCollisions = this.checkCollisions;
  12048. serializationObject.alpha = this.alpha;
  12049. serializationObject.beta = this.beta;
  12050. serializationObject.radius = this.radius;
  12051. return serializationObject;
  12052. };
  12053. return ArcRotateCamera;
  12054. })(BABYLON.TargetCamera);
  12055. BABYLON.ArcRotateCamera = ArcRotateCamera;
  12056. })(BABYLON || (BABYLON = {}));
  12057. var BABYLON;
  12058. (function (BABYLON) {
  12059. var RenderingManager = (function () {
  12060. function RenderingManager(scene) {
  12061. this._renderingGroups = new Array();
  12062. this._scene = scene;
  12063. }
  12064. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  12065. if (this._scene._activeParticleSystems.length === 0) {
  12066. return;
  12067. }
  12068. // Particles
  12069. var activeCamera = this._scene.activeCamera;
  12070. var beforeParticlesDate = BABYLON.Tools.Now;
  12071. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  12072. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  12073. if (particleSystem.renderingGroupId !== index) {
  12074. continue;
  12075. }
  12076. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  12077. continue;
  12078. }
  12079. this._clearDepthBuffer();
  12080. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  12081. this._scene._activeParticles += particleSystem.render();
  12082. }
  12083. }
  12084. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  12085. };
  12086. RenderingManager.prototype._renderSprites = function (index) {
  12087. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  12088. return;
  12089. }
  12090. // Sprites
  12091. var activeCamera = this._scene.activeCamera;
  12092. var beforeSpritessDate = BABYLON.Tools.Now;
  12093. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  12094. var spriteManager = this._scene.spriteManagers[id];
  12095. if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  12096. this._clearDepthBuffer();
  12097. spriteManager.render();
  12098. }
  12099. }
  12100. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  12101. };
  12102. RenderingManager.prototype._clearDepthBuffer = function () {
  12103. if (this._depthBufferAlreadyCleaned) {
  12104. return;
  12105. }
  12106. this._scene.getEngine().clear(0, false, true);
  12107. this._depthBufferAlreadyCleaned = true;
  12108. };
  12109. RenderingManager.prototype._renderSpritesAndParticles = function () {
  12110. if (this._currentRenderSprites) {
  12111. this._renderSprites(this._currentIndex);
  12112. }
  12113. if (this._currentRenderParticles) {
  12114. this._renderParticles(this._currentIndex, this._currentActiveMeshes);
  12115. }
  12116. };
  12117. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  12118. this._currentActiveMeshes = activeMeshes;
  12119. this._currentRenderParticles = renderParticles;
  12120. this._currentRenderSprites = renderSprites;
  12121. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  12122. this._depthBufferAlreadyCleaned = index == 0;
  12123. var renderingGroup = this._renderingGroups[index];
  12124. var needToStepBack = false;
  12125. this._currentIndex = index;
  12126. if (renderingGroup) {
  12127. this._clearDepthBuffer();
  12128. if (!renderingGroup.onBeforeTransparentRendering) {
  12129. renderingGroup.onBeforeTransparentRendering = this._renderSpritesAndParticles.bind(this);
  12130. }
  12131. if (!renderingGroup.render(customRenderFunction)) {
  12132. this._renderingGroups.splice(index, 1);
  12133. needToStepBack = true;
  12134. this._renderSpritesAndParticles();
  12135. }
  12136. }
  12137. else {
  12138. this._renderSpritesAndParticles();
  12139. }
  12140. if (needToStepBack) {
  12141. index--;
  12142. }
  12143. }
  12144. };
  12145. RenderingManager.prototype.reset = function () {
  12146. this._renderingGroups.forEach(function (renderingGroup, index, array) {
  12147. if (renderingGroup) {
  12148. renderingGroup.prepare();
  12149. }
  12150. });
  12151. };
  12152. RenderingManager.prototype.dispatch = function (subMesh) {
  12153. var mesh = subMesh.getMesh();
  12154. var renderingGroupId = mesh.renderingGroupId || 0;
  12155. if (!this._renderingGroups[renderingGroupId]) {
  12156. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  12157. }
  12158. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  12159. };
  12160. RenderingManager.MAX_RENDERINGGROUPS = 4;
  12161. return RenderingManager;
  12162. })();
  12163. BABYLON.RenderingManager = RenderingManager;
  12164. })(BABYLON || (BABYLON = {}));
  12165. var BABYLON;
  12166. (function (BABYLON) {
  12167. var RenderingGroup = (function () {
  12168. function RenderingGroup(index, scene) {
  12169. this.index = index;
  12170. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  12171. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  12172. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  12173. this._scene = scene;
  12174. }
  12175. RenderingGroup.prototype.render = function (customRenderFunction) {
  12176. if (customRenderFunction) {
  12177. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  12178. return true;
  12179. }
  12180. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  12181. if (this.onBeforeTransparentRendering) {
  12182. this.onBeforeTransparentRendering();
  12183. }
  12184. return false;
  12185. }
  12186. var engine = this._scene.getEngine();
  12187. // Opaque
  12188. var subIndex;
  12189. var submesh;
  12190. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  12191. submesh = this._opaqueSubMeshes.data[subIndex];
  12192. submesh.render(false);
  12193. }
  12194. // Alpha test
  12195. engine.setAlphaTesting(true);
  12196. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  12197. submesh = this._alphaTestSubMeshes.data[subIndex];
  12198. submesh.render(false);
  12199. }
  12200. engine.setAlphaTesting(false);
  12201. if (this.onBeforeTransparentRendering) {
  12202. this.onBeforeTransparentRendering();
  12203. }
  12204. // Transparent
  12205. if (this._transparentSubMeshes.length) {
  12206. // Sorting
  12207. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  12208. submesh = this._transparentSubMeshes.data[subIndex];
  12209. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  12210. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.globalPosition).length();
  12211. }
  12212. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  12213. sortedArray.sort(function (a, b) {
  12214. // Alpha index first
  12215. if (a._alphaIndex > b._alphaIndex) {
  12216. return 1;
  12217. }
  12218. if (a._alphaIndex < b._alphaIndex) {
  12219. return -1;
  12220. }
  12221. // Then distance to camera
  12222. if (a._distanceToCamera < b._distanceToCamera) {
  12223. return 1;
  12224. }
  12225. if (a._distanceToCamera > b._distanceToCamera) {
  12226. return -1;
  12227. }
  12228. return 0;
  12229. });
  12230. // Rendering
  12231. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  12232. submesh = sortedArray[subIndex];
  12233. submesh.render(true);
  12234. }
  12235. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12236. }
  12237. return true;
  12238. };
  12239. RenderingGroup.prototype.prepare = function () {
  12240. this._opaqueSubMeshes.reset();
  12241. this._transparentSubMeshes.reset();
  12242. this._alphaTestSubMeshes.reset();
  12243. };
  12244. RenderingGroup.prototype.dispatch = function (subMesh) {
  12245. var material = subMesh.getMaterial();
  12246. var mesh = subMesh.getMesh();
  12247. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  12248. this._transparentSubMeshes.push(subMesh);
  12249. }
  12250. else if (material.needAlphaTesting()) {
  12251. this._alphaTestSubMeshes.push(subMesh);
  12252. }
  12253. else {
  12254. this._opaqueSubMeshes.push(subMesh); // Opaque
  12255. }
  12256. };
  12257. return RenderingGroup;
  12258. })();
  12259. BABYLON.RenderingGroup = RenderingGroup;
  12260. })(BABYLON || (BABYLON = {}));
  12261. var BABYLON;
  12262. (function (BABYLON) {
  12263. /**
  12264. * Represents a scene to be rendered by the engine.
  12265. * @see http://doc.babylonjs.com/page.php?p=21911
  12266. */
  12267. var Scene = (function () {
  12268. /**
  12269. * @constructor
  12270. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  12271. */
  12272. function Scene(engine) {
  12273. // Members
  12274. this.autoClear = true;
  12275. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  12276. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  12277. this.forceWireframe = false;
  12278. this.forcePointsCloud = false;
  12279. this.forceShowBoundingBoxes = false;
  12280. this.animationsEnabled = true;
  12281. this.constantlyUpdateMeshUnderPointer = false;
  12282. // Animations
  12283. this.animations = [];
  12284. 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
  12285. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  12286. this._startingPointerTime = 0;
  12287. // Fog
  12288. /**
  12289. * is fog enabled on this scene.
  12290. * @type {boolean}
  12291. */
  12292. this.fogEnabled = true;
  12293. this.fogMode = Scene.FOGMODE_NONE;
  12294. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  12295. this.fogDensity = 0.1;
  12296. this.fogStart = 0;
  12297. this.fogEnd = 1000.0;
  12298. // Lights
  12299. /**
  12300. * is shadow enabled on this scene.
  12301. * @type {boolean}
  12302. */
  12303. this.shadowsEnabled = true;
  12304. /**
  12305. * is light enabled on this scene.
  12306. * @type {boolean}
  12307. */
  12308. this.lightsEnabled = true;
  12309. /**
  12310. * All of the lights added to this scene.
  12311. * @see BABYLON.Light
  12312. * @type {BABYLON.Light[]}
  12313. */
  12314. this.lights = new Array();
  12315. // Cameras
  12316. /**
  12317. * All of the cameras added to this scene.
  12318. * @see BABYLON.Camera
  12319. * @type {BABYLON.Camera[]}
  12320. */
  12321. this.cameras = new Array();
  12322. this.activeCameras = new Array();
  12323. // Meshes
  12324. /**
  12325. * All of the (abstract) meshes added to this scene.
  12326. * @see BABYLON.AbstractMesh
  12327. * @type {BABYLON.AbstractMesh[]}
  12328. */
  12329. this.meshes = new Array();
  12330. // Geometries
  12331. this._geometries = new Array();
  12332. this.materials = new Array();
  12333. this.multiMaterials = new Array();
  12334. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  12335. // Textures
  12336. this.texturesEnabled = true;
  12337. this.textures = new Array();
  12338. // Particles
  12339. this.particlesEnabled = true;
  12340. this.particleSystems = new Array();
  12341. // Sprites
  12342. this.spritesEnabled = true;
  12343. this.spriteManagers = new Array();
  12344. // Layers
  12345. this.layers = new Array();
  12346. // Skeletons
  12347. this.skeletonsEnabled = true;
  12348. this.skeletons = new Array();
  12349. // Lens flares
  12350. this.lensFlaresEnabled = true;
  12351. this.lensFlareSystems = new Array();
  12352. // Collisions
  12353. this.collisionsEnabled = true;
  12354. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  12355. // Postprocesses
  12356. this.postProcessesEnabled = true;
  12357. // Customs render targets
  12358. this.renderTargetsEnabled = true;
  12359. this.dumpNextRenderTargets = false;
  12360. this.customRenderTargets = new Array();
  12361. // Imported meshes
  12362. this.importedMeshesFiles = new Array();
  12363. // Probes
  12364. this.probesEnabled = true;
  12365. this.reflectionProbes = new Array();
  12366. this._actionManagers = new Array();
  12367. this._meshesForIntersections = new BABYLON.SmartArray(256);
  12368. // Procedural textures
  12369. this.proceduralTexturesEnabled = true;
  12370. this._proceduralTextures = new Array();
  12371. this.soundTracks = new Array();
  12372. this._audioEnabled = true;
  12373. this._headphone = false;
  12374. this._totalVertices = 0;
  12375. this._activeIndices = 0;
  12376. this._activeParticles = 0;
  12377. this._lastFrameDuration = 0;
  12378. this._evaluateActiveMeshesDuration = 0;
  12379. this._renderTargetsDuration = 0;
  12380. this._particlesDuration = 0;
  12381. this._renderDuration = 0;
  12382. this._spritesDuration = 0;
  12383. this._animationRatio = 0;
  12384. this._renderId = 0;
  12385. this._executeWhenReadyTimeoutId = -1;
  12386. this._toBeDisposed = new BABYLON.SmartArray(256);
  12387. this._onReadyCallbacks = new Array();
  12388. this._pendingData = []; //ANY
  12389. this._onBeforeRenderCallbacks = new Array();
  12390. this._onAfterRenderCallbacks = new Array();
  12391. this._activeMeshes = new BABYLON.SmartArray(256);
  12392. this._processedMaterials = new BABYLON.SmartArray(256);
  12393. this._renderTargets = new BABYLON.SmartArray(256);
  12394. this._activeParticleSystems = new BABYLON.SmartArray(256);
  12395. this._activeSkeletons = new BABYLON.SmartArray(32);
  12396. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  12397. this._activeBones = 0;
  12398. this._activeAnimatables = new Array();
  12399. this._transformMatrix = BABYLON.Matrix.Zero();
  12400. this._edgesRenderers = new BABYLON.SmartArray(16);
  12401. this._uniqueIdCounter = 0;
  12402. this._engine = engine;
  12403. engine.scenes.push(this);
  12404. this._renderingManager = new BABYLON.RenderingManager(this);
  12405. this.postProcessManager = new BABYLON.PostProcessManager(this);
  12406. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  12407. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  12408. if (BABYLON.OutlineRenderer) {
  12409. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  12410. }
  12411. this.attachControl();
  12412. this._debugLayer = new BABYLON.DebugLayer(this);
  12413. if (BABYLON.SoundTrack) {
  12414. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  12415. }
  12416. //simplification queue
  12417. if (BABYLON.SimplificationQueue) {
  12418. this.simplificationQueue = new BABYLON.SimplificationQueue();
  12419. }
  12420. //collision coordinator initialization. For now legacy per default.
  12421. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  12422. }
  12423. Object.defineProperty(Scene, "FOGMODE_NONE", {
  12424. get: function () {
  12425. return Scene._FOGMODE_NONE;
  12426. },
  12427. enumerable: true,
  12428. configurable: true
  12429. });
  12430. Object.defineProperty(Scene, "FOGMODE_EXP", {
  12431. get: function () {
  12432. return Scene._FOGMODE_EXP;
  12433. },
  12434. enumerable: true,
  12435. configurable: true
  12436. });
  12437. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  12438. get: function () {
  12439. return Scene._FOGMODE_EXP2;
  12440. },
  12441. enumerable: true,
  12442. configurable: true
  12443. });
  12444. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  12445. get: function () {
  12446. return Scene._FOGMODE_LINEAR;
  12447. },
  12448. enumerable: true,
  12449. configurable: true
  12450. });
  12451. Object.defineProperty(Scene.prototype, "debugLayer", {
  12452. // Properties
  12453. get: function () {
  12454. return this._debugLayer;
  12455. },
  12456. enumerable: true,
  12457. configurable: true
  12458. });
  12459. Object.defineProperty(Scene.prototype, "workerCollisions", {
  12460. get: function () {
  12461. return this._workerCollisions;
  12462. },
  12463. set: function (enabled) {
  12464. enabled = (enabled && !!Worker);
  12465. this._workerCollisions = enabled;
  12466. if (this.collisionCoordinator) {
  12467. this.collisionCoordinator.destroy();
  12468. }
  12469. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  12470. this.collisionCoordinator.init(this);
  12471. },
  12472. enumerable: true,
  12473. configurable: true
  12474. });
  12475. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  12476. get: function () {
  12477. return this._selectionOctree;
  12478. },
  12479. enumerable: true,
  12480. configurable: true
  12481. });
  12482. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  12483. /**
  12484. * The mesh that is currently under the pointer.
  12485. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  12486. */
  12487. get: function () {
  12488. return this._pointerOverMesh;
  12489. },
  12490. enumerable: true,
  12491. configurable: true
  12492. });
  12493. Object.defineProperty(Scene.prototype, "pointerX", {
  12494. /**
  12495. * Current on-screen X position of the pointer
  12496. * @return {number} X position of the pointer
  12497. */
  12498. get: function () {
  12499. return this._pointerX;
  12500. },
  12501. enumerable: true,
  12502. configurable: true
  12503. });
  12504. Object.defineProperty(Scene.prototype, "pointerY", {
  12505. /**
  12506. * Current on-screen Y position of the pointer
  12507. * @return {number} Y position of the pointer
  12508. */
  12509. get: function () {
  12510. return this._pointerY;
  12511. },
  12512. enumerable: true,
  12513. configurable: true
  12514. });
  12515. Scene.prototype.getCachedMaterial = function () {
  12516. return this._cachedMaterial;
  12517. };
  12518. Scene.prototype.getBoundingBoxRenderer = function () {
  12519. return this._boundingBoxRenderer;
  12520. };
  12521. Scene.prototype.getOutlineRenderer = function () {
  12522. return this._outlineRenderer;
  12523. };
  12524. Scene.prototype.getEngine = function () {
  12525. return this._engine;
  12526. };
  12527. Scene.prototype.getTotalVertices = function () {
  12528. return this._totalVertices;
  12529. };
  12530. Scene.prototype.getActiveIndices = function () {
  12531. return this._activeIndices;
  12532. };
  12533. Scene.prototype.getActiveParticles = function () {
  12534. return this._activeParticles;
  12535. };
  12536. Scene.prototype.getActiveBones = function () {
  12537. return this._activeBones;
  12538. };
  12539. // Stats
  12540. Scene.prototype.getLastFrameDuration = function () {
  12541. return this._lastFrameDuration;
  12542. };
  12543. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  12544. return this._evaluateActiveMeshesDuration;
  12545. };
  12546. Scene.prototype.getActiveMeshes = function () {
  12547. return this._activeMeshes;
  12548. };
  12549. Scene.prototype.getRenderTargetsDuration = function () {
  12550. return this._renderTargetsDuration;
  12551. };
  12552. Scene.prototype.getRenderDuration = function () {
  12553. return this._renderDuration;
  12554. };
  12555. Scene.prototype.getParticlesDuration = function () {
  12556. return this._particlesDuration;
  12557. };
  12558. Scene.prototype.getSpritesDuration = function () {
  12559. return this._spritesDuration;
  12560. };
  12561. Scene.prototype.getAnimationRatio = function () {
  12562. return this._animationRatio;
  12563. };
  12564. Scene.prototype.getRenderId = function () {
  12565. return this._renderId;
  12566. };
  12567. Scene.prototype.incrementRenderId = function () {
  12568. this._renderId++;
  12569. };
  12570. Scene.prototype._updatePointerPosition = function (evt) {
  12571. var canvasRect = this._engine.getRenderingCanvasClientRect();
  12572. this._pointerX = evt.clientX - canvasRect.left;
  12573. this._pointerY = evt.clientY - canvasRect.top;
  12574. if (this.cameraToUseForPointers) {
  12575. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  12576. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  12577. }
  12578. };
  12579. // Pointers handling
  12580. Scene.prototype.attachControl = function () {
  12581. var _this = this;
  12582. var spritePredicate = function (sprite) {
  12583. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  12584. };
  12585. this._onPointerMove = function (evt) {
  12586. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  12587. return;
  12588. }
  12589. var canvas = _this._engine.getRenderingCanvas();
  12590. _this._updatePointerPosition(evt);
  12591. // Meshes
  12592. 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);
  12593. if (pickResult.hit && pickResult.pickedMesh) {
  12594. _this.setPointerOverSprite(null);
  12595. _this.setPointerOverMesh(pickResult.pickedMesh);
  12596. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  12597. canvas.style.cursor = "pointer";
  12598. }
  12599. else {
  12600. canvas.style.cursor = "";
  12601. }
  12602. }
  12603. else {
  12604. _this.setPointerOverMesh(null);
  12605. // Sprites
  12606. pickResult = _this.pickSprite(_this._pointerX, _this._pointerY, spritePredicate, false, _this.cameraToUseForPointers);
  12607. if (pickResult.hit && pickResult.pickedSprite) {
  12608. canvas.style.cursor = "pointer";
  12609. _this.setPointerOverSprite(pickResult.pickedSprite);
  12610. }
  12611. else {
  12612. _this.setPointerOverSprite(null);
  12613. // Restore pointer
  12614. canvas.style.cursor = "";
  12615. }
  12616. }
  12617. if (_this.onPointerMove) {
  12618. _this.onPointerMove(evt, pickResult);
  12619. }
  12620. };
  12621. this._onPointerDown = function (evt) {
  12622. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  12623. return;
  12624. }
  12625. _this._updatePointerPosition(evt);
  12626. _this._startingPointerPosition.x = _this._pointerX;
  12627. _this._startingPointerPosition.y = _this._pointerY;
  12628. _this._startingPointerTime = new Date().getTime();
  12629. var predicate = null;
  12630. // Meshes
  12631. _this._pickedDownMesh = null;
  12632. if (!_this.onPointerDown && !_this.onPointerPick) {
  12633. predicate = function (mesh) {
  12634. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPointerTriggers;
  12635. };
  12636. }
  12637. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  12638. if (pickResult.hit && pickResult.pickedMesh) {
  12639. if (pickResult.pickedMesh.actionManager) {
  12640. _this._pickedDownMesh = pickResult.pickedMesh;
  12641. if (pickResult.pickedMesh.actionManager.hasPickTriggers) {
  12642. switch (evt.button) {
  12643. case 0:
  12644. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12645. break;
  12646. case 1:
  12647. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12648. break;
  12649. case 2:
  12650. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12651. break;
  12652. }
  12653. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12654. }
  12655. if (pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  12656. var that = _this;
  12657. window.setTimeout(function () {
  12658. var pickResult = that.pick(that._pointerX, that._pointerY, function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger); }, false, that.cameraToUseForPointers);
  12659. if (pickResult.hit && pickResult.pickedMesh) {
  12660. if (pickResult.pickedMesh.actionManager) {
  12661. if (that._startingPointerTime !== 0 && ((new Date().getTime() - that._startingPointerTime) > BABYLON.ActionManager.LongPressDelay) && (Math.abs(that._startingPointerPosition.x - that._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(that._startingPointerPosition.y - that._pointerY) < BABYLON.ActionManager.DragMovementThreshold)) {
  12662. that._startingPointerTime = 0;
  12663. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12664. }
  12665. }
  12666. }
  12667. }, BABYLON.ActionManager.LongPressDelay);
  12668. }
  12669. }
  12670. }
  12671. if (_this.onPointerDown) {
  12672. _this.onPointerDown(evt, pickResult);
  12673. }
  12674. // Sprites
  12675. _this._pickedDownSprite = null;
  12676. if (_this.spriteManagers.length > 0) {
  12677. pickResult = _this.pickSprite(_this._pointerX, _this._pointerY, spritePredicate, false, _this.cameraToUseForPointers);
  12678. if (pickResult.hit && pickResult.pickedSprite) {
  12679. if (pickResult.pickedSprite.actionManager) {
  12680. _this._pickedDownSprite = pickResult.pickedSprite;
  12681. switch (evt.button) {
  12682. case 0:
  12683. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12684. break;
  12685. case 1:
  12686. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12687. break;
  12688. case 2:
  12689. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12690. break;
  12691. }
  12692. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12693. }
  12694. }
  12695. }
  12696. };
  12697. this._onPointerUp = function (evt) {
  12698. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  12699. return;
  12700. }
  12701. var predicate = null;
  12702. _this._updatePointerPosition(evt);
  12703. if (!_this.onPointerUp && !_this.onPointerPick) {
  12704. predicate = function (mesh) {
  12705. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && (mesh.actionManager.hasPickTriggers || mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger));
  12706. };
  12707. }
  12708. // Meshes
  12709. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  12710. if (pickResult.hit && pickResult.pickedMesh) {
  12711. if (_this.onPointerPick && _this._pickedDownMesh != null && pickResult.pickedMesh == _this._pickedDownMesh) {
  12712. _this.onPointerPick(evt, pickResult);
  12713. }
  12714. if (pickResult.pickedMesh.actionManager) {
  12715. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12716. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  12717. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12718. }
  12719. }
  12720. }
  12721. if (_this._pickedDownMesh && _this._pickedDownMesh !== pickResult.pickedMesh) {
  12722. _this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(_this._pickedDownMesh, evt));
  12723. }
  12724. if (_this.onPointerUp) {
  12725. _this.onPointerUp(evt, pickResult);
  12726. }
  12727. _this._startingPointerTime = 0;
  12728. // Sprites
  12729. if (_this.spriteManagers.length > 0) {
  12730. pickResult = _this.pickSprite(_this._pointerX, _this._pointerY, spritePredicate, false, _this.cameraToUseForPointers);
  12731. if (pickResult.hit && pickResult.pickedSprite) {
  12732. if (pickResult.pickedSprite.actionManager) {
  12733. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12734. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  12735. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12736. }
  12737. }
  12738. }
  12739. if (_this._pickedDownSprite && _this._pickedDownSprite !== pickResult.pickedSprite) {
  12740. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  12741. }
  12742. }
  12743. };
  12744. this._onKeyDown = function (evt) {
  12745. if (_this.actionManager) {
  12746. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  12747. }
  12748. };
  12749. this._onKeyUp = function (evt) {
  12750. if (_this.actionManager) {
  12751. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  12752. }
  12753. };
  12754. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12755. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  12756. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  12757. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
  12758. // Wheel
  12759. this._engine.getRenderingCanvas().addEventListener('mousewheel', this._onPointerMove, false);
  12760. this._engine.getRenderingCanvas().addEventListener('DOMMouseScroll', this._onPointerMove, false);
  12761. BABYLON.Tools.RegisterTopRootEvents([
  12762. { name: "keydown", handler: this._onKeyDown },
  12763. { name: "keyup", handler: this._onKeyUp }
  12764. ]);
  12765. };
  12766. Scene.prototype.detachControl = function () {
  12767. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12768. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  12769. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  12770. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
  12771. // Wheel
  12772. this._engine.getRenderingCanvas().removeEventListener('mousewheel', this._onPointerMove);
  12773. this._engine.getRenderingCanvas().removeEventListener('DOMMouseScroll', this._onPointerMove);
  12774. BABYLON.Tools.UnregisterTopRootEvents([
  12775. { name: "keydown", handler: this._onKeyDown },
  12776. { name: "keyup", handler: this._onKeyUp }
  12777. ]);
  12778. };
  12779. // Ready
  12780. Scene.prototype.isReady = function () {
  12781. if (this._pendingData.length > 0) {
  12782. return false;
  12783. }
  12784. var index;
  12785. for (index = 0; index < this._geometries.length; index++) {
  12786. var geometry = this._geometries[index];
  12787. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  12788. return false;
  12789. }
  12790. }
  12791. for (index = 0; index < this.meshes.length; index++) {
  12792. var mesh = this.meshes[index];
  12793. if (!mesh.isReady()) {
  12794. return false;
  12795. }
  12796. var mat = mesh.material;
  12797. if (mat) {
  12798. if (!mat.isReady(mesh)) {
  12799. return false;
  12800. }
  12801. }
  12802. }
  12803. return true;
  12804. };
  12805. Scene.prototype.resetCachedMaterial = function () {
  12806. this._cachedMaterial = null;
  12807. };
  12808. Scene.prototype.registerBeforeRender = function (func) {
  12809. this._onBeforeRenderCallbacks.push(func);
  12810. };
  12811. Scene.prototype.unregisterBeforeRender = function (func) {
  12812. var index = this._onBeforeRenderCallbacks.indexOf(func);
  12813. if (index > -1) {
  12814. this._onBeforeRenderCallbacks.splice(index, 1);
  12815. }
  12816. };
  12817. Scene.prototype.registerAfterRender = function (func) {
  12818. this._onAfterRenderCallbacks.push(func);
  12819. };
  12820. Scene.prototype.unregisterAfterRender = function (func) {
  12821. var index = this._onAfterRenderCallbacks.indexOf(func);
  12822. if (index > -1) {
  12823. this._onAfterRenderCallbacks.splice(index, 1);
  12824. }
  12825. };
  12826. Scene.prototype._addPendingData = function (data) {
  12827. this._pendingData.push(data);
  12828. };
  12829. Scene.prototype._removePendingData = function (data) {
  12830. var index = this._pendingData.indexOf(data);
  12831. if (index !== -1) {
  12832. this._pendingData.splice(index, 1);
  12833. }
  12834. };
  12835. Scene.prototype.getWaitingItemsCount = function () {
  12836. return this._pendingData.length;
  12837. };
  12838. /**
  12839. * Registers a function to be executed when the scene is ready.
  12840. * @param {Function} func - the function to be executed.
  12841. */
  12842. Scene.prototype.executeWhenReady = function (func) {
  12843. var _this = this;
  12844. this._onReadyCallbacks.push(func);
  12845. if (this._executeWhenReadyTimeoutId !== -1) {
  12846. return;
  12847. }
  12848. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12849. _this._checkIsReady();
  12850. }, 150);
  12851. };
  12852. Scene.prototype._checkIsReady = function () {
  12853. var _this = this;
  12854. if (this.isReady()) {
  12855. this._onReadyCallbacks.forEach(function (func) {
  12856. func();
  12857. });
  12858. this._onReadyCallbacks = [];
  12859. this._executeWhenReadyTimeoutId = -1;
  12860. return;
  12861. }
  12862. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12863. _this._checkIsReady();
  12864. }, 150);
  12865. };
  12866. // Animations
  12867. /**
  12868. * Will start the animation sequence of a given target
  12869. * @param target - the target
  12870. * @param {number} from - from which frame should animation start
  12871. * @param {number} to - till which frame should animation run.
  12872. * @param {boolean} [loop] - should the animation loop
  12873. * @param {number} [speedRatio] - the speed in which to run the animation
  12874. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  12875. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  12876. * @return {BABYLON.Animatable} the animatable object created for this animation
  12877. * @see BABYLON.Animatable
  12878. * @see http://doc.babylonjs.com/page.php?p=22081
  12879. */
  12880. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  12881. if (speedRatio === void 0) { speedRatio = 1.0; }
  12882. this.stopAnimation(target);
  12883. if (!animatable) {
  12884. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  12885. }
  12886. // Local animations
  12887. if (target.animations) {
  12888. animatable.appendAnimations(target, target.animations);
  12889. }
  12890. // Children animations
  12891. if (target.getAnimatables) {
  12892. var animatables = target.getAnimatables();
  12893. for (var index = 0; index < animatables.length; index++) {
  12894. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  12895. }
  12896. }
  12897. return animatable;
  12898. };
  12899. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  12900. if (speedRatio === undefined) {
  12901. speedRatio = 1.0;
  12902. }
  12903. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  12904. return animatable;
  12905. };
  12906. Scene.prototype.getAnimatableByTarget = function (target) {
  12907. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12908. if (this._activeAnimatables[index].target === target) {
  12909. return this._activeAnimatables[index];
  12910. }
  12911. }
  12912. return null;
  12913. };
  12914. Object.defineProperty(Scene.prototype, "Animatables", {
  12915. get: function () {
  12916. return this._activeAnimatables;
  12917. },
  12918. enumerable: true,
  12919. configurable: true
  12920. });
  12921. /**
  12922. * Will stop the animation of the given target
  12923. * @param target - the target
  12924. * @see beginAnimation
  12925. */
  12926. Scene.prototype.stopAnimation = function (target) {
  12927. var animatable = this.getAnimatableByTarget(target);
  12928. if (animatable) {
  12929. animatable.stop();
  12930. }
  12931. };
  12932. Scene.prototype._animate = function () {
  12933. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  12934. return;
  12935. }
  12936. if (!this._animationStartDate) {
  12937. if (this._pendingData.length > 0) {
  12938. return;
  12939. }
  12940. this._animationStartDate = BABYLON.Tools.Now;
  12941. }
  12942. // Getting time
  12943. var now = BABYLON.Tools.Now;
  12944. var delay = now - this._animationStartDate;
  12945. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12946. this._activeAnimatables[index]._animate(delay);
  12947. }
  12948. };
  12949. // Matrix
  12950. Scene.prototype.getViewMatrix = function () {
  12951. return this._viewMatrix;
  12952. };
  12953. Scene.prototype.getProjectionMatrix = function () {
  12954. return this._projectionMatrix;
  12955. };
  12956. Scene.prototype.getTransformMatrix = function () {
  12957. return this._transformMatrix;
  12958. };
  12959. Scene.prototype.setTransformMatrix = function (view, projection) {
  12960. this._viewMatrix = view;
  12961. this._projectionMatrix = projection;
  12962. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  12963. };
  12964. // Methods
  12965. Scene.prototype.addMesh = function (newMesh) {
  12966. newMesh.uniqueId = this._uniqueIdCounter++;
  12967. var position = this.meshes.push(newMesh);
  12968. //notify the collision coordinator
  12969. this.collisionCoordinator.onMeshAdded(newMesh);
  12970. if (this.onNewMeshAdded) {
  12971. this.onNewMeshAdded(newMesh, position, this);
  12972. }
  12973. };
  12974. Scene.prototype.removeMesh = function (toRemove) {
  12975. var index = this.meshes.indexOf(toRemove);
  12976. if (index !== -1) {
  12977. // Remove from the scene if mesh found
  12978. this.meshes.splice(index, 1);
  12979. }
  12980. //notify the collision coordinator
  12981. this.collisionCoordinator.onMeshRemoved(toRemove);
  12982. if (this.onMeshRemoved) {
  12983. this.onMeshRemoved(toRemove);
  12984. }
  12985. return index;
  12986. };
  12987. Scene.prototype.removeSkeleton = function (toRemove) {
  12988. var index = this.skeletons.indexOf(toRemove);
  12989. if (index !== -1) {
  12990. // Remove from the scene if mesh found
  12991. this.skeletons.splice(index, 1);
  12992. }
  12993. return index;
  12994. };
  12995. Scene.prototype.removeLight = function (toRemove) {
  12996. var index = this.lights.indexOf(toRemove);
  12997. if (index !== -1) {
  12998. // Remove from the scene if mesh found
  12999. this.lights.splice(index, 1);
  13000. }
  13001. if (this.onLightRemoved) {
  13002. this.onLightRemoved(toRemove);
  13003. }
  13004. return index;
  13005. };
  13006. Scene.prototype.removeCamera = function (toRemove) {
  13007. var index = this.cameras.indexOf(toRemove);
  13008. if (index !== -1) {
  13009. // Remove from the scene if mesh found
  13010. this.cameras.splice(index, 1);
  13011. }
  13012. // Remove from activeCameras
  13013. var index2 = this.activeCameras.indexOf(toRemove);
  13014. if (index2 !== -1) {
  13015. // Remove from the scene if mesh found
  13016. this.activeCameras.splice(index2, 1);
  13017. }
  13018. // Reset the activeCamera
  13019. if (this.activeCamera === toRemove) {
  13020. if (this.cameras.length > 0) {
  13021. this.activeCamera = this.cameras[0];
  13022. }
  13023. else {
  13024. this.activeCamera = null;
  13025. }
  13026. }
  13027. if (this.onCameraRemoved) {
  13028. this.onCameraRemoved(toRemove);
  13029. }
  13030. return index;
  13031. };
  13032. Scene.prototype.addLight = function (newLight) {
  13033. newLight.uniqueId = this._uniqueIdCounter++;
  13034. var position = this.lights.push(newLight);
  13035. if (this.onNewLightAdded) {
  13036. this.onNewLightAdded(newLight, position, this);
  13037. }
  13038. };
  13039. Scene.prototype.addCamera = function (newCamera) {
  13040. newCamera.uniqueId = this._uniqueIdCounter++;
  13041. var position = this.cameras.push(newCamera);
  13042. if (this.onNewCameraAdded) {
  13043. this.onNewCameraAdded(newCamera, position, this);
  13044. }
  13045. };
  13046. /**
  13047. * Switch active camera
  13048. * @param {Camera} newCamera - new active camera
  13049. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  13050. */
  13051. Scene.prototype.swithActiveCamera = function (newCamera, attachControl) {
  13052. if (attachControl === void 0) { attachControl = true; }
  13053. var canvas = this._engine.getRenderingCanvas();
  13054. this.activeCamera.detachControl(canvas);
  13055. this.activeCamera = newCamera;
  13056. if (attachControl) {
  13057. newCamera.attachControl(canvas);
  13058. }
  13059. };
  13060. /**
  13061. * sets the active camera of the scene using its ID
  13062. * @param {string} id - the camera's ID
  13063. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  13064. * @see activeCamera
  13065. */
  13066. Scene.prototype.setActiveCameraByID = function (id) {
  13067. var camera = this.getCameraByID(id);
  13068. if (camera) {
  13069. this.activeCamera = camera;
  13070. return camera;
  13071. }
  13072. return null;
  13073. };
  13074. /**
  13075. * sets the active camera of the scene using its name
  13076. * @param {string} name - the camera's name
  13077. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  13078. * @see activeCamera
  13079. */
  13080. Scene.prototype.setActiveCameraByName = function (name) {
  13081. var camera = this.getCameraByName(name);
  13082. if (camera) {
  13083. this.activeCamera = camera;
  13084. return camera;
  13085. }
  13086. return null;
  13087. };
  13088. /**
  13089. * get a material using its id
  13090. * @param {string} the material's ID
  13091. * @return {BABYLON.Material|null} the material or null if none found.
  13092. */
  13093. Scene.prototype.getMaterialByID = function (id) {
  13094. for (var index = 0; index < this.materials.length; index++) {
  13095. if (this.materials[index].id === id) {
  13096. return this.materials[index];
  13097. }
  13098. }
  13099. return null;
  13100. };
  13101. /**
  13102. * get a material using its name
  13103. * @param {string} the material's name
  13104. * @return {BABYLON.Material|null} the material or null if none found.
  13105. */
  13106. Scene.prototype.getMaterialByName = function (name) {
  13107. for (var index = 0; index < this.materials.length; index++) {
  13108. if (this.materials[index].name === name) {
  13109. return this.materials[index];
  13110. }
  13111. }
  13112. return null;
  13113. };
  13114. Scene.prototype.getLensFlareSystemByName = function (name) {
  13115. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  13116. if (this.lensFlareSystems[index].name === name) {
  13117. return this.lensFlareSystems[index];
  13118. }
  13119. }
  13120. return null;
  13121. };
  13122. Scene.prototype.getCameraByID = function (id) {
  13123. for (var index = 0; index < this.cameras.length; index++) {
  13124. if (this.cameras[index].id === id) {
  13125. return this.cameras[index];
  13126. }
  13127. }
  13128. return null;
  13129. };
  13130. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  13131. for (var index = 0; index < this.cameras.length; index++) {
  13132. if (this.cameras[index].uniqueId === uniqueId) {
  13133. return this.cameras[index];
  13134. }
  13135. }
  13136. return null;
  13137. };
  13138. /**
  13139. * get a camera using its name
  13140. * @param {string} the camera's name
  13141. * @return {BABYLON.Camera|null} the camera or null if none found.
  13142. */
  13143. Scene.prototype.getCameraByName = function (name) {
  13144. for (var index = 0; index < this.cameras.length; index++) {
  13145. if (this.cameras[index].name === name) {
  13146. return this.cameras[index];
  13147. }
  13148. }
  13149. return null;
  13150. };
  13151. /**
  13152. * get a bone using its id
  13153. * @param {string} the bone's id
  13154. * @return {BABYLON.Bone|null} the bone or null if not found
  13155. */
  13156. Scene.prototype.getBoneByID = function (id) {
  13157. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  13158. var skeleton = this.skeletons[skeletonIndex];
  13159. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  13160. if (skeleton.bones[boneIndex].id === id) {
  13161. return skeleton.bones[boneIndex];
  13162. }
  13163. }
  13164. }
  13165. return null;
  13166. };
  13167. /**
  13168. * get a bone using its id
  13169. * @param {string} the bone's name
  13170. * @return {BABYLON.Bone|null} the bone or null if not found
  13171. */
  13172. Scene.prototype.getBoneByName = function (name) {
  13173. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  13174. var skeleton = this.skeletons[skeletonIndex];
  13175. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  13176. if (skeleton.bones[boneIndex].name === name) {
  13177. return skeleton.bones[boneIndex];
  13178. }
  13179. }
  13180. }
  13181. return null;
  13182. };
  13183. /**
  13184. * get a light node using its name
  13185. * @param {string} the light's name
  13186. * @return {BABYLON.Light|null} the light or null if none found.
  13187. */
  13188. Scene.prototype.getLightByName = function (name) {
  13189. for (var index = 0; index < this.lights.length; index++) {
  13190. if (this.lights[index].name === name) {
  13191. return this.lights[index];
  13192. }
  13193. }
  13194. return null;
  13195. };
  13196. /**
  13197. * get a light node using its ID
  13198. * @param {string} the light's id
  13199. * @return {BABYLON.Light|null} the light or null if none found.
  13200. */
  13201. Scene.prototype.getLightByID = function (id) {
  13202. for (var index = 0; index < this.lights.length; index++) {
  13203. if (this.lights[index].id === id) {
  13204. return this.lights[index];
  13205. }
  13206. }
  13207. return null;
  13208. };
  13209. /**
  13210. * get a light node using its scene-generated unique ID
  13211. * @param {number} the light's unique id
  13212. * @return {BABYLON.Light|null} the light or null if none found.
  13213. */
  13214. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  13215. for (var index = 0; index < this.lights.length; index++) {
  13216. if (this.lights[index].uniqueId === uniqueId) {
  13217. return this.lights[index];
  13218. }
  13219. }
  13220. return null;
  13221. };
  13222. /**
  13223. * get a particle system by id
  13224. * @param id {number} the particle system id
  13225. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  13226. */
  13227. Scene.prototype.getParticleSystemByID = function (id) {
  13228. for (var index = 0; index < this.particleSystems.length; index++) {
  13229. if (this.particleSystems[index].id === id) {
  13230. return this.particleSystems[index];
  13231. }
  13232. }
  13233. return null;
  13234. };
  13235. /**
  13236. * get a geometry using its ID
  13237. * @param {string} the geometry's id
  13238. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  13239. */
  13240. Scene.prototype.getGeometryByID = function (id) {
  13241. for (var index = 0; index < this._geometries.length; index++) {
  13242. if (this._geometries[index].id === id) {
  13243. return this._geometries[index];
  13244. }
  13245. }
  13246. return null;
  13247. };
  13248. /**
  13249. * add a new geometry to this scene.
  13250. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  13251. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  13252. * @return {boolean} was the geometry added or not
  13253. */
  13254. Scene.prototype.pushGeometry = function (geometry, force) {
  13255. if (!force && this.getGeometryByID(geometry.id)) {
  13256. return false;
  13257. }
  13258. this._geometries.push(geometry);
  13259. //notify the collision coordinator
  13260. this.collisionCoordinator.onGeometryAdded(geometry);
  13261. if (this.onGeometryAdded) {
  13262. this.onGeometryAdded(geometry);
  13263. }
  13264. return true;
  13265. };
  13266. /**
  13267. * Removes an existing geometry
  13268. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  13269. * @return {boolean} was the geometry removed or not
  13270. */
  13271. Scene.prototype.removeGeometry = function (geometry) {
  13272. var index = this._geometries.indexOf(geometry);
  13273. if (index > -1) {
  13274. this._geometries.splice(index, 1);
  13275. //notify the collision coordinator
  13276. this.collisionCoordinator.onGeometryDeleted(geometry);
  13277. if (this.onGeometryRemoved) {
  13278. this.onGeometryRemoved(geometry);
  13279. }
  13280. return true;
  13281. }
  13282. return false;
  13283. };
  13284. Scene.prototype.getGeometries = function () {
  13285. return this._geometries;
  13286. };
  13287. /**
  13288. * Get the first added mesh found of a given ID
  13289. * @param {string} id - the id to search for
  13290. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  13291. */
  13292. Scene.prototype.getMeshByID = function (id) {
  13293. for (var index = 0; index < this.meshes.length; index++) {
  13294. if (this.meshes[index].id === id) {
  13295. return this.meshes[index];
  13296. }
  13297. }
  13298. return null;
  13299. };
  13300. /**
  13301. * Get a mesh with its auto-generated unique id
  13302. * @param {number} uniqueId - the unique id to search for
  13303. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  13304. */
  13305. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  13306. for (var index = 0; index < this.meshes.length; index++) {
  13307. if (this.meshes[index].uniqueId === uniqueId) {
  13308. return this.meshes[index];
  13309. }
  13310. }
  13311. return null;
  13312. };
  13313. /**
  13314. * Get a the last added mesh found of a given ID
  13315. * @param {string} id - the id to search for
  13316. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  13317. */
  13318. Scene.prototype.getLastMeshByID = function (id) {
  13319. for (var index = this.meshes.length - 1; index >= 0; index--) {
  13320. if (this.meshes[index].id === id) {
  13321. return this.meshes[index];
  13322. }
  13323. }
  13324. return null;
  13325. };
  13326. /**
  13327. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  13328. * @param {string} id - the id to search for
  13329. * @return {BABYLON.Node|null} the node found or null if not found at all.
  13330. */
  13331. Scene.prototype.getLastEntryByID = function (id) {
  13332. var index;
  13333. for (index = this.meshes.length - 1; index >= 0; index--) {
  13334. if (this.meshes[index].id === id) {
  13335. return this.meshes[index];
  13336. }
  13337. }
  13338. for (index = this.cameras.length - 1; index >= 0; index--) {
  13339. if (this.cameras[index].id === id) {
  13340. return this.cameras[index];
  13341. }
  13342. }
  13343. for (index = this.lights.length - 1; index >= 0; index--) {
  13344. if (this.lights[index].id === id) {
  13345. return this.lights[index];
  13346. }
  13347. }
  13348. return null;
  13349. };
  13350. Scene.prototype.getNodeByID = function (id) {
  13351. var mesh = this.getMeshByID(id);
  13352. if (mesh) {
  13353. return mesh;
  13354. }
  13355. var light = this.getLightByID(id);
  13356. if (light) {
  13357. return light;
  13358. }
  13359. var camera = this.getCameraByID(id);
  13360. if (camera) {
  13361. return camera;
  13362. }
  13363. var bone = this.getBoneByID(id);
  13364. return bone;
  13365. };
  13366. Scene.prototype.getNodeByName = function (name) {
  13367. var mesh = this.getMeshByName(name);
  13368. if (mesh) {
  13369. return mesh;
  13370. }
  13371. var light = this.getLightByName(name);
  13372. if (light) {
  13373. return light;
  13374. }
  13375. var camera = this.getCameraByName(name);
  13376. if (camera) {
  13377. return camera;
  13378. }
  13379. var bone = this.getBoneByName(name);
  13380. return bone;
  13381. };
  13382. Scene.prototype.getMeshByName = function (name) {
  13383. for (var index = 0; index < this.meshes.length; index++) {
  13384. if (this.meshes[index].name === name) {
  13385. return this.meshes[index];
  13386. }
  13387. }
  13388. return null;
  13389. };
  13390. Scene.prototype.getSoundByName = function (name) {
  13391. var index;
  13392. if (BABYLON.AudioEngine) {
  13393. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  13394. if (this.mainSoundTrack.soundCollection[index].name === name) {
  13395. return this.mainSoundTrack.soundCollection[index];
  13396. }
  13397. }
  13398. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  13399. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  13400. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  13401. return this.soundTracks[sdIndex].soundCollection[index];
  13402. }
  13403. }
  13404. }
  13405. }
  13406. return null;
  13407. };
  13408. Scene.prototype.getLastSkeletonByID = function (id) {
  13409. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  13410. if (this.skeletons[index].id === id) {
  13411. return this.skeletons[index];
  13412. }
  13413. }
  13414. return null;
  13415. };
  13416. Scene.prototype.getSkeletonById = function (id) {
  13417. for (var index = 0; index < this.skeletons.length; index++) {
  13418. if (this.skeletons[index].id === id) {
  13419. return this.skeletons[index];
  13420. }
  13421. }
  13422. return null;
  13423. };
  13424. Scene.prototype.getSkeletonByName = function (name) {
  13425. for (var index = 0; index < this.skeletons.length; index++) {
  13426. if (this.skeletons[index].name === name) {
  13427. return this.skeletons[index];
  13428. }
  13429. }
  13430. return null;
  13431. };
  13432. Scene.prototype.isActiveMesh = function (mesh) {
  13433. return (this._activeMeshes.indexOf(mesh) !== -1);
  13434. };
  13435. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  13436. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  13437. var material = subMesh.getMaterial();
  13438. if (mesh.showSubMeshesBoundingBox) {
  13439. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  13440. }
  13441. if (material) {
  13442. // Render targets
  13443. if (material.getRenderTargetTextures) {
  13444. if (this._processedMaterials.indexOf(material) === -1) {
  13445. this._processedMaterials.push(material);
  13446. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  13447. }
  13448. }
  13449. // Dispatch
  13450. this._activeIndices += subMesh.indexCount;
  13451. this._renderingManager.dispatch(subMesh);
  13452. }
  13453. }
  13454. };
  13455. Scene.prototype._evaluateActiveMeshes = function () {
  13456. this.activeCamera._activeMeshes.reset();
  13457. this._activeMeshes.reset();
  13458. this._renderingManager.reset();
  13459. this._processedMaterials.reset();
  13460. this._activeParticleSystems.reset();
  13461. this._activeSkeletons.reset();
  13462. this._softwareSkinnedMeshes.reset();
  13463. this._boundingBoxRenderer.reset();
  13464. this._edgesRenderers.reset();
  13465. if (!this._frustumPlanes) {
  13466. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  13467. }
  13468. else {
  13469. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  13470. }
  13471. // Meshes
  13472. var meshes;
  13473. var len;
  13474. if (this._selectionOctree) {
  13475. var selection = this._selectionOctree.select(this._frustumPlanes);
  13476. meshes = selection.data;
  13477. len = selection.length;
  13478. }
  13479. else {
  13480. len = this.meshes.length;
  13481. meshes = this.meshes;
  13482. }
  13483. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  13484. var mesh = meshes[meshIndex];
  13485. if (mesh.isBlocked) {
  13486. continue;
  13487. }
  13488. this._totalVertices += mesh.getTotalVertices();
  13489. if (!mesh.isReady() || !mesh.isEnabled()) {
  13490. continue;
  13491. }
  13492. mesh.computeWorldMatrix();
  13493. // Intersections
  13494. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  13495. this._meshesForIntersections.pushNoDuplicate(mesh);
  13496. }
  13497. // Switch to current LOD
  13498. var meshLOD = mesh.getLOD(this.activeCamera);
  13499. if (!meshLOD) {
  13500. continue;
  13501. }
  13502. mesh._preActivate();
  13503. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  13504. this._activeMeshes.push(mesh);
  13505. this.activeCamera._activeMeshes.push(mesh);
  13506. mesh._activate(this._renderId);
  13507. this._activeMesh(meshLOD);
  13508. }
  13509. }
  13510. // Particle systems
  13511. var beforeParticlesDate = BABYLON.Tools.Now;
  13512. if (this.particlesEnabled) {
  13513. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  13514. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  13515. var particleSystem = this.particleSystems[particleIndex];
  13516. if (!particleSystem.isStarted()) {
  13517. continue;
  13518. }
  13519. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  13520. this._activeParticleSystems.push(particleSystem);
  13521. particleSystem.animate();
  13522. }
  13523. }
  13524. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  13525. }
  13526. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  13527. };
  13528. Scene.prototype._activeMesh = function (mesh) {
  13529. if (mesh.skeleton && this.skeletonsEnabled) {
  13530. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  13531. if (!mesh.computeBonesUsingShaders) {
  13532. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  13533. }
  13534. }
  13535. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  13536. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  13537. }
  13538. if (mesh._edgesRenderer) {
  13539. this._edgesRenderers.push(mesh._edgesRenderer);
  13540. }
  13541. if (mesh && mesh.subMeshes) {
  13542. // Submeshes Octrees
  13543. var len;
  13544. var subMeshes;
  13545. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  13546. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  13547. len = intersections.length;
  13548. subMeshes = intersections.data;
  13549. }
  13550. else {
  13551. subMeshes = mesh.subMeshes;
  13552. len = subMeshes.length;
  13553. }
  13554. for (var subIndex = 0; subIndex < len; subIndex++) {
  13555. var subMesh = subMeshes[subIndex];
  13556. this._evaluateSubMesh(subMesh, mesh);
  13557. }
  13558. }
  13559. };
  13560. Scene.prototype.updateTransformMatrix = function (force) {
  13561. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  13562. };
  13563. Scene.prototype._renderForCamera = function (camera) {
  13564. var engine = this._engine;
  13565. this.activeCamera = camera;
  13566. if (!this.activeCamera)
  13567. throw new Error("Active camera not set");
  13568. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13569. // Viewport
  13570. engine.setViewport(this.activeCamera.viewport);
  13571. // Camera
  13572. this.resetCachedMaterial();
  13573. this._renderId++;
  13574. this.updateTransformMatrix();
  13575. if (this.beforeCameraRender) {
  13576. this.beforeCameraRender(this.activeCamera);
  13577. }
  13578. // Meshes
  13579. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  13580. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  13581. this._evaluateActiveMeshes();
  13582. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  13583. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  13584. // Skeletons
  13585. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  13586. var skeleton = this._activeSkeletons.data[skeletonIndex];
  13587. skeleton.prepare();
  13588. }
  13589. // Software skinning
  13590. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  13591. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  13592. mesh.applySkeleton(mesh.skeleton);
  13593. }
  13594. // Render targets
  13595. var beforeRenderTargetDate = BABYLON.Tools.Now;
  13596. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  13597. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13598. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  13599. var renderTarget = this._renderTargets.data[renderIndex];
  13600. if (renderTarget._shouldRender()) {
  13601. this._renderId++;
  13602. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  13603. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  13604. }
  13605. }
  13606. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13607. this._renderId++;
  13608. engine.restoreDefaultFramebuffer(); // Restore back buffer
  13609. }
  13610. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  13611. // Prepare Frame
  13612. this.postProcessManager._prepareFrame();
  13613. var beforeRenderDate = BABYLON.Tools.Now;
  13614. // Backgrounds
  13615. var layerIndex;
  13616. var layer;
  13617. if (this.layers.length) {
  13618. engine.setDepthBuffer(false);
  13619. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13620. layer = this.layers[layerIndex];
  13621. if (layer.isBackground) {
  13622. layer.render();
  13623. }
  13624. }
  13625. engine.setDepthBuffer(true);
  13626. }
  13627. // Render
  13628. BABYLON.Tools.StartPerformanceCounter("Main render");
  13629. this._renderingManager.render(null, null, true, true);
  13630. BABYLON.Tools.EndPerformanceCounter("Main render");
  13631. // Bounding boxes
  13632. this._boundingBoxRenderer.render();
  13633. // Edges
  13634. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  13635. this._edgesRenderers.data[edgesRendererIndex].render();
  13636. }
  13637. // Lens flares
  13638. if (this.lensFlaresEnabled) {
  13639. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13640. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  13641. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  13642. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  13643. lensFlareSystem.render();
  13644. }
  13645. }
  13646. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13647. }
  13648. // Foregrounds
  13649. if (this.layers.length) {
  13650. engine.setDepthBuffer(false);
  13651. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13652. layer = this.layers[layerIndex];
  13653. if (!layer.isBackground) {
  13654. layer.render();
  13655. }
  13656. }
  13657. engine.setDepthBuffer(true);
  13658. }
  13659. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  13660. // Finalize frame
  13661. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  13662. // Update camera
  13663. this.activeCamera._updateFromScene();
  13664. // Reset some special arrays
  13665. this._renderTargets.reset();
  13666. if (this.afterCameraRender) {
  13667. this.afterCameraRender(this.activeCamera);
  13668. }
  13669. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13670. };
  13671. Scene.prototype._processSubCameras = function (camera) {
  13672. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  13673. this._renderForCamera(camera);
  13674. return;
  13675. }
  13676. // rig cameras
  13677. for (var index = 0; index < camera._rigCameras.length; index++) {
  13678. this._renderForCamera(camera._rigCameras[index]);
  13679. }
  13680. this.activeCamera = camera;
  13681. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  13682. // Update camera
  13683. this.activeCamera._updateFromScene();
  13684. };
  13685. Scene.prototype._checkIntersections = function () {
  13686. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  13687. var sourceMesh = this._meshesForIntersections.data[index];
  13688. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  13689. var action = sourceMesh.actionManager.actions[actionIndex];
  13690. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13691. var parameters = action.getTriggerParameter();
  13692. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  13693. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  13694. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  13695. if (areIntersecting && currentIntersectionInProgress === -1) {
  13696. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  13697. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  13698. sourceMesh._intersectionsInProgress.push(otherMesh);
  13699. }
  13700. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13701. sourceMesh._intersectionsInProgress.push(otherMesh);
  13702. }
  13703. }
  13704. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  13705. //They intersected, and now they don't.
  13706. //is this trigger an exit trigger? execute an event.
  13707. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13708. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  13709. }
  13710. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  13711. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13712. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  13713. }
  13714. }
  13715. }
  13716. }
  13717. }
  13718. };
  13719. Scene.prototype.render = function () {
  13720. var startDate = BABYLON.Tools.Now;
  13721. this._particlesDuration = 0;
  13722. this._spritesDuration = 0;
  13723. this._activeParticles = 0;
  13724. this._renderDuration = 0;
  13725. this._renderTargetsDuration = 0;
  13726. this._evaluateActiveMeshesDuration = 0;
  13727. this._totalVertices = 0;
  13728. this._activeIndices = 0;
  13729. this._activeBones = 0;
  13730. this.getEngine().resetDrawCalls();
  13731. this._meshesForIntersections.reset();
  13732. this.resetCachedMaterial();
  13733. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  13734. // Actions
  13735. if (this.actionManager) {
  13736. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  13737. }
  13738. //Simplification Queue
  13739. if (this.simplificationQueue && !this.simplificationQueue.running) {
  13740. this.simplificationQueue.executeNext();
  13741. }
  13742. // Animations
  13743. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  13744. this._animationRatio = deltaTime * (60.0 / 1000.0);
  13745. this._animate();
  13746. // Physics
  13747. if (this._physicsEngine) {
  13748. BABYLON.Tools.StartPerformanceCounter("Physics");
  13749. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  13750. BABYLON.Tools.EndPerformanceCounter("Physics");
  13751. }
  13752. // Before render
  13753. if (this.beforeRender) {
  13754. this.beforeRender();
  13755. }
  13756. var callbackIndex;
  13757. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  13758. this._onBeforeRenderCallbacks[callbackIndex]();
  13759. }
  13760. // Customs render targets
  13761. var beforeRenderTargetDate = BABYLON.Tools.Now;
  13762. var engine = this.getEngine();
  13763. var currentActiveCamera = this.activeCamera;
  13764. if (this.renderTargetsEnabled) {
  13765. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  13766. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  13767. var renderTarget = this.customRenderTargets[customIndex];
  13768. if (renderTarget._shouldRender()) {
  13769. this._renderId++;
  13770. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  13771. if (!this.activeCamera)
  13772. throw new Error("Active camera not set");
  13773. // Viewport
  13774. engine.setViewport(this.activeCamera.viewport);
  13775. // Camera
  13776. this.updateTransformMatrix();
  13777. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  13778. }
  13779. }
  13780. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  13781. this._renderId++;
  13782. }
  13783. if (this.customRenderTargets.length > 0) {
  13784. engine.restoreDefaultFramebuffer();
  13785. }
  13786. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  13787. this.activeCamera = currentActiveCamera;
  13788. // Procedural textures
  13789. if (this.proceduralTexturesEnabled) {
  13790. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  13791. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  13792. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  13793. if (proceduralTexture._shouldRender()) {
  13794. proceduralTexture.render();
  13795. }
  13796. }
  13797. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  13798. }
  13799. // Clear
  13800. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  13801. // Shadows
  13802. if (this.shadowsEnabled) {
  13803. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  13804. var light = this.lights[lightIndex];
  13805. var shadowGenerator = light.getShadowGenerator();
  13806. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  13807. this._renderTargets.push(shadowGenerator.getShadowMap());
  13808. }
  13809. }
  13810. }
  13811. // Depth renderer
  13812. if (this._depthRenderer) {
  13813. this._renderTargets.push(this._depthRenderer.getDepthMap());
  13814. }
  13815. // RenderPipeline
  13816. this.postProcessRenderPipelineManager.update();
  13817. // Multi-cameras?
  13818. if (this.activeCameras.length > 0) {
  13819. var currentRenderId = this._renderId;
  13820. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  13821. this._renderId = currentRenderId;
  13822. if (cameraIndex > 0) {
  13823. this._engine.clear(0, false, true);
  13824. }
  13825. this._processSubCameras(this.activeCameras[cameraIndex]);
  13826. }
  13827. }
  13828. else {
  13829. if (!this.activeCamera) {
  13830. throw new Error("No camera defined");
  13831. }
  13832. this._processSubCameras(this.activeCamera);
  13833. }
  13834. // Intersection checks
  13835. this._checkIntersections();
  13836. // Update the audio listener attached to the camera
  13837. if (BABYLON.AudioEngine) {
  13838. this._updateAudioParameters();
  13839. }
  13840. // After render
  13841. if (this.afterRender) {
  13842. this.afterRender();
  13843. }
  13844. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  13845. this._onAfterRenderCallbacks[callbackIndex]();
  13846. }
  13847. // Cleaning
  13848. for (var index = 0; index < this._toBeDisposed.length; index++) {
  13849. this._toBeDisposed.data[index].dispose();
  13850. this._toBeDisposed[index] = null;
  13851. }
  13852. this._toBeDisposed.reset();
  13853. if (this.dumpNextRenderTargets) {
  13854. this.dumpNextRenderTargets = false;
  13855. }
  13856. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  13857. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  13858. };
  13859. Scene.prototype._updateAudioParameters = function () {
  13860. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  13861. return;
  13862. }
  13863. var listeningCamera;
  13864. var audioEngine = BABYLON.Engine.audioEngine;
  13865. if (this.activeCameras.length > 0) {
  13866. listeningCamera = this.activeCameras[0];
  13867. }
  13868. else {
  13869. listeningCamera = this.activeCamera;
  13870. }
  13871. if (listeningCamera && audioEngine.canUseWebAudio) {
  13872. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  13873. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  13874. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  13875. cameraDirection.normalize();
  13876. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  13877. var i;
  13878. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13879. var sound = this.mainSoundTrack.soundCollection[i];
  13880. if (sound.useCustomAttenuation) {
  13881. sound.updateDistanceFromListener();
  13882. }
  13883. }
  13884. for (i = 0; i < this.soundTracks.length; i++) {
  13885. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13886. sound = this.soundTracks[i].soundCollection[j];
  13887. if (sound.useCustomAttenuation) {
  13888. sound.updateDistanceFromListener();
  13889. }
  13890. }
  13891. }
  13892. }
  13893. };
  13894. Object.defineProperty(Scene.prototype, "audioEnabled", {
  13895. // Audio
  13896. get: function () {
  13897. return this._audioEnabled;
  13898. },
  13899. set: function (value) {
  13900. this._audioEnabled = value;
  13901. if (BABYLON.AudioEngine) {
  13902. if (this._audioEnabled) {
  13903. this._enableAudio();
  13904. }
  13905. else {
  13906. this._disableAudio();
  13907. }
  13908. }
  13909. },
  13910. enumerable: true,
  13911. configurable: true
  13912. });
  13913. Scene.prototype._disableAudio = function () {
  13914. var i;
  13915. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13916. this.mainSoundTrack.soundCollection[i].pause();
  13917. }
  13918. for (i = 0; i < this.soundTracks.length; i++) {
  13919. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13920. this.soundTracks[i].soundCollection[j].pause();
  13921. }
  13922. }
  13923. };
  13924. Scene.prototype._enableAudio = function () {
  13925. var i;
  13926. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13927. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  13928. this.mainSoundTrack.soundCollection[i].play();
  13929. }
  13930. }
  13931. for (i = 0; i < this.soundTracks.length; i++) {
  13932. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13933. if (this.soundTracks[i].soundCollection[j].isPaused) {
  13934. this.soundTracks[i].soundCollection[j].play();
  13935. }
  13936. }
  13937. }
  13938. };
  13939. Object.defineProperty(Scene.prototype, "headphone", {
  13940. get: function () {
  13941. return this._headphone;
  13942. },
  13943. set: function (value) {
  13944. this._headphone = value;
  13945. if (BABYLON.AudioEngine) {
  13946. if (this._headphone) {
  13947. this._switchAudioModeForHeadphones();
  13948. }
  13949. else {
  13950. this._switchAudioModeForNormalSpeakers();
  13951. }
  13952. }
  13953. },
  13954. enumerable: true,
  13955. configurable: true
  13956. });
  13957. Scene.prototype._switchAudioModeForHeadphones = function () {
  13958. this.mainSoundTrack.switchPanningModelToHRTF();
  13959. for (var i = 0; i < this.soundTracks.length; i++) {
  13960. this.soundTracks[i].switchPanningModelToHRTF();
  13961. }
  13962. };
  13963. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  13964. this.mainSoundTrack.switchPanningModelToEqualPower();
  13965. for (var i = 0; i < this.soundTracks.length; i++) {
  13966. this.soundTracks[i].switchPanningModelToEqualPower();
  13967. }
  13968. };
  13969. Scene.prototype.enableDepthRenderer = function () {
  13970. if (this._depthRenderer) {
  13971. return this._depthRenderer;
  13972. }
  13973. this._depthRenderer = new BABYLON.DepthRenderer(this);
  13974. return this._depthRenderer;
  13975. };
  13976. Scene.prototype.disableDepthRenderer = function () {
  13977. if (!this._depthRenderer) {
  13978. return;
  13979. }
  13980. this._depthRenderer.dispose();
  13981. this._depthRenderer = null;
  13982. };
  13983. Scene.prototype.freezeMaterials = function () {
  13984. for (var i = 0; i < this.materials.length; i++) {
  13985. this.materials[i].freeze();
  13986. }
  13987. };
  13988. Scene.prototype.unfreezeMaterials = function () {
  13989. for (var i = 0; i < this.materials.length; i++) {
  13990. this.materials[i].unfreeze();
  13991. }
  13992. };
  13993. Scene.prototype.dispose = function () {
  13994. this.beforeRender = null;
  13995. this.afterRender = null;
  13996. this.skeletons = [];
  13997. this._boundingBoxRenderer.dispose();
  13998. if (this._depthRenderer) {
  13999. this._depthRenderer.dispose();
  14000. }
  14001. // Debug layer
  14002. this.debugLayer.hide();
  14003. // Events
  14004. if (this.onDispose) {
  14005. this.onDispose();
  14006. }
  14007. this._onBeforeRenderCallbacks = [];
  14008. this._onAfterRenderCallbacks = [];
  14009. this.detachControl();
  14010. // Release sounds & sounds tracks
  14011. if (BABYLON.AudioEngine) {
  14012. this.disposeSounds();
  14013. }
  14014. // Detach cameras
  14015. var canvas = this._engine.getRenderingCanvas();
  14016. var index;
  14017. for (index = 0; index < this.cameras.length; index++) {
  14018. this.cameras[index].detachControl(canvas);
  14019. }
  14020. // Release lights
  14021. while (this.lights.length) {
  14022. this.lights[0].dispose();
  14023. }
  14024. // Release meshes
  14025. while (this.meshes.length) {
  14026. this.meshes[0].dispose(true);
  14027. }
  14028. // Release cameras
  14029. while (this.cameras.length) {
  14030. this.cameras[0].dispose();
  14031. }
  14032. // Release materials
  14033. while (this.materials.length) {
  14034. this.materials[0].dispose();
  14035. }
  14036. // Release particles
  14037. while (this.particleSystems.length) {
  14038. this.particleSystems[0].dispose();
  14039. }
  14040. // Release sprites
  14041. while (this.spriteManagers.length) {
  14042. this.spriteManagers[0].dispose();
  14043. }
  14044. // Release layers
  14045. while (this.layers.length) {
  14046. this.layers[0].dispose();
  14047. }
  14048. // Release textures
  14049. while (this.textures.length) {
  14050. this.textures[0].dispose();
  14051. }
  14052. // Post-processes
  14053. this.postProcessManager.dispose();
  14054. // Physics
  14055. if (this._physicsEngine) {
  14056. this.disablePhysicsEngine();
  14057. }
  14058. // Remove from engine
  14059. index = this._engine.scenes.indexOf(this);
  14060. if (index > -1) {
  14061. this._engine.scenes.splice(index, 1);
  14062. }
  14063. this._engine.wipeCaches();
  14064. };
  14065. // Release sounds & sounds tracks
  14066. Scene.prototype.disposeSounds = function () {
  14067. this.mainSoundTrack.dispose();
  14068. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  14069. this.soundTracks[scIndex].dispose();
  14070. }
  14071. };
  14072. // Octrees
  14073. Scene.prototype.getWorldExtends = function () {
  14074. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14075. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  14076. for (var index = 0; index < this.meshes.length; index++) {
  14077. var mesh = this.meshes[index];
  14078. mesh.computeWorldMatrix(true);
  14079. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  14080. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  14081. BABYLON.Tools.CheckExtends(minBox, min, max);
  14082. BABYLON.Tools.CheckExtends(maxBox, min, max);
  14083. }
  14084. return {
  14085. min: min,
  14086. max: max
  14087. };
  14088. };
  14089. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  14090. if (maxCapacity === void 0) { maxCapacity = 64; }
  14091. if (maxDepth === void 0) { maxDepth = 2; }
  14092. if (!this._selectionOctree) {
  14093. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  14094. }
  14095. var worldExtends = this.getWorldExtends();
  14096. // Update octree
  14097. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  14098. return this._selectionOctree;
  14099. };
  14100. // Picking
  14101. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  14102. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  14103. var engine = this._engine;
  14104. if (!camera) {
  14105. if (!this.activeCamera)
  14106. throw new Error("Active camera not set");
  14107. camera = this.activeCamera;
  14108. }
  14109. var cameraViewport = camera.viewport;
  14110. var viewport = cameraViewport.toGlobal(engine);
  14111. // Moving coordinates to local viewport world
  14112. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  14113. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  14114. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  14115. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  14116. };
  14117. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  14118. var engine = this._engine;
  14119. if (!camera) {
  14120. if (!this.activeCamera)
  14121. throw new Error("Active camera not set");
  14122. camera = this.activeCamera;
  14123. }
  14124. var cameraViewport = camera.viewport;
  14125. var viewport = cameraViewport.toGlobal(engine);
  14126. var identity = BABYLON.Matrix.Identity();
  14127. // Moving coordinates to local viewport world
  14128. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  14129. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  14130. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  14131. };
  14132. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  14133. var pickingInfo = null;
  14134. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  14135. var mesh = this.meshes[meshIndex];
  14136. if (predicate) {
  14137. if (!predicate(mesh)) {
  14138. continue;
  14139. }
  14140. }
  14141. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  14142. continue;
  14143. }
  14144. var world = mesh.getWorldMatrix();
  14145. var ray = rayFunction(world);
  14146. var result = mesh.intersects(ray, fastCheck);
  14147. if (!result || !result.hit)
  14148. continue;
  14149. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  14150. continue;
  14151. pickingInfo = result;
  14152. if (fastCheck) {
  14153. break;
  14154. }
  14155. }
  14156. return pickingInfo || new BABYLON.PickingInfo();
  14157. };
  14158. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  14159. var pickingInfo = null;
  14160. camera = camera || this.activeCamera;
  14161. if (this.spriteManagers.length > 0) {
  14162. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  14163. var spriteManager = this.spriteManagers[spriteIndex];
  14164. if (!spriteManager.isPickable) {
  14165. continue;
  14166. }
  14167. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  14168. if (!result || !result.hit)
  14169. continue;
  14170. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  14171. continue;
  14172. pickingInfo = result;
  14173. if (fastCheck) {
  14174. break;
  14175. }
  14176. }
  14177. }
  14178. return pickingInfo || new BABYLON.PickingInfo();
  14179. };
  14180. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  14181. var _this = this;
  14182. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  14183. /// <param name="x">X position on screen</param>
  14184. /// <param name="y">Y position on screen</param>
  14185. /// <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>
  14186. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  14187. /// <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>
  14188. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  14189. };
  14190. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  14191. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  14192. /// <param name="x">X position on screen</param>
  14193. /// <param name="y">Y position on screen</param>
  14194. /// <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>
  14195. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  14196. /// <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>
  14197. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  14198. };
  14199. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  14200. var _this = this;
  14201. return this._internalPick(function (world) {
  14202. if (!_this._pickWithRayInverseMatrix) {
  14203. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  14204. }
  14205. world.invertToRef(_this._pickWithRayInverseMatrix);
  14206. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  14207. }, predicate, fastCheck);
  14208. };
  14209. Scene.prototype.setPointerOverMesh = function (mesh) {
  14210. if (this._pointerOverMesh === mesh) {
  14211. return;
  14212. }
  14213. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  14214. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  14215. }
  14216. this._pointerOverMesh = mesh;
  14217. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  14218. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  14219. }
  14220. };
  14221. Scene.prototype.getPointerOverMesh = function () {
  14222. return this._pointerOverMesh;
  14223. };
  14224. Scene.prototype.setPointerOverSprite = function (sprite) {
  14225. if (this._pointerOverSprite === sprite) {
  14226. return;
  14227. }
  14228. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  14229. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  14230. }
  14231. this._pointerOverSprite = sprite;
  14232. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  14233. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  14234. }
  14235. };
  14236. Scene.prototype.getPointerOverSprite = function () {
  14237. return this._pointerOverSprite;
  14238. };
  14239. // Physics
  14240. Scene.prototype.getPhysicsEngine = function () {
  14241. return this._physicsEngine;
  14242. };
  14243. /**
  14244. * Enables physics to the current scene
  14245. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  14246. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  14247. * @return {boolean} was the physics engine initialized
  14248. */
  14249. Scene.prototype.enablePhysics = function (gravity, plugin) {
  14250. if (this._physicsEngine) {
  14251. return true;
  14252. }
  14253. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  14254. if (!this._physicsEngine.isSupported()) {
  14255. this._physicsEngine = null;
  14256. return false;
  14257. }
  14258. this._physicsEngine._initialize(gravity);
  14259. return true;
  14260. };
  14261. Scene.prototype.disablePhysicsEngine = function () {
  14262. if (!this._physicsEngine) {
  14263. return;
  14264. }
  14265. this._physicsEngine.dispose();
  14266. this._physicsEngine = undefined;
  14267. };
  14268. Scene.prototype.isPhysicsEnabled = function () {
  14269. return this._physicsEngine !== undefined;
  14270. };
  14271. /**
  14272. * Sets the gravity of the physics engine (and NOT of the scene)
  14273. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  14274. */
  14275. Scene.prototype.setGravity = function (gravity) {
  14276. if (!this._physicsEngine) {
  14277. return;
  14278. }
  14279. this._physicsEngine._setGravity(gravity);
  14280. };
  14281. Scene.prototype.createCompoundImpostor = function (parts, options) {
  14282. if (parts.parts) {
  14283. options = parts;
  14284. parts = parts.parts;
  14285. }
  14286. if (!this._physicsEngine) {
  14287. return null;
  14288. }
  14289. for (var index = 0; index < parts.length; index++) {
  14290. var mesh = parts[index].mesh;
  14291. mesh._physicImpostor = parts[index].impostor;
  14292. mesh._physicsMass = options.mass / parts.length;
  14293. mesh._physicsFriction = options.friction;
  14294. mesh._physicRestitution = options.restitution;
  14295. }
  14296. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  14297. };
  14298. Scene.prototype.deleteCompoundImpostor = function (compound) {
  14299. for (var index = 0; index < compound.parts.length; index++) {
  14300. var mesh = compound.parts[index].mesh;
  14301. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  14302. this._physicsEngine._unregisterMesh(mesh);
  14303. }
  14304. };
  14305. // Misc.
  14306. Scene.prototype.createDefaultCameraOrLight = function () {
  14307. // Light
  14308. if (this.lights.length === 0) {
  14309. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  14310. }
  14311. // Camera
  14312. if (!this.activeCamera) {
  14313. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  14314. // Compute position
  14315. var worldExtends = this.getWorldExtends();
  14316. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  14317. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  14318. camera.setTarget(worldCenter);
  14319. this.activeCamera = camera;
  14320. }
  14321. };
  14322. // Tags
  14323. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  14324. if (tagsQuery === undefined) {
  14325. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  14326. return list;
  14327. }
  14328. var listByTags = [];
  14329. forEach = forEach || (function (item) { return; });
  14330. for (var i in list) {
  14331. var item = list[i];
  14332. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  14333. listByTags.push(item);
  14334. forEach(item);
  14335. }
  14336. }
  14337. return listByTags;
  14338. };
  14339. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  14340. return this._getByTags(this.meshes, tagsQuery, forEach);
  14341. };
  14342. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  14343. return this._getByTags(this.cameras, tagsQuery, forEach);
  14344. };
  14345. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  14346. return this._getByTags(this.lights, tagsQuery, forEach);
  14347. };
  14348. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  14349. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  14350. };
  14351. // Statics
  14352. Scene._FOGMODE_NONE = 0;
  14353. Scene._FOGMODE_EXP = 1;
  14354. Scene._FOGMODE_EXP2 = 2;
  14355. Scene._FOGMODE_LINEAR = 3;
  14356. Scene.MinDeltaTime = 1.0;
  14357. Scene.MaxDeltaTime = 1000.0;
  14358. return Scene;
  14359. })();
  14360. BABYLON.Scene = Scene;
  14361. })(BABYLON || (BABYLON = {}));
  14362. var BABYLON;
  14363. (function (BABYLON) {
  14364. var VertexBuffer = (function () {
  14365. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  14366. if (engine instanceof BABYLON.Mesh) {
  14367. this._engine = engine.getScene().getEngine();
  14368. }
  14369. else {
  14370. this._engine = engine;
  14371. }
  14372. this._updatable = updatable;
  14373. this._data = data;
  14374. if (!postponeInternalCreation) {
  14375. this.create();
  14376. }
  14377. this._kind = kind;
  14378. if (stride) {
  14379. this._strideSize = stride;
  14380. return;
  14381. }
  14382. // Deduce stride from kind
  14383. switch (kind) {
  14384. case VertexBuffer.PositionKind:
  14385. this._strideSize = 3;
  14386. break;
  14387. case VertexBuffer.NormalKind:
  14388. this._strideSize = 3;
  14389. break;
  14390. case VertexBuffer.UVKind:
  14391. case VertexBuffer.UV2Kind:
  14392. case VertexBuffer.UV3Kind:
  14393. case VertexBuffer.UV4Kind:
  14394. case VertexBuffer.UV5Kind:
  14395. case VertexBuffer.UV6Kind:
  14396. this._strideSize = 2;
  14397. break;
  14398. case VertexBuffer.ColorKind:
  14399. this._strideSize = 4;
  14400. break;
  14401. case VertexBuffer.MatricesIndicesKind:
  14402. case VertexBuffer.MatricesIndicesExtraKind:
  14403. this._strideSize = 4;
  14404. break;
  14405. case VertexBuffer.MatricesWeightsKind:
  14406. case VertexBuffer.MatricesWeightsExtraKind:
  14407. this._strideSize = 4;
  14408. break;
  14409. }
  14410. }
  14411. // Properties
  14412. VertexBuffer.prototype.isUpdatable = function () {
  14413. return this._updatable;
  14414. };
  14415. VertexBuffer.prototype.getData = function () {
  14416. return this._data;
  14417. };
  14418. VertexBuffer.prototype.getBuffer = function () {
  14419. return this._buffer;
  14420. };
  14421. VertexBuffer.prototype.getStrideSize = function () {
  14422. return this._strideSize;
  14423. };
  14424. // Methods
  14425. VertexBuffer.prototype.create = function (data) {
  14426. if (!data && this._buffer) {
  14427. return; // nothing to do
  14428. }
  14429. data = data || this._data;
  14430. if (!this._buffer) {
  14431. if (this._updatable) {
  14432. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  14433. }
  14434. else {
  14435. this._buffer = this._engine.createVertexBuffer(data);
  14436. }
  14437. }
  14438. if (this._updatable) {
  14439. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  14440. this._data = data;
  14441. }
  14442. };
  14443. VertexBuffer.prototype.update = function (data) {
  14444. this.create(data);
  14445. };
  14446. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  14447. if (!this._buffer) {
  14448. return;
  14449. }
  14450. if (this._updatable) {
  14451. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  14452. this._data = null;
  14453. }
  14454. };
  14455. VertexBuffer.prototype.dispose = function () {
  14456. if (!this._buffer) {
  14457. return;
  14458. }
  14459. if (this._engine._releaseBuffer(this._buffer)) {
  14460. this._buffer = null;
  14461. }
  14462. };
  14463. Object.defineProperty(VertexBuffer, "PositionKind", {
  14464. get: function () {
  14465. return VertexBuffer._PositionKind;
  14466. },
  14467. enumerable: true,
  14468. configurable: true
  14469. });
  14470. Object.defineProperty(VertexBuffer, "NormalKind", {
  14471. get: function () {
  14472. return VertexBuffer._NormalKind;
  14473. },
  14474. enumerable: true,
  14475. configurable: true
  14476. });
  14477. Object.defineProperty(VertexBuffer, "UVKind", {
  14478. get: function () {
  14479. return VertexBuffer._UVKind;
  14480. },
  14481. enumerable: true,
  14482. configurable: true
  14483. });
  14484. Object.defineProperty(VertexBuffer, "UV2Kind", {
  14485. get: function () {
  14486. return VertexBuffer._UV2Kind;
  14487. },
  14488. enumerable: true,
  14489. configurable: true
  14490. });
  14491. Object.defineProperty(VertexBuffer, "UV3Kind", {
  14492. get: function () {
  14493. return VertexBuffer._UV3Kind;
  14494. },
  14495. enumerable: true,
  14496. configurable: true
  14497. });
  14498. Object.defineProperty(VertexBuffer, "UV4Kind", {
  14499. get: function () {
  14500. return VertexBuffer._UV4Kind;
  14501. },
  14502. enumerable: true,
  14503. configurable: true
  14504. });
  14505. Object.defineProperty(VertexBuffer, "UV5Kind", {
  14506. get: function () {
  14507. return VertexBuffer._UV5Kind;
  14508. },
  14509. enumerable: true,
  14510. configurable: true
  14511. });
  14512. Object.defineProperty(VertexBuffer, "UV6Kind", {
  14513. get: function () {
  14514. return VertexBuffer._UV6Kind;
  14515. },
  14516. enumerable: true,
  14517. configurable: true
  14518. });
  14519. Object.defineProperty(VertexBuffer, "ColorKind", {
  14520. get: function () {
  14521. return VertexBuffer._ColorKind;
  14522. },
  14523. enumerable: true,
  14524. configurable: true
  14525. });
  14526. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  14527. get: function () {
  14528. return VertexBuffer._MatricesIndicesKind;
  14529. },
  14530. enumerable: true,
  14531. configurable: true
  14532. });
  14533. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  14534. get: function () {
  14535. return VertexBuffer._MatricesWeightsKind;
  14536. },
  14537. enumerable: true,
  14538. configurable: true
  14539. });
  14540. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  14541. get: function () {
  14542. return VertexBuffer._MatricesIndicesExtraKind;
  14543. },
  14544. enumerable: true,
  14545. configurable: true
  14546. });
  14547. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  14548. get: function () {
  14549. return VertexBuffer._MatricesWeightsExtraKind;
  14550. },
  14551. enumerable: true,
  14552. configurable: true
  14553. });
  14554. // Enums
  14555. VertexBuffer._PositionKind = "position";
  14556. VertexBuffer._NormalKind = "normal";
  14557. VertexBuffer._UVKind = "uv";
  14558. VertexBuffer._UV2Kind = "uv2";
  14559. VertexBuffer._UV3Kind = "uv3";
  14560. VertexBuffer._UV4Kind = "uv4";
  14561. VertexBuffer._UV5Kind = "uv5";
  14562. VertexBuffer._UV6Kind = "uv6";
  14563. VertexBuffer._ColorKind = "color";
  14564. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  14565. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  14566. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  14567. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  14568. return VertexBuffer;
  14569. })();
  14570. BABYLON.VertexBuffer = VertexBuffer;
  14571. })(BABYLON || (BABYLON = {}));
  14572. var BABYLON;
  14573. (function (BABYLON) {
  14574. /**
  14575. * Creates an instance based on a source mesh.
  14576. */
  14577. var InstancedMesh = (function (_super) {
  14578. __extends(InstancedMesh, _super);
  14579. function InstancedMesh(name, source) {
  14580. _super.call(this, name, source.getScene());
  14581. source.instances.push(this);
  14582. this._sourceMesh = source;
  14583. this.position.copyFrom(source.position);
  14584. this.rotation.copyFrom(source.rotation);
  14585. this.scaling.copyFrom(source.scaling);
  14586. if (source.rotationQuaternion) {
  14587. this.rotationQuaternion = source.rotationQuaternion.clone();
  14588. }
  14589. this.infiniteDistance = source.infiniteDistance;
  14590. this.setPivotMatrix(source.getPivotMatrix());
  14591. this.refreshBoundingInfo();
  14592. this._syncSubMeshes();
  14593. }
  14594. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  14595. // Methods
  14596. get: function () {
  14597. return this._sourceMesh.receiveShadows;
  14598. },
  14599. enumerable: true,
  14600. configurable: true
  14601. });
  14602. Object.defineProperty(InstancedMesh.prototype, "material", {
  14603. get: function () {
  14604. return this._sourceMesh.material;
  14605. },
  14606. enumerable: true,
  14607. configurable: true
  14608. });
  14609. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  14610. get: function () {
  14611. return this._sourceMesh.visibility;
  14612. },
  14613. enumerable: true,
  14614. configurable: true
  14615. });
  14616. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  14617. get: function () {
  14618. return this._sourceMesh.skeleton;
  14619. },
  14620. enumerable: true,
  14621. configurable: true
  14622. });
  14623. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  14624. get: function () {
  14625. return this._sourceMesh.renderingGroupId;
  14626. },
  14627. enumerable: true,
  14628. configurable: true
  14629. });
  14630. InstancedMesh.prototype.getTotalVertices = function () {
  14631. return this._sourceMesh.getTotalVertices();
  14632. };
  14633. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  14634. get: function () {
  14635. return this._sourceMesh;
  14636. },
  14637. enumerable: true,
  14638. configurable: true
  14639. });
  14640. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  14641. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  14642. };
  14643. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  14644. return this._sourceMesh.isVerticesDataPresent(kind);
  14645. };
  14646. InstancedMesh.prototype.getIndices = function () {
  14647. return this._sourceMesh.getIndices();
  14648. };
  14649. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  14650. get: function () {
  14651. return this._sourceMesh._positions;
  14652. },
  14653. enumerable: true,
  14654. configurable: true
  14655. });
  14656. InstancedMesh.prototype.refreshBoundingInfo = function () {
  14657. var meshBB = this._sourceMesh.getBoundingInfo();
  14658. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  14659. this._updateBoundingInfo();
  14660. };
  14661. InstancedMesh.prototype._preActivate = function () {
  14662. if (this._currentLOD) {
  14663. this._currentLOD._preActivate();
  14664. }
  14665. };
  14666. InstancedMesh.prototype._activate = function (renderId) {
  14667. if (this._currentLOD) {
  14668. this._currentLOD._registerInstanceForRenderId(this, renderId);
  14669. }
  14670. };
  14671. InstancedMesh.prototype.getLOD = function (camera) {
  14672. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  14673. if (this._currentLOD === this.sourceMesh) {
  14674. return this;
  14675. }
  14676. return this._currentLOD;
  14677. };
  14678. InstancedMesh.prototype._syncSubMeshes = function () {
  14679. this.releaseSubMeshes();
  14680. if (this._sourceMesh.subMeshes) {
  14681. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  14682. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  14683. }
  14684. }
  14685. };
  14686. InstancedMesh.prototype._generatePointsArray = function () {
  14687. return this._sourceMesh._generatePointsArray();
  14688. };
  14689. // Clone
  14690. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  14691. var result = this._sourceMesh.createInstance(name);
  14692. // Deep copy
  14693. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  14694. // Bounding info
  14695. this.refreshBoundingInfo();
  14696. // Parent
  14697. if (newParent) {
  14698. result.parent = newParent;
  14699. }
  14700. if (!doNotCloneChildren) {
  14701. // Children
  14702. for (var index = 0; index < this.getScene().meshes.length; index++) {
  14703. var mesh = this.getScene().meshes[index];
  14704. if (mesh.parent === this) {
  14705. mesh.clone(mesh.name, result);
  14706. }
  14707. }
  14708. }
  14709. result.computeWorldMatrix(true);
  14710. return result;
  14711. };
  14712. // Dispoe
  14713. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  14714. // Remove from mesh
  14715. var index = this._sourceMesh.instances.indexOf(this);
  14716. this._sourceMesh.instances.splice(index, 1);
  14717. _super.prototype.dispose.call(this, doNotRecurse);
  14718. };
  14719. return InstancedMesh;
  14720. })(BABYLON.AbstractMesh);
  14721. BABYLON.InstancedMesh = InstancedMesh;
  14722. })(BABYLON || (BABYLON = {}));
  14723. var BABYLON;
  14724. (function (BABYLON) {
  14725. var _InstancesBatch = (function () {
  14726. function _InstancesBatch() {
  14727. this.mustReturn = false;
  14728. this.visibleInstances = new Array();
  14729. this.renderSelf = new Array();
  14730. }
  14731. return _InstancesBatch;
  14732. })();
  14733. BABYLON._InstancesBatch = _InstancesBatch;
  14734. var Mesh = (function (_super) {
  14735. __extends(Mesh, _super);
  14736. /**
  14737. * @constructor
  14738. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  14739. * @param {Scene} scene - The scene to add this mesh to.
  14740. * @param {Node} parent - The parent of this mesh, if it has one
  14741. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  14742. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  14743. * When false, achieved by calling a clone(), also passing False.
  14744. * This will make creation of children, recursive.
  14745. */
  14746. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  14747. if (parent === void 0) { parent = null; }
  14748. _super.call(this, name, scene);
  14749. // Members
  14750. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  14751. this.instances = new Array();
  14752. this._LODLevels = new Array();
  14753. this._onBeforeRenderCallbacks = new Array();
  14754. this._onAfterRenderCallbacks = new Array();
  14755. this._visibleInstances = {};
  14756. this._renderIdForInstances = new Array();
  14757. this._batchCache = new _InstancesBatch();
  14758. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  14759. this._sideOrientation = Mesh._DEFAULTSIDE;
  14760. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  14761. if (source) {
  14762. // Geometry
  14763. if (source._geometry) {
  14764. source._geometry.applyToMesh(this);
  14765. }
  14766. // Deep copy
  14767. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], []);
  14768. this.id = name + "." + source.id;
  14769. // Material
  14770. this.material = source.material;
  14771. var index;
  14772. if (!doNotCloneChildren) {
  14773. // Children
  14774. for (index = 0; index < scene.meshes.length; index++) {
  14775. var mesh = scene.meshes[index];
  14776. if (mesh.parent === source) {
  14777. // doNotCloneChildren is always going to be False
  14778. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  14779. }
  14780. }
  14781. }
  14782. // Particles
  14783. for (index = 0; index < scene.particleSystems.length; index++) {
  14784. var system = scene.particleSystems[index];
  14785. if (system.emitter === source) {
  14786. system.clone(system.name, this);
  14787. }
  14788. }
  14789. this.computeWorldMatrix(true);
  14790. }
  14791. // Parent
  14792. if (parent !== null) {
  14793. this.parent = parent;
  14794. }
  14795. }
  14796. Object.defineProperty(Mesh, "FRONTSIDE", {
  14797. get: function () {
  14798. return Mesh._FRONTSIDE;
  14799. },
  14800. enumerable: true,
  14801. configurable: true
  14802. });
  14803. Object.defineProperty(Mesh, "BACKSIDE", {
  14804. get: function () {
  14805. return Mesh._BACKSIDE;
  14806. },
  14807. enumerable: true,
  14808. configurable: true
  14809. });
  14810. Object.defineProperty(Mesh, "DOUBLESIDE", {
  14811. get: function () {
  14812. return Mesh._DOUBLESIDE;
  14813. },
  14814. enumerable: true,
  14815. configurable: true
  14816. });
  14817. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  14818. get: function () {
  14819. return Mesh._DEFAULTSIDE;
  14820. },
  14821. enumerable: true,
  14822. configurable: true
  14823. });
  14824. Object.defineProperty(Mesh, "NO_CAP", {
  14825. get: function () {
  14826. return Mesh._NO_CAP;
  14827. },
  14828. enumerable: true,
  14829. configurable: true
  14830. });
  14831. Object.defineProperty(Mesh, "CAP_START", {
  14832. get: function () {
  14833. return Mesh._CAP_START;
  14834. },
  14835. enumerable: true,
  14836. configurable: true
  14837. });
  14838. Object.defineProperty(Mesh, "CAP_END", {
  14839. get: function () {
  14840. return Mesh._CAP_END;
  14841. },
  14842. enumerable: true,
  14843. configurable: true
  14844. });
  14845. Object.defineProperty(Mesh, "CAP_ALL", {
  14846. get: function () {
  14847. return Mesh._CAP_ALL;
  14848. },
  14849. enumerable: true,
  14850. configurable: true
  14851. });
  14852. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  14853. // Methods
  14854. get: function () {
  14855. return this._LODLevels.length > 0;
  14856. },
  14857. enumerable: true,
  14858. configurable: true
  14859. });
  14860. Mesh.prototype._sortLODLevels = function () {
  14861. this._LODLevels.sort(function (a, b) {
  14862. if (a.distance < b.distance) {
  14863. return 1;
  14864. }
  14865. if (a.distance > b.distance) {
  14866. return -1;
  14867. }
  14868. return 0;
  14869. });
  14870. };
  14871. /**
  14872. * Add a mesh as LOD level triggered at the given distance.
  14873. * @param {number} distance - the distance from the center of the object to show this level
  14874. * @param {Mesh} mesh - the mesh to be added as LOD level
  14875. * @return {Mesh} this mesh (for chaining)
  14876. */
  14877. Mesh.prototype.addLODLevel = function (distance, mesh) {
  14878. if (mesh && mesh._masterMesh) {
  14879. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  14880. return this;
  14881. }
  14882. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  14883. this._LODLevels.push(level);
  14884. if (mesh) {
  14885. mesh._masterMesh = this;
  14886. }
  14887. this._sortLODLevels();
  14888. return this;
  14889. };
  14890. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  14891. for (var index = 0; index < this._LODLevels.length; index++) {
  14892. var level = this._LODLevels[index];
  14893. if (level.distance === distance) {
  14894. return level.mesh;
  14895. }
  14896. }
  14897. return null;
  14898. };
  14899. /**
  14900. * Remove a mesh from the LOD array
  14901. * @param {Mesh} mesh - the mesh to be removed.
  14902. * @return {Mesh} this mesh (for chaining)
  14903. */
  14904. Mesh.prototype.removeLODLevel = function (mesh) {
  14905. for (var index = 0; index < this._LODLevels.length; index++) {
  14906. if (this._LODLevels[index].mesh === mesh) {
  14907. this._LODLevels.splice(index, 1);
  14908. if (mesh) {
  14909. mesh._masterMesh = null;
  14910. }
  14911. }
  14912. }
  14913. this._sortLODLevels();
  14914. return this;
  14915. };
  14916. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  14917. if (!this._LODLevels || this._LODLevels.length === 0) {
  14918. return this;
  14919. }
  14920. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  14921. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  14922. if (this.onLODLevelSelection) {
  14923. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  14924. }
  14925. return this;
  14926. }
  14927. for (var index = 0; index < this._LODLevels.length; index++) {
  14928. var level = this._LODLevels[index];
  14929. if (level.distance < distanceToCamera) {
  14930. if (level.mesh) {
  14931. level.mesh._preActivate();
  14932. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  14933. }
  14934. if (this.onLODLevelSelection) {
  14935. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  14936. }
  14937. return level.mesh;
  14938. }
  14939. }
  14940. if (this.onLODLevelSelection) {
  14941. this.onLODLevelSelection(distanceToCamera, this, this);
  14942. }
  14943. return this;
  14944. };
  14945. Object.defineProperty(Mesh.prototype, "geometry", {
  14946. get: function () {
  14947. return this._geometry;
  14948. },
  14949. enumerable: true,
  14950. configurable: true
  14951. });
  14952. Mesh.prototype.getTotalVertices = function () {
  14953. if (!this._geometry) {
  14954. return 0;
  14955. }
  14956. return this._geometry.getTotalVertices();
  14957. };
  14958. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  14959. if (!this._geometry) {
  14960. return null;
  14961. }
  14962. return this._geometry.getVerticesData(kind, copyWhenShared);
  14963. };
  14964. Mesh.prototype.getVertexBuffer = function (kind) {
  14965. if (!this._geometry) {
  14966. return undefined;
  14967. }
  14968. return this._geometry.getVertexBuffer(kind);
  14969. };
  14970. Mesh.prototype.isVerticesDataPresent = function (kind) {
  14971. if (!this._geometry) {
  14972. if (this._delayInfo) {
  14973. return this._delayInfo.indexOf(kind) !== -1;
  14974. }
  14975. return false;
  14976. }
  14977. return this._geometry.isVerticesDataPresent(kind);
  14978. };
  14979. Mesh.prototype.getVerticesDataKinds = function () {
  14980. if (!this._geometry) {
  14981. var result = [];
  14982. if (this._delayInfo) {
  14983. for (var kind in this._delayInfo) {
  14984. result.push(kind);
  14985. }
  14986. }
  14987. return result;
  14988. }
  14989. return this._geometry.getVerticesDataKinds();
  14990. };
  14991. Mesh.prototype.getTotalIndices = function () {
  14992. if (!this._geometry) {
  14993. return 0;
  14994. }
  14995. return this._geometry.getTotalIndices();
  14996. };
  14997. Mesh.prototype.getIndices = function (copyWhenShared) {
  14998. if (!this._geometry) {
  14999. return [];
  15000. }
  15001. return this._geometry.getIndices(copyWhenShared);
  15002. };
  15003. Object.defineProperty(Mesh.prototype, "isBlocked", {
  15004. get: function () {
  15005. return this._masterMesh !== null && this._masterMesh !== undefined;
  15006. },
  15007. enumerable: true,
  15008. configurable: true
  15009. });
  15010. Mesh.prototype.isReady = function () {
  15011. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  15012. return false;
  15013. }
  15014. return _super.prototype.isReady.call(this);
  15015. };
  15016. Mesh.prototype.isDisposed = function () {
  15017. return this._isDisposed;
  15018. };
  15019. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  15020. get: function () {
  15021. return this._sideOrientation;
  15022. },
  15023. set: function (sideO) {
  15024. this._sideOrientation = sideO;
  15025. },
  15026. enumerable: true,
  15027. configurable: true
  15028. });
  15029. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  15030. get: function () {
  15031. return this._areNormalsFrozen;
  15032. },
  15033. enumerable: true,
  15034. configurable: true
  15035. });
  15036. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  15037. Mesh.prototype.freezeNormals = function () {
  15038. this._areNormalsFrozen = true;
  15039. };
  15040. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  15041. Mesh.prototype.unfreezeNormals = function () {
  15042. this._areNormalsFrozen = false;
  15043. };
  15044. // Methods
  15045. Mesh.prototype._preActivate = function () {
  15046. var sceneRenderId = this.getScene().getRenderId();
  15047. if (this._preActivateId === sceneRenderId) {
  15048. return;
  15049. }
  15050. this._preActivateId = sceneRenderId;
  15051. this._visibleInstances = null;
  15052. };
  15053. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  15054. if (!this._visibleInstances) {
  15055. this._visibleInstances = {};
  15056. this._visibleInstances.defaultRenderId = renderId;
  15057. this._visibleInstances.selfDefaultRenderId = this._renderId;
  15058. }
  15059. if (!this._visibleInstances[renderId]) {
  15060. this._visibleInstances[renderId] = new Array();
  15061. }
  15062. this._visibleInstances[renderId].push(instance);
  15063. };
  15064. Mesh.prototype.refreshBoundingInfo = function () {
  15065. if (this._boundingInfo.isLocked) {
  15066. return;
  15067. }
  15068. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15069. if (data) {
  15070. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  15071. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  15072. }
  15073. if (this.subMeshes) {
  15074. for (var index = 0; index < this.subMeshes.length; index++) {
  15075. this.subMeshes[index].refreshBoundingInfo();
  15076. }
  15077. }
  15078. this._updateBoundingInfo();
  15079. };
  15080. Mesh.prototype._createGlobalSubMesh = function () {
  15081. var totalVertices = this.getTotalVertices();
  15082. if (!totalVertices || !this.getIndices()) {
  15083. return null;
  15084. }
  15085. this.releaseSubMeshes();
  15086. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  15087. };
  15088. Mesh.prototype.subdivide = function (count) {
  15089. if (count < 1) {
  15090. return;
  15091. }
  15092. var totalIndices = this.getTotalIndices();
  15093. var subdivisionSize = (totalIndices / count) | 0;
  15094. var offset = 0;
  15095. // Ensure that subdivisionSize is a multiple of 3
  15096. while (subdivisionSize % 3 !== 0) {
  15097. subdivisionSize++;
  15098. }
  15099. this.releaseSubMeshes();
  15100. for (var index = 0; index < count; index++) {
  15101. if (offset >= totalIndices) {
  15102. break;
  15103. }
  15104. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  15105. offset += subdivisionSize;
  15106. }
  15107. this.synchronizeInstances();
  15108. };
  15109. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  15110. if (!this._geometry) {
  15111. var vertexData = new BABYLON.VertexData();
  15112. vertexData.set(data, kind);
  15113. var scene = this.getScene();
  15114. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  15115. }
  15116. else {
  15117. this._geometry.setVerticesData(kind, data, updatable, stride);
  15118. }
  15119. };
  15120. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  15121. if (!this._geometry) {
  15122. return;
  15123. }
  15124. if (!makeItUnique) {
  15125. this._geometry.updateVerticesData(kind, data, updateExtends);
  15126. }
  15127. else {
  15128. this.makeGeometryUnique();
  15129. this.updateVerticesData(kind, data, updateExtends, false);
  15130. }
  15131. };
  15132. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  15133. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  15134. if (!this._geometry) {
  15135. return;
  15136. }
  15137. if (!makeItUnique) {
  15138. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  15139. }
  15140. else {
  15141. this.makeGeometryUnique();
  15142. this.updateVerticesDataDirectly(kind, data, offset, false);
  15143. }
  15144. };
  15145. // Mesh positions update function :
  15146. // updates the mesh positions according to the positionFunction returned values.
  15147. // The positionFunction argument must be a javascript function accepting the mesh "positions" array as parameter.
  15148. // This dedicated positionFunction computes new mesh positions according to the given mesh type.
  15149. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  15150. if (computeNormals === void 0) { computeNormals = true; }
  15151. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15152. positionFunction(positions);
  15153. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  15154. if (computeNormals) {
  15155. var indices = this.getIndices();
  15156. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15157. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  15158. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  15159. }
  15160. };
  15161. Mesh.prototype.makeGeometryUnique = function () {
  15162. if (!this._geometry) {
  15163. return;
  15164. }
  15165. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  15166. geometry.applyToMesh(this);
  15167. };
  15168. Mesh.prototype.setIndices = function (indices, totalVertices) {
  15169. if (!this._geometry) {
  15170. var vertexData = new BABYLON.VertexData();
  15171. vertexData.indices = indices;
  15172. var scene = this.getScene();
  15173. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  15174. }
  15175. else {
  15176. this._geometry.setIndices(indices, totalVertices);
  15177. }
  15178. };
  15179. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  15180. var engine = this.getScene().getEngine();
  15181. // Wireframe
  15182. var indexToBind;
  15183. if (this._unIndexed) {
  15184. indexToBind = null;
  15185. }
  15186. else {
  15187. switch (fillMode) {
  15188. case BABYLON.Material.PointFillMode:
  15189. indexToBind = null;
  15190. break;
  15191. case BABYLON.Material.WireFrameFillMode:
  15192. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  15193. break;
  15194. default:
  15195. case BABYLON.Material.TriangleFillMode:
  15196. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  15197. break;
  15198. }
  15199. }
  15200. // VBOs
  15201. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  15202. };
  15203. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  15204. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  15205. return;
  15206. }
  15207. if (this.onBeforeDraw) {
  15208. this.onBeforeDraw();
  15209. }
  15210. var engine = this.getScene().getEngine();
  15211. // Draw order
  15212. switch (fillMode) {
  15213. case BABYLON.Material.PointFillMode:
  15214. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  15215. break;
  15216. case BABYLON.Material.WireFrameFillMode:
  15217. if (this._unIndexed) {
  15218. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  15219. }
  15220. else {
  15221. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  15222. }
  15223. break;
  15224. default:
  15225. if (this._unIndexed) {
  15226. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  15227. }
  15228. else {
  15229. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  15230. }
  15231. }
  15232. };
  15233. Mesh.prototype.registerBeforeRender = function (func) {
  15234. this._onBeforeRenderCallbacks.push(func);
  15235. };
  15236. Mesh.prototype.unregisterBeforeRender = function (func) {
  15237. var index = this._onBeforeRenderCallbacks.indexOf(func);
  15238. if (index > -1) {
  15239. this._onBeforeRenderCallbacks.splice(index, 1);
  15240. }
  15241. };
  15242. Mesh.prototype.registerAfterRender = function (func) {
  15243. this._onAfterRenderCallbacks.push(func);
  15244. };
  15245. Mesh.prototype.unregisterAfterRender = function (func) {
  15246. var index = this._onAfterRenderCallbacks.indexOf(func);
  15247. if (index > -1) {
  15248. this._onAfterRenderCallbacks.splice(index, 1);
  15249. }
  15250. };
  15251. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  15252. var scene = this.getScene();
  15253. this._batchCache.mustReturn = false;
  15254. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  15255. this._batchCache.visibleInstances[subMeshId] = null;
  15256. if (this._visibleInstances) {
  15257. var currentRenderId = scene.getRenderId();
  15258. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  15259. var selfRenderId = this._renderId;
  15260. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  15261. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  15262. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  15263. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  15264. }
  15265. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  15266. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  15267. this._batchCache.mustReturn = true;
  15268. return this._batchCache;
  15269. }
  15270. if (currentRenderId !== selfRenderId) {
  15271. this._batchCache.renderSelf[subMeshId] = false;
  15272. }
  15273. }
  15274. this._renderIdForInstances[subMeshId] = currentRenderId;
  15275. }
  15276. return this._batchCache;
  15277. };
  15278. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  15279. var visibleInstances = batch.visibleInstances[subMesh._id];
  15280. var matricesCount = visibleInstances.length + 1;
  15281. var bufferSize = matricesCount * 16 * 4;
  15282. while (this._instancesBufferSize < bufferSize) {
  15283. this._instancesBufferSize *= 2;
  15284. }
  15285. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  15286. if (this._worldMatricesInstancesBuffer) {
  15287. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  15288. }
  15289. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  15290. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  15291. }
  15292. var offset = 0;
  15293. var instancesCount = 0;
  15294. var world = this.getWorldMatrix();
  15295. if (batch.renderSelf[subMesh._id]) {
  15296. world.copyToArray(this._worldMatricesInstancesArray, offset);
  15297. offset += 16;
  15298. instancesCount++;
  15299. }
  15300. if (visibleInstances) {
  15301. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  15302. var instance = visibleInstances[instanceIndex];
  15303. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  15304. offset += 16;
  15305. instancesCount++;
  15306. }
  15307. }
  15308. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  15309. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  15310. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  15311. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  15312. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  15313. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  15314. this._draw(subMesh, fillMode, instancesCount);
  15315. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  15316. };
  15317. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  15318. var scene = this.getScene();
  15319. var engine = scene.getEngine();
  15320. if (hardwareInstancedRendering) {
  15321. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  15322. }
  15323. else {
  15324. if (batch.renderSelf[subMesh._id]) {
  15325. // Draw
  15326. if (onBeforeDraw) {
  15327. onBeforeDraw(false, this.getWorldMatrix());
  15328. }
  15329. this._draw(subMesh, fillMode);
  15330. }
  15331. if (batch.visibleInstances[subMesh._id]) {
  15332. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  15333. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  15334. // World
  15335. var world = instance.getWorldMatrix();
  15336. if (onBeforeDraw) {
  15337. onBeforeDraw(true, world);
  15338. }
  15339. // Draw
  15340. this._draw(subMesh, fillMode);
  15341. }
  15342. }
  15343. }
  15344. };
  15345. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  15346. var scene = this.getScene();
  15347. // Managing instances
  15348. var batch = this._getInstancesRenderList(subMesh._id);
  15349. if (batch.mustReturn) {
  15350. return;
  15351. }
  15352. // Checking geometry state
  15353. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  15354. return;
  15355. }
  15356. var callbackIndex;
  15357. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  15358. this._onBeforeRenderCallbacks[callbackIndex](this);
  15359. }
  15360. var engine = scene.getEngine();
  15361. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  15362. // Material
  15363. var effectiveMaterial = subMesh.getMaterial();
  15364. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  15365. return;
  15366. }
  15367. // Outline - step 1
  15368. var savedDepthWrite = engine.getDepthWrite();
  15369. if (this.renderOutline) {
  15370. engine.setDepthWrite(false);
  15371. scene.getOutlineRenderer().render(subMesh, batch);
  15372. engine.setDepthWrite(savedDepthWrite);
  15373. }
  15374. effectiveMaterial._preBind();
  15375. var effect = effectiveMaterial.getEffect();
  15376. // Bind
  15377. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  15378. this._bind(subMesh, effect, fillMode);
  15379. var world = this.getWorldMatrix();
  15380. effectiveMaterial.bind(world, this);
  15381. // Alpha mode
  15382. if (enableAlphaMode) {
  15383. engine.setAlphaMode(effectiveMaterial.alphaMode);
  15384. }
  15385. // Draw
  15386. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  15387. if (isInstance) {
  15388. effectiveMaterial.bindOnlyWorldMatrix(world);
  15389. }
  15390. });
  15391. // Unbind
  15392. effectiveMaterial.unbind();
  15393. // Outline - step 2
  15394. if (this.renderOutline && savedDepthWrite) {
  15395. engine.setDepthWrite(true);
  15396. engine.setColorWrite(false);
  15397. scene.getOutlineRenderer().render(subMesh, batch);
  15398. engine.setColorWrite(true);
  15399. }
  15400. // Overlay
  15401. if (this.renderOverlay) {
  15402. var currentMode = engine.getAlphaMode();
  15403. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  15404. scene.getOutlineRenderer().render(subMesh, batch, true);
  15405. engine.setAlphaMode(currentMode);
  15406. }
  15407. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  15408. this._onAfterRenderCallbacks[callbackIndex](this);
  15409. }
  15410. };
  15411. Mesh.prototype.getEmittedParticleSystems = function () {
  15412. var results = new Array();
  15413. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  15414. var particleSystem = this.getScene().particleSystems[index];
  15415. if (particleSystem.emitter === this) {
  15416. results.push(particleSystem);
  15417. }
  15418. }
  15419. return results;
  15420. };
  15421. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  15422. var results = new Array();
  15423. var descendants = this.getDescendants();
  15424. descendants.push(this);
  15425. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  15426. var particleSystem = this.getScene().particleSystems[index];
  15427. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  15428. results.push(particleSystem);
  15429. }
  15430. }
  15431. return results;
  15432. };
  15433. Mesh.prototype.getChildren = function () {
  15434. var results = [];
  15435. for (var index = 0; index < this.getScene().meshes.length; index++) {
  15436. var mesh = this.getScene().meshes[index];
  15437. if (mesh.parent === this) {
  15438. results.push(mesh);
  15439. }
  15440. }
  15441. return results;
  15442. };
  15443. Mesh.prototype._checkDelayState = function () {
  15444. var _this = this;
  15445. var that = this;
  15446. var scene = this.getScene();
  15447. if (this._geometry) {
  15448. this._geometry.load(scene);
  15449. }
  15450. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  15451. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  15452. scene._addPendingData(that);
  15453. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  15454. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  15455. if (data instanceof ArrayBuffer) {
  15456. _this._delayLoadingFunction(data, _this);
  15457. }
  15458. else {
  15459. _this._delayLoadingFunction(JSON.parse(data), _this);
  15460. }
  15461. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  15462. scene._removePendingData(_this);
  15463. }, function () { }, scene.database, getBinaryData);
  15464. }
  15465. };
  15466. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  15467. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  15468. return false;
  15469. }
  15470. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  15471. return false;
  15472. }
  15473. this._checkDelayState();
  15474. return true;
  15475. };
  15476. Mesh.prototype.setMaterialByID = function (id) {
  15477. var materials = this.getScene().materials;
  15478. var index;
  15479. for (index = 0; index < materials.length; index++) {
  15480. if (materials[index].id === id) {
  15481. this.material = materials[index];
  15482. return;
  15483. }
  15484. }
  15485. // Multi
  15486. var multiMaterials = this.getScene().multiMaterials;
  15487. for (index = 0; index < multiMaterials.length; index++) {
  15488. if (multiMaterials[index].id === id) {
  15489. this.material = multiMaterials[index];
  15490. return;
  15491. }
  15492. }
  15493. };
  15494. Mesh.prototype.getAnimatables = function () {
  15495. var results = [];
  15496. if (this.material) {
  15497. results.push(this.material);
  15498. }
  15499. if (this.skeleton) {
  15500. results.push(this.skeleton);
  15501. }
  15502. return results;
  15503. };
  15504. // Geometry
  15505. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  15506. // Position
  15507. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  15508. return;
  15509. }
  15510. this._resetPointsArrayCache();
  15511. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15512. var temp = [];
  15513. var index;
  15514. for (index = 0; index < data.length; index += 3) {
  15515. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  15516. }
  15517. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  15518. // Normals
  15519. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15520. return;
  15521. }
  15522. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15523. temp = [];
  15524. for (index = 0; index < data.length; index += 3) {
  15525. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  15526. }
  15527. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  15528. // flip faces?
  15529. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  15530. this.flipFaces();
  15531. }
  15532. };
  15533. // Will apply current transform to mesh and reset world matrix
  15534. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  15535. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  15536. this.scaling.copyFromFloats(1, 1, 1);
  15537. this.position.copyFromFloats(0, 0, 0);
  15538. this.rotation.copyFromFloats(0, 0, 0);
  15539. //only if quaternion is already set
  15540. if (this.rotationQuaternion) {
  15541. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  15542. }
  15543. this._worldMatrix = BABYLON.Matrix.Identity();
  15544. };
  15545. // Cache
  15546. Mesh.prototype._resetPointsArrayCache = function () {
  15547. this._positions = null;
  15548. };
  15549. Mesh.prototype._generatePointsArray = function () {
  15550. if (this._positions)
  15551. return true;
  15552. this._positions = [];
  15553. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15554. if (!data) {
  15555. return false;
  15556. }
  15557. for (var index = 0; index < data.length; index += 3) {
  15558. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  15559. }
  15560. return true;
  15561. };
  15562. // Clone
  15563. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  15564. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  15565. };
  15566. // Dispose
  15567. Mesh.prototype.dispose = function (doNotRecurse) {
  15568. if (this._geometry) {
  15569. this._geometry.releaseForMesh(this, true);
  15570. }
  15571. // Instances
  15572. if (this._worldMatricesInstancesBuffer) {
  15573. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  15574. this._worldMatricesInstancesBuffer = null;
  15575. }
  15576. while (this.instances.length) {
  15577. this.instances[0].dispose();
  15578. }
  15579. _super.prototype.dispose.call(this, doNotRecurse);
  15580. };
  15581. // Geometric tools
  15582. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  15583. var _this = this;
  15584. var scene = this.getScene();
  15585. var onload = function (img) {
  15586. // Getting height map data
  15587. var canvas = document.createElement("canvas");
  15588. var context = canvas.getContext("2d");
  15589. var heightMapWidth = img.width;
  15590. var heightMapHeight = img.height;
  15591. canvas.width = heightMapWidth;
  15592. canvas.height = heightMapHeight;
  15593. context.drawImage(img, 0, 0);
  15594. // Create VertexData from map data
  15595. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  15596. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  15597. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  15598. //execute success callback, if set
  15599. if (onSuccess) {
  15600. onSuccess(_this);
  15601. }
  15602. };
  15603. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  15604. };
  15605. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  15606. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  15607. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  15608. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  15609. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  15610. return;
  15611. }
  15612. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15613. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15614. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  15615. var position = BABYLON.Vector3.Zero();
  15616. var normal = BABYLON.Vector3.Zero();
  15617. var uv = BABYLON.Vector2.Zero();
  15618. for (var index = 0; index < positions.length; index += 3) {
  15619. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  15620. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  15621. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  15622. // Compute height
  15623. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  15624. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  15625. var pos = (u + v * heightMapWidth) * 4;
  15626. var r = buffer[pos] / 255.0;
  15627. var g = buffer[pos + 1] / 255.0;
  15628. var b = buffer[pos + 2] / 255.0;
  15629. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  15630. normal.normalize();
  15631. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  15632. position = position.add(normal);
  15633. position.toArray(positions, index);
  15634. }
  15635. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  15636. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  15637. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  15638. };
  15639. Mesh.prototype.convertToFlatShadedMesh = function () {
  15640. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  15641. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  15642. var kinds = this.getVerticesDataKinds();
  15643. var vbs = [];
  15644. var data = [];
  15645. var newdata = [];
  15646. var updatableNormals = false;
  15647. var kindIndex;
  15648. var kind;
  15649. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15650. kind = kinds[kindIndex];
  15651. var vertexBuffer = this.getVertexBuffer(kind);
  15652. if (kind === BABYLON.VertexBuffer.NormalKind) {
  15653. updatableNormals = vertexBuffer.isUpdatable();
  15654. kinds.splice(kindIndex, 1);
  15655. kindIndex--;
  15656. continue;
  15657. }
  15658. vbs[kind] = vertexBuffer;
  15659. data[kind] = vbs[kind].getData();
  15660. newdata[kind] = [];
  15661. }
  15662. // Save previous submeshes
  15663. var previousSubmeshes = this.subMeshes.slice(0);
  15664. var indices = this.getIndices();
  15665. var totalIndices = this.getTotalIndices();
  15666. // Generating unique vertices per face
  15667. var index;
  15668. for (index = 0; index < totalIndices; index++) {
  15669. var vertexIndex = indices[index];
  15670. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15671. kind = kinds[kindIndex];
  15672. var stride = vbs[kind].getStrideSize();
  15673. for (var offset = 0; offset < stride; offset++) {
  15674. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  15675. }
  15676. }
  15677. }
  15678. // Updating faces & normal
  15679. var normals = [];
  15680. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  15681. for (index = 0; index < totalIndices; index += 3) {
  15682. indices[index] = index;
  15683. indices[index + 1] = index + 1;
  15684. indices[index + 2] = index + 2;
  15685. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  15686. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  15687. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  15688. var p1p2 = p1.subtract(p2);
  15689. var p3p2 = p3.subtract(p2);
  15690. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  15691. // Store same normals for every vertex
  15692. for (var localIndex = 0; localIndex < 3; localIndex++) {
  15693. normals.push(normal.x);
  15694. normals.push(normal.y);
  15695. normals.push(normal.z);
  15696. }
  15697. }
  15698. this.setIndices(indices);
  15699. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  15700. // Updating vertex buffers
  15701. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15702. kind = kinds[kindIndex];
  15703. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  15704. }
  15705. // Updating submeshes
  15706. this.releaseSubMeshes();
  15707. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  15708. var previousOne = previousSubmeshes[submeshIndex];
  15709. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  15710. }
  15711. this.synchronizeInstances();
  15712. };
  15713. Mesh.prototype.convertToUnIndexedMesh = function () {
  15714. /// <summary>Remove indices by unfolding faces into buffers</summary>
  15715. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  15716. var kinds = this.getVerticesDataKinds();
  15717. var vbs = [];
  15718. var data = [];
  15719. var newdata = [];
  15720. var updatableNormals = false;
  15721. var kindIndex;
  15722. var kind;
  15723. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15724. kind = kinds[kindIndex];
  15725. var vertexBuffer = this.getVertexBuffer(kind);
  15726. vbs[kind] = vertexBuffer;
  15727. data[kind] = vbs[kind].getData();
  15728. newdata[kind] = [];
  15729. }
  15730. // Save previous submeshes
  15731. var previousSubmeshes = this.subMeshes.slice(0);
  15732. var indices = this.getIndices();
  15733. var totalIndices = this.getTotalIndices();
  15734. // Generating unique vertices per face
  15735. var index;
  15736. for (index = 0; index < totalIndices; index++) {
  15737. var vertexIndex = indices[index];
  15738. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15739. kind = kinds[kindIndex];
  15740. var stride = vbs[kind].getStrideSize();
  15741. for (var offset = 0; offset < stride; offset++) {
  15742. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  15743. }
  15744. }
  15745. }
  15746. // Updating indices
  15747. for (index = 0; index < totalIndices; index += 3) {
  15748. indices[index] = index;
  15749. indices[index + 1] = index + 1;
  15750. indices[index + 2] = index + 2;
  15751. }
  15752. this.setIndices(indices);
  15753. // Updating vertex buffers
  15754. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15755. kind = kinds[kindIndex];
  15756. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  15757. }
  15758. // Updating submeshes
  15759. this.releaseSubMeshes();
  15760. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  15761. var previousOne = previousSubmeshes[submeshIndex];
  15762. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  15763. }
  15764. this._unIndexed = true;
  15765. this.synchronizeInstances();
  15766. };
  15767. // will inverse faces orientations, and invert normals too if specified
  15768. Mesh.prototype.flipFaces = function (flipNormals) {
  15769. if (flipNormals === void 0) { flipNormals = false; }
  15770. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  15771. var i;
  15772. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15773. for (i = 0; i < vertex_data.normals.length; i++) {
  15774. vertex_data.normals[i] *= -1;
  15775. }
  15776. }
  15777. var temp;
  15778. for (i = 0; i < vertex_data.indices.length; i += 3) {
  15779. // reassign indices
  15780. temp = vertex_data.indices[i + 1];
  15781. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  15782. vertex_data.indices[i + 2] = temp;
  15783. }
  15784. vertex_data.applyToMesh(this);
  15785. };
  15786. // Instances
  15787. Mesh.prototype.createInstance = function (name) {
  15788. return new BABYLON.InstancedMesh(name, this);
  15789. };
  15790. Mesh.prototype.synchronizeInstances = function () {
  15791. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  15792. var instance = this.instances[instanceIndex];
  15793. instance._syncSubMeshes();
  15794. }
  15795. };
  15796. /**
  15797. * Simplify the mesh according to the given array of settings.
  15798. * Function will return immediately and will simplify async.
  15799. * @param settings a collection of simplification settings.
  15800. * @param parallelProcessing should all levels calculate parallel or one after the other.
  15801. * @param type the type of simplification to run.
  15802. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  15803. */
  15804. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  15805. if (parallelProcessing === void 0) { parallelProcessing = true; }
  15806. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  15807. this.getScene().simplificationQueue.addTask({
  15808. settings: settings,
  15809. parallelProcessing: parallelProcessing,
  15810. mesh: this,
  15811. simplificationType: simplificationType,
  15812. successCallback: successCallback
  15813. });
  15814. };
  15815. /**
  15816. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  15817. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  15818. * This should be used together with the simplification to avoid disappearing triangles.
  15819. * @param successCallback an optional success callback to be called after the optimization finished.
  15820. */
  15821. Mesh.prototype.optimizeIndices = function (successCallback) {
  15822. var _this = this;
  15823. var indices = this.getIndices();
  15824. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15825. var vectorPositions = [];
  15826. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  15827. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  15828. }
  15829. var dupes = [];
  15830. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  15831. var realPos = vectorPositions.length - 1 - iteration;
  15832. var testedPosition = vectorPositions[realPos];
  15833. for (var j = 0; j < realPos; ++j) {
  15834. var againstPosition = vectorPositions[j];
  15835. if (testedPosition.equals(againstPosition)) {
  15836. dupes[realPos] = j;
  15837. break;
  15838. }
  15839. }
  15840. }, function () {
  15841. for (var i = 0; i < indices.length; ++i) {
  15842. indices[i] = dupes[indices[i]] || indices[i];
  15843. }
  15844. //indices are now reordered
  15845. var originalSubMeshes = _this.subMeshes.slice(0);
  15846. _this.setIndices(indices);
  15847. _this.subMeshes = originalSubMeshes;
  15848. if (successCallback) {
  15849. successCallback(_this);
  15850. }
  15851. });
  15852. };
  15853. // Statics
  15854. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  15855. var mesh = new Mesh(parsedMesh.name, scene);
  15856. mesh.id = parsedMesh.id;
  15857. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  15858. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  15859. if (parsedMesh.rotationQuaternion) {
  15860. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  15861. }
  15862. else if (parsedMesh.rotation) {
  15863. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  15864. }
  15865. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  15866. if (parsedMesh.localMatrix) {
  15867. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  15868. }
  15869. else if (parsedMesh.pivotMatrix) {
  15870. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  15871. }
  15872. mesh.setEnabled(parsedMesh.isEnabled);
  15873. mesh.isVisible = parsedMesh.isVisible;
  15874. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  15875. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  15876. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  15877. if (parsedMesh.applyFog !== undefined) {
  15878. mesh.applyFog = parsedMesh.applyFog;
  15879. }
  15880. if (parsedMesh.pickable !== undefined) {
  15881. mesh.isPickable = parsedMesh.pickable;
  15882. }
  15883. if (parsedMesh.alphaIndex !== undefined) {
  15884. mesh.alphaIndex = parsedMesh.alphaIndex;
  15885. }
  15886. mesh.receiveShadows = parsedMesh.receiveShadows;
  15887. mesh.billboardMode = parsedMesh.billboardMode;
  15888. if (parsedMesh.visibility !== undefined) {
  15889. mesh.visibility = parsedMesh.visibility;
  15890. }
  15891. mesh.checkCollisions = parsedMesh.checkCollisions;
  15892. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  15893. // freezeWorldMatrix
  15894. if (parsedMesh.freezeWorldMatrix) {
  15895. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  15896. }
  15897. // Parent
  15898. if (parsedMesh.parentId) {
  15899. mesh._waitingParentId = parsedMesh.parentId;
  15900. }
  15901. // Actions
  15902. if (parsedMesh.actions !== undefined) {
  15903. mesh._waitingActions = parsedMesh.actions;
  15904. }
  15905. // Geometry
  15906. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  15907. if (parsedMesh.delayLoadingFile) {
  15908. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  15909. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  15910. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  15911. if (parsedMesh._binaryInfo) {
  15912. mesh._binaryInfo = parsedMesh._binaryInfo;
  15913. }
  15914. mesh._delayInfo = [];
  15915. if (parsedMesh.hasUVs) {
  15916. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  15917. }
  15918. if (parsedMesh.hasUVs2) {
  15919. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  15920. }
  15921. if (parsedMesh.hasUVs3) {
  15922. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  15923. }
  15924. if (parsedMesh.hasUVs4) {
  15925. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  15926. }
  15927. if (parsedMesh.hasUVs5) {
  15928. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  15929. }
  15930. if (parsedMesh.hasUVs6) {
  15931. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  15932. }
  15933. if (parsedMesh.hasColors) {
  15934. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  15935. }
  15936. if (parsedMesh.hasMatricesIndices) {
  15937. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  15938. }
  15939. if (parsedMesh.hasMatricesWeights) {
  15940. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  15941. }
  15942. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  15943. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  15944. mesh._checkDelayState();
  15945. }
  15946. }
  15947. else {
  15948. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  15949. }
  15950. // Material
  15951. if (parsedMesh.materialId) {
  15952. mesh.setMaterialByID(parsedMesh.materialId);
  15953. }
  15954. else {
  15955. mesh.material = null;
  15956. }
  15957. // Skeleton
  15958. if (parsedMesh.skeletonId > -1) {
  15959. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  15960. if (parsedMesh.numBoneInfluencers) {
  15961. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  15962. }
  15963. }
  15964. // Physics
  15965. if (parsedMesh.physicsImpostor) {
  15966. if (!scene.isPhysicsEnabled()) {
  15967. scene.enablePhysics();
  15968. }
  15969. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  15970. }
  15971. // Animations
  15972. if (parsedMesh.animations) {
  15973. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  15974. var parsedAnimation = parsedMesh.animations[animationIndex];
  15975. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  15976. }
  15977. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  15978. }
  15979. if (parsedMesh.autoAnimate) {
  15980. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  15981. }
  15982. // Layer Mask
  15983. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  15984. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  15985. }
  15986. else {
  15987. mesh.layerMask = 0x0FFFFFFF;
  15988. }
  15989. // Instances
  15990. if (parsedMesh.instances) {
  15991. for (var index = 0; index < parsedMesh.instances.length; index++) {
  15992. var parsedInstance = parsedMesh.instances[index];
  15993. var instance = mesh.createInstance(parsedInstance.name);
  15994. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  15995. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  15996. if (parsedInstance.rotationQuaternion) {
  15997. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  15998. }
  15999. else if (parsedInstance.rotation) {
  16000. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  16001. }
  16002. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  16003. instance.checkCollisions = mesh.checkCollisions;
  16004. if (parsedMesh.animations) {
  16005. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  16006. parsedAnimation = parsedMesh.animations[animationIndex];
  16007. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  16008. }
  16009. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  16010. }
  16011. }
  16012. }
  16013. return mesh;
  16014. };
  16015. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  16016. return BABYLON.MeshBuilder.CreateRibbon(name, {
  16017. pathArray: pathArray,
  16018. closeArray: closeArray,
  16019. closePath: closePath,
  16020. offset: offset,
  16021. updatable: updatable,
  16022. sideOrientation: sideOrientation,
  16023. instance: instance
  16024. }, scene);
  16025. };
  16026. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  16027. var options = {
  16028. radius: radius,
  16029. tessellation: tessellation,
  16030. sideOrientation: sideOrientation,
  16031. updatable: updatable
  16032. };
  16033. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  16034. };
  16035. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  16036. var options = {
  16037. size: size,
  16038. sideOrientation: sideOrientation,
  16039. updatable: updatable
  16040. };
  16041. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  16042. };
  16043. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  16044. var options = {
  16045. segments: segments,
  16046. diameterX: diameter,
  16047. diameterY: diameter,
  16048. diameterZ: diameter,
  16049. sideOrientation: sideOrientation,
  16050. updatable: updatable
  16051. };
  16052. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  16053. };
  16054. // Cylinder and cone
  16055. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  16056. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  16057. if (scene !== undefined) {
  16058. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  16059. updatable = scene;
  16060. }
  16061. scene = subdivisions;
  16062. subdivisions = 1;
  16063. }
  16064. var options = {
  16065. height: height,
  16066. diameterTop: diameterTop,
  16067. diameterBottom: diameterBottom,
  16068. tessellation: tessellation,
  16069. subdivisions: subdivisions,
  16070. sideOrientation: sideOrientation,
  16071. updatable: updatable
  16072. };
  16073. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  16074. };
  16075. // Torus (Code from SharpDX.org)
  16076. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  16077. var options = {
  16078. diameter: diameter,
  16079. thickness: thickness,
  16080. tessellation: tessellation,
  16081. sideOrientation: sideOrientation,
  16082. updatable: updatable
  16083. };
  16084. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  16085. };
  16086. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  16087. var options = {
  16088. radius: radius,
  16089. tube: tube,
  16090. radialSegments: radialSegments,
  16091. tubularSegments: tubularSegments,
  16092. p: p,
  16093. q: q,
  16094. sideOrientation: sideOrientation,
  16095. updatable: updatable
  16096. };
  16097. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  16098. };
  16099. // Lines
  16100. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  16101. var options = {
  16102. points: points,
  16103. updatable: updatable,
  16104. instance: instance
  16105. };
  16106. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  16107. };
  16108. // Dashed Lines
  16109. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  16110. var options = {
  16111. points: points,
  16112. dashSize: dashSize,
  16113. gapSize: gapSize,
  16114. dashNb: dashNb,
  16115. updatable: updatable
  16116. };
  16117. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  16118. };
  16119. // Extrusion
  16120. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  16121. var options = {
  16122. shape: shape,
  16123. path: path,
  16124. scale: scale,
  16125. rotation: rotation,
  16126. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  16127. sideOrientation: sideOrientation,
  16128. instance: instance,
  16129. updatable: updatable
  16130. };
  16131. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  16132. };
  16133. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  16134. var options = {
  16135. shape: shape,
  16136. path: path,
  16137. scaleFunction: scaleFunction,
  16138. rotationFunction: rotationFunction,
  16139. ribbonCloseArray: ribbonCloseArray,
  16140. ribbonClosePath: ribbonClosePath,
  16141. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  16142. sideOrientation: sideOrientation,
  16143. instance: instance,
  16144. updatable: updatable
  16145. };
  16146. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  16147. };
  16148. // Lathe
  16149. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  16150. var options = {
  16151. shape: shape,
  16152. radius: radius,
  16153. tessellation: tessellation,
  16154. sideOrientation: sideOrientation,
  16155. updatable: updatable
  16156. };
  16157. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  16158. };
  16159. // Plane & ground
  16160. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  16161. var options = {
  16162. size: size,
  16163. width: size,
  16164. height: size,
  16165. sideOrientation: sideOrientation,
  16166. updatable: updatable
  16167. };
  16168. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  16169. };
  16170. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  16171. var options = {
  16172. width: width,
  16173. height: height,
  16174. subdivisions: subdivisions,
  16175. updatable: updatable
  16176. };
  16177. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  16178. };
  16179. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  16180. var options = {
  16181. xmin: xmin,
  16182. zmin: zmin,
  16183. xmax: xmax,
  16184. zmax: zmax,
  16185. subdivisions: subdivisions,
  16186. precision: precision,
  16187. updatable: updatable
  16188. };
  16189. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  16190. };
  16191. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  16192. var options = {
  16193. width: width,
  16194. height: height,
  16195. subdivisions: subdivisions,
  16196. minHeight: minHeight,
  16197. maxHeight: maxHeight,
  16198. updatable: updatable,
  16199. onReady: onReady
  16200. };
  16201. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  16202. };
  16203. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  16204. var options = {
  16205. path: path,
  16206. radius: radius,
  16207. tessellation: tessellation,
  16208. radiusFunction: radiusFunction,
  16209. arc: 1,
  16210. cap: cap,
  16211. updatable: updatable,
  16212. sideOrientation: sideOrientation,
  16213. instance: instance
  16214. };
  16215. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  16216. };
  16217. Mesh.CreatePolyhedron = function (name, options, scene) {
  16218. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  16219. };
  16220. Mesh.CreateIcoSphere = function (name, options, scene) {
  16221. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  16222. };
  16223. // Decals
  16224. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  16225. var options = {
  16226. position: position,
  16227. normal: normal,
  16228. size: size,
  16229. angle: angle
  16230. };
  16231. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  16232. };
  16233. // Skeletons
  16234. /**
  16235. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  16236. */
  16237. Mesh.prototype.setPositionsForCPUSkinning = function () {
  16238. var source;
  16239. if (!this._sourcePositions) {
  16240. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16241. this._sourcePositions = new Float32Array(source);
  16242. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  16243. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  16244. }
  16245. }
  16246. return this._sourcePositions;
  16247. };
  16248. /**
  16249. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  16250. */
  16251. Mesh.prototype.setNormalsForCPUSkinning = function () {
  16252. var source;
  16253. if (!this._sourceNormals) {
  16254. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16255. this._sourceNormals = new Float32Array(source);
  16256. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  16257. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  16258. }
  16259. }
  16260. return this._sourceNormals;
  16261. };
  16262. /**
  16263. * Update the vertex buffers by applying transformation from the bones
  16264. * @param {skeleton} skeleton to apply
  16265. */
  16266. Mesh.prototype.applySkeleton = function (skeleton) {
  16267. if (!this.geometry) {
  16268. return;
  16269. }
  16270. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  16271. return;
  16272. }
  16273. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  16274. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  16275. return this;
  16276. }
  16277. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16278. return this;
  16279. }
  16280. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  16281. return this;
  16282. }
  16283. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  16284. return this;
  16285. }
  16286. if (!this._sourcePositions) {
  16287. this.setPositionsForCPUSkinning();
  16288. }
  16289. if (!this._sourceNormals) {
  16290. this.setNormalsForCPUSkinning();
  16291. }
  16292. // positionsData checks for not being Float32Array will only pass at most once
  16293. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16294. if (!(positionsData instanceof Float32Array)) {
  16295. positionsData = new Float32Array(positionsData);
  16296. }
  16297. // normalsData checks for not being Float32Array will only pass at most once
  16298. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16299. if (!(normalsData instanceof Float32Array)) {
  16300. normalsData = new Float32Array(normalsData);
  16301. }
  16302. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  16303. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  16304. var needExtras = this.numBoneInfluencers > 4;
  16305. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  16306. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  16307. var skeletonMatrices = skeleton.getTransformMatrices(this);
  16308. var tempVector3 = BABYLON.Vector3.Zero();
  16309. var finalMatrix = new BABYLON.Matrix();
  16310. var tempMatrix = new BABYLON.Matrix();
  16311. var matWeightIdx = 0;
  16312. var inf;
  16313. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  16314. var weight;
  16315. for (inf = 0; inf < 4; inf++) {
  16316. weight = matricesWeightsData[matWeightIdx + inf];
  16317. if (weight > 0) {
  16318. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  16319. finalMatrix.addToSelf(tempMatrix);
  16320. }
  16321. else
  16322. break;
  16323. }
  16324. if (needExtras) {
  16325. for (inf = 0; inf < 4; inf++) {
  16326. weight = matricesWeightsExtraData[matWeightIdx + inf];
  16327. if (weight > 0) {
  16328. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  16329. finalMatrix.addToSelf(tempMatrix);
  16330. }
  16331. else
  16332. break;
  16333. }
  16334. }
  16335. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  16336. tempVector3.toArray(positionsData, index);
  16337. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  16338. tempVector3.toArray(normalsData, index);
  16339. finalMatrix.reset();
  16340. }
  16341. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  16342. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  16343. return this;
  16344. };
  16345. // Tools
  16346. Mesh.MinMax = function (meshes) {
  16347. var minVector = null;
  16348. var maxVector = null;
  16349. for (var i in meshes) {
  16350. var mesh = meshes[i];
  16351. var boundingBox = mesh.getBoundingInfo().boundingBox;
  16352. if (!minVector) {
  16353. minVector = boundingBox.minimumWorld;
  16354. maxVector = boundingBox.maximumWorld;
  16355. continue;
  16356. }
  16357. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  16358. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  16359. }
  16360. return {
  16361. min: minVector,
  16362. max: maxVector
  16363. };
  16364. };
  16365. Mesh.Center = function (meshesOrMinMaxVector) {
  16366. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  16367. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  16368. };
  16369. /**
  16370. * Merge the array of meshes into a single mesh for performance reasons.
  16371. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  16372. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  16373. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  16374. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  16375. */
  16376. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  16377. if (disposeSource === void 0) { disposeSource = true; }
  16378. var index;
  16379. if (!allow32BitsIndices) {
  16380. var totalVertices = 0;
  16381. // Counting vertices
  16382. for (index = 0; index < meshes.length; index++) {
  16383. if (meshes[index]) {
  16384. totalVertices += meshes[index].getTotalVertices();
  16385. if (totalVertices > 65536) {
  16386. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  16387. return null;
  16388. }
  16389. }
  16390. }
  16391. }
  16392. // Merge
  16393. var vertexData;
  16394. var otherVertexData;
  16395. var source;
  16396. for (index = 0; index < meshes.length; index++) {
  16397. if (meshes[index]) {
  16398. meshes[index].computeWorldMatrix(true);
  16399. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  16400. otherVertexData.transform(meshes[index].getWorldMatrix());
  16401. if (vertexData) {
  16402. vertexData.merge(otherVertexData);
  16403. }
  16404. else {
  16405. vertexData = otherVertexData;
  16406. source = meshes[index];
  16407. }
  16408. }
  16409. }
  16410. if (!meshSubclass) {
  16411. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  16412. }
  16413. vertexData.applyToMesh(meshSubclass);
  16414. // Setting properties
  16415. meshSubclass.material = source.material;
  16416. meshSubclass.checkCollisions = source.checkCollisions;
  16417. // Cleaning
  16418. if (disposeSource) {
  16419. for (index = 0; index < meshes.length; index++) {
  16420. if (meshes[index]) {
  16421. meshes[index].dispose();
  16422. }
  16423. }
  16424. }
  16425. return meshSubclass;
  16426. };
  16427. // Consts
  16428. Mesh._FRONTSIDE = 0;
  16429. Mesh._BACKSIDE = 1;
  16430. Mesh._DOUBLESIDE = 2;
  16431. Mesh._DEFAULTSIDE = 0;
  16432. Mesh._NO_CAP = 0;
  16433. Mesh._CAP_START = 1;
  16434. Mesh._CAP_END = 2;
  16435. Mesh._CAP_ALL = 3;
  16436. return Mesh;
  16437. })(BABYLON.AbstractMesh);
  16438. BABYLON.Mesh = Mesh;
  16439. })(BABYLON || (BABYLON = {}));
  16440. var BABYLON;
  16441. (function (BABYLON) {
  16442. var SubMesh = (function () {
  16443. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  16444. if (createBoundingBox === void 0) { createBoundingBox = true; }
  16445. this.materialIndex = materialIndex;
  16446. this.verticesStart = verticesStart;
  16447. this.verticesCount = verticesCount;
  16448. this.indexStart = indexStart;
  16449. this.indexCount = indexCount;
  16450. this._renderId = 0;
  16451. this._mesh = mesh;
  16452. this._renderingMesh = renderingMesh || mesh;
  16453. mesh.subMeshes.push(this);
  16454. this._trianglePlanes = [];
  16455. this._id = mesh.subMeshes.length - 1;
  16456. if (createBoundingBox) {
  16457. this.refreshBoundingInfo();
  16458. mesh.computeWorldMatrix(true);
  16459. }
  16460. }
  16461. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  16462. get: function () {
  16463. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  16464. },
  16465. enumerable: true,
  16466. configurable: true
  16467. });
  16468. SubMesh.prototype.getBoundingInfo = function () {
  16469. if (this.IsGlobal) {
  16470. return this._mesh.getBoundingInfo();
  16471. }
  16472. return this._boundingInfo;
  16473. };
  16474. SubMesh.prototype.getMesh = function () {
  16475. return this._mesh;
  16476. };
  16477. SubMesh.prototype.getRenderingMesh = function () {
  16478. return this._renderingMesh;
  16479. };
  16480. SubMesh.prototype.getMaterial = function () {
  16481. var rootMaterial = this._renderingMesh.material;
  16482. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  16483. var multiMaterial = rootMaterial;
  16484. return multiMaterial.getSubMaterial(this.materialIndex);
  16485. }
  16486. if (!rootMaterial) {
  16487. return this._mesh.getScene().defaultMaterial;
  16488. }
  16489. return rootMaterial;
  16490. };
  16491. // Methods
  16492. SubMesh.prototype.refreshBoundingInfo = function () {
  16493. if (this.IsGlobal) {
  16494. return;
  16495. }
  16496. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16497. if (!data) {
  16498. this._boundingInfo = this._mesh._boundingInfo;
  16499. return;
  16500. }
  16501. var indices = this._renderingMesh.getIndices();
  16502. var extend;
  16503. //is this the only submesh?
  16504. if (this.indexStart === 0 && this.indexCount === indices.length) {
  16505. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  16506. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  16507. }
  16508. else {
  16509. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  16510. }
  16511. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  16512. };
  16513. SubMesh.prototype._checkCollision = function (collider) {
  16514. return this.getBoundingInfo()._checkCollision(collider);
  16515. };
  16516. SubMesh.prototype.updateBoundingInfo = function (world) {
  16517. if (!this.getBoundingInfo()) {
  16518. this.refreshBoundingInfo();
  16519. }
  16520. this.getBoundingInfo().update(world);
  16521. };
  16522. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  16523. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  16524. };
  16525. SubMesh.prototype.render = function (enableAlphaMode) {
  16526. this._renderingMesh.render(this, enableAlphaMode);
  16527. };
  16528. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  16529. if (!this._linesIndexBuffer) {
  16530. var linesIndices = [];
  16531. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  16532. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  16533. }
  16534. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  16535. this.linesIndexCount = linesIndices.length;
  16536. }
  16537. return this._linesIndexBuffer;
  16538. };
  16539. SubMesh.prototype.canIntersects = function (ray) {
  16540. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  16541. };
  16542. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  16543. var intersectInfo = null;
  16544. // Triangles test
  16545. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  16546. var p0 = positions[indices[index]];
  16547. var p1 = positions[indices[index + 1]];
  16548. var p2 = positions[indices[index + 2]];
  16549. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  16550. if (currentIntersectInfo) {
  16551. if (currentIntersectInfo.distance < 0) {
  16552. continue;
  16553. }
  16554. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  16555. intersectInfo = currentIntersectInfo;
  16556. intersectInfo.faceId = index / 3;
  16557. if (fastCheck) {
  16558. break;
  16559. }
  16560. }
  16561. }
  16562. }
  16563. return intersectInfo;
  16564. };
  16565. // Clone
  16566. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  16567. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  16568. if (!this.IsGlobal) {
  16569. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  16570. }
  16571. return result;
  16572. };
  16573. // Dispose
  16574. SubMesh.prototype.dispose = function () {
  16575. if (this._linesIndexBuffer) {
  16576. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  16577. this._linesIndexBuffer = null;
  16578. }
  16579. // Remove from mesh
  16580. var index = this._mesh.subMeshes.indexOf(this);
  16581. this._mesh.subMeshes.splice(index, 1);
  16582. };
  16583. // Statics
  16584. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  16585. var minVertexIndex = Number.MAX_VALUE;
  16586. var maxVertexIndex = -Number.MAX_VALUE;
  16587. renderingMesh = renderingMesh || mesh;
  16588. var indices = renderingMesh.getIndices();
  16589. for (var index = startIndex; index < startIndex + indexCount; index++) {
  16590. var vertexIndex = indices[index];
  16591. if (vertexIndex < minVertexIndex)
  16592. minVertexIndex = vertexIndex;
  16593. if (vertexIndex > maxVertexIndex)
  16594. maxVertexIndex = vertexIndex;
  16595. }
  16596. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  16597. };
  16598. return SubMesh;
  16599. })();
  16600. BABYLON.SubMesh = SubMesh;
  16601. })(BABYLON || (BABYLON = {}));
  16602. var BABYLON;
  16603. (function (BABYLON) {
  16604. var MeshBuilder = (function () {
  16605. function MeshBuilder() {
  16606. }
  16607. MeshBuilder.CreateBox = function (name, options, scene) {
  16608. var box = new BABYLON.Mesh(name, scene);
  16609. var vertexData = BABYLON.VertexData.CreateBox(options);
  16610. vertexData.applyToMesh(box, options.updatable);
  16611. return box;
  16612. };
  16613. MeshBuilder.CreateSphere = function (name, options, scene) {
  16614. var sphere = new BABYLON.Mesh(name, scene);
  16615. var vertexData = BABYLON.VertexData.CreateSphere(options);
  16616. vertexData.applyToMesh(sphere, options.updatable);
  16617. return sphere;
  16618. };
  16619. MeshBuilder.CreateDisc = function (name, options, scene) {
  16620. var disc = new BABYLON.Mesh(name, scene);
  16621. var vertexData = BABYLON.VertexData.CreateDisc(options);
  16622. vertexData.applyToMesh(disc, options.updatable);
  16623. return disc;
  16624. };
  16625. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  16626. var sphere = new BABYLON.Mesh(name, scene);
  16627. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  16628. vertexData.applyToMesh(sphere, options.updatable);
  16629. return sphere;
  16630. };
  16631. ;
  16632. MeshBuilder.CreateRibbon = function (name, options, scene) {
  16633. var pathArray = options.pathArray;
  16634. var closeArray = options.closeArray;
  16635. var closePath = options.closePath;
  16636. var offset = options.offset;
  16637. var sideOrientation = options.sideOrientation;
  16638. var instance = options.instance;
  16639. var updatable = options.updatable;
  16640. if (instance) {
  16641. // positionFunction : ribbon case
  16642. // only pathArray and sideOrientation parameters are taken into account for positions update
  16643. var positionFunction = function (positions) {
  16644. var minlg = pathArray[0].length;
  16645. var i = 0;
  16646. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  16647. for (var si = 1; si <= ns; si++) {
  16648. for (var p = 0; p < pathArray.length; p++) {
  16649. var path = pathArray[p];
  16650. var l = path.length;
  16651. minlg = (minlg < l) ? minlg : l;
  16652. var j = 0;
  16653. while (j < minlg) {
  16654. positions[i] = path[j].x;
  16655. positions[i + 1] = path[j].y;
  16656. positions[i + 2] = path[j].z;
  16657. j++;
  16658. i += 3;
  16659. }
  16660. if (instance._closePath) {
  16661. positions[i] = path[0].x;
  16662. positions[i + 1] = path[0].y;
  16663. positions[i + 2] = path[0].z;
  16664. i += 3;
  16665. }
  16666. }
  16667. }
  16668. };
  16669. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16670. positionFunction(positions);
  16671. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  16672. if (!(instance.areNormalsFrozen)) {
  16673. var indices = instance.getIndices();
  16674. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16675. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  16676. if (instance._closePath) {
  16677. var indexFirst = 0;
  16678. var indexLast = 0;
  16679. for (var p = 0; p < pathArray.length; p++) {
  16680. indexFirst = instance._idx[p] * 3;
  16681. if (p + 1 < pathArray.length) {
  16682. indexLast = (instance._idx[p + 1] - 1) * 3;
  16683. }
  16684. else {
  16685. indexLast = normals.length - 3;
  16686. }
  16687. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  16688. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  16689. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  16690. normals[indexLast] = normals[indexFirst];
  16691. normals[indexLast + 1] = normals[indexFirst + 1];
  16692. normals[indexLast + 2] = normals[indexFirst + 2];
  16693. }
  16694. }
  16695. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  16696. }
  16697. return instance;
  16698. }
  16699. else {
  16700. var ribbon = new BABYLON.Mesh(name, scene);
  16701. ribbon.sideOrientation = sideOrientation;
  16702. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  16703. if (closePath) {
  16704. ribbon._idx = vertexData._idx;
  16705. }
  16706. ribbon._closePath = closePath;
  16707. ribbon._closeArray = closeArray;
  16708. vertexData.applyToMesh(ribbon, updatable);
  16709. return ribbon;
  16710. }
  16711. };
  16712. MeshBuilder.CreateCylinder = function (name, options, scene) {
  16713. var cylinder = new BABYLON.Mesh(name, scene);
  16714. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  16715. vertexData.applyToMesh(cylinder, options.updatable);
  16716. return cylinder;
  16717. };
  16718. MeshBuilder.CreateTorus = function (name, options, scene) {
  16719. var torus = new BABYLON.Mesh(name, scene);
  16720. var vertexData = BABYLON.VertexData.CreateTorus(options);
  16721. vertexData.applyToMesh(torus, options.updatable);
  16722. return torus;
  16723. };
  16724. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  16725. var torusKnot = new BABYLON.Mesh(name, scene);
  16726. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  16727. vertexData.applyToMesh(torusKnot, options.updatable);
  16728. return torusKnot;
  16729. };
  16730. MeshBuilder.CreateLines = function (name, options, scene) {
  16731. var instance = options.instance;
  16732. var points = options.points;
  16733. if (instance) {
  16734. var positionFunction = function (positions) {
  16735. var i = 0;
  16736. for (var p = 0; p < points.length; p++) {
  16737. positions[i] = points[p].x;
  16738. positions[i + 1] = points[p].y;
  16739. positions[i + 2] = points[p].z;
  16740. i += 3;
  16741. }
  16742. };
  16743. instance.updateMeshPositions(positionFunction, false);
  16744. return instance;
  16745. }
  16746. // lines creation
  16747. var lines = new BABYLON.LinesMesh(name, scene);
  16748. var vertexData = BABYLON.VertexData.CreateLines(options);
  16749. vertexData.applyToMesh(lines, options.updatable);
  16750. return lines;
  16751. };
  16752. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  16753. var points = options.points;
  16754. var instance = options.instance;
  16755. var gapSize = options.gapSize;
  16756. var dashNb = options.dashNb;
  16757. var dashSize = options.dashSize;
  16758. if (instance) {
  16759. var positionFunction = function (positions) {
  16760. var curvect = BABYLON.Vector3.Zero();
  16761. var nbSeg = positions.length / 6;
  16762. var lg = 0;
  16763. var nb = 0;
  16764. var shft = 0;
  16765. var dashshft = 0;
  16766. var curshft = 0;
  16767. var p = 0;
  16768. var i = 0;
  16769. var j = 0;
  16770. for (i = 0; i < points.length - 1; i++) {
  16771. points[i + 1].subtractToRef(points[i], curvect);
  16772. lg += curvect.length();
  16773. }
  16774. shft = lg / nbSeg;
  16775. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  16776. for (i = 0; i < points.length - 1; i++) {
  16777. points[i + 1].subtractToRef(points[i], curvect);
  16778. nb = Math.floor(curvect.length() / shft);
  16779. curvect.normalize();
  16780. j = 0;
  16781. while (j < nb && p < positions.length) {
  16782. curshft = shft * j;
  16783. positions[p] = points[i].x + curshft * curvect.x;
  16784. positions[p + 1] = points[i].y + curshft * curvect.y;
  16785. positions[p + 2] = points[i].z + curshft * curvect.z;
  16786. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  16787. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  16788. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  16789. p += 6;
  16790. j++;
  16791. }
  16792. }
  16793. while (p < positions.length) {
  16794. positions[p] = points[i].x;
  16795. positions[p + 1] = points[i].y;
  16796. positions[p + 2] = points[i].z;
  16797. p += 3;
  16798. }
  16799. };
  16800. instance.updateMeshPositions(positionFunction, false);
  16801. return instance;
  16802. }
  16803. // dashed lines creation
  16804. var dashedLines = new BABYLON.LinesMesh(name, scene);
  16805. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  16806. vertexData.applyToMesh(dashedLines, options.updatable);
  16807. dashedLines.dashSize = dashSize;
  16808. dashedLines.gapSize = gapSize;
  16809. return dashedLines;
  16810. };
  16811. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  16812. var path = options.path;
  16813. var shape = options.shape;
  16814. var scale = options.scale || 1;
  16815. var rotation = options.rotation || 0;
  16816. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  16817. var updatable = options.updatable;
  16818. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  16819. var instance = options.instance;
  16820. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance);
  16821. };
  16822. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  16823. var path = options.path;
  16824. var shape = options.shape;
  16825. var scaleFunction = options.scaleFunction || (function () { return 1; });
  16826. var rotationFunction = options.rotationFunction || (function () { return 0; });
  16827. var ribbonCloseArray = options.ribbonCloseArray || false;
  16828. var ribbonClosePath = options.ribbonClosePath || false;
  16829. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  16830. var updatable = options.updatable;
  16831. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  16832. var instance = options.instance;
  16833. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance);
  16834. };
  16835. MeshBuilder.CreateLathe = function (name, options, scene) {
  16836. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  16837. var closed = (options.closed === undefined) ? true : options.closed;
  16838. var shape = options.shape;
  16839. var radius = options.radius || 1;
  16840. var tessellation = options.tessellation || 64;
  16841. var updatable = options.updatable;
  16842. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  16843. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  16844. var pi2 = Math.PI * 2;
  16845. var paths = new Array();
  16846. var i = 0;
  16847. var p = 0;
  16848. var step = pi2 / tessellation * arc;
  16849. var rotated;
  16850. var path = new Array();
  16851. ;
  16852. for (i = 0; i <= tessellation; i++) {
  16853. var path = [];
  16854. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  16855. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  16856. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  16857. }
  16858. for (p = 0; p < shape.length; p++) {
  16859. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  16860. path.push(rotated);
  16861. }
  16862. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  16863. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[shape.length - 1].x * radius, shape[shape.length - 1].y, Math.sin(i * step) * shape[shape.length - 1].x * radius));
  16864. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  16865. }
  16866. paths.push(path);
  16867. }
  16868. // lathe ribbon
  16869. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable }, scene);
  16870. return lathe;
  16871. };
  16872. MeshBuilder.CreatePlane = function (name, options, scene) {
  16873. var plane = new BABYLON.Mesh(name, scene);
  16874. var vertexData = BABYLON.VertexData.CreatePlane(options);
  16875. vertexData.applyToMesh(plane, options.updatable);
  16876. if (options.sourcePlane) {
  16877. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  16878. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  16879. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  16880. plane.rotate(vectorProduct, product);
  16881. }
  16882. return plane;
  16883. };
  16884. MeshBuilder.CreateGround = function (name, options, scene) {
  16885. var ground = new BABYLON.GroundMesh(name, scene);
  16886. ground._setReady(false);
  16887. ground._subdivisions = options.subdivisions || 1;
  16888. ground._width = options.width || 1;
  16889. ground._height = options.height || 1;
  16890. ground._maxX = ground._width / 2;
  16891. ground._maxZ = ground._height / 2;
  16892. ground._minX = -ground._maxX;
  16893. ground._minZ = -ground._maxZ;
  16894. var vertexData = BABYLON.VertexData.CreateGround(options);
  16895. vertexData.applyToMesh(ground, options.updatable);
  16896. ground._setReady(true);
  16897. return ground;
  16898. };
  16899. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  16900. var tiledGround = new BABYLON.Mesh(name, scene);
  16901. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  16902. vertexData.applyToMesh(tiledGround, options.updatable);
  16903. return tiledGround;
  16904. };
  16905. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  16906. var width = options.width || 10;
  16907. var height = options.height || 10;
  16908. var subdivisions = options.subdivisions || 1;
  16909. var minHeight = options.minHeight;
  16910. var maxHeight = options.maxHeight || 10;
  16911. var updatable = options.updatable;
  16912. var onReady = options.onReady;
  16913. var ground = new BABYLON.GroundMesh(name, scene);
  16914. ground._subdivisions = subdivisions;
  16915. ground._width = width;
  16916. ground._height = height;
  16917. ground._maxX = ground._width / 2;
  16918. ground._maxZ = ground._height / 2;
  16919. ground._minX = -ground._maxX;
  16920. ground._minZ = -ground._maxZ;
  16921. ground._setReady(false);
  16922. var onload = function (img) {
  16923. // Getting height map data
  16924. var canvas = document.createElement("canvas");
  16925. var context = canvas.getContext("2d");
  16926. var bufferWidth = img.width;
  16927. var bufferHeight = img.height;
  16928. canvas.width = bufferWidth;
  16929. canvas.height = bufferHeight;
  16930. context.drawImage(img, 0, 0);
  16931. // Create VertexData from map data
  16932. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  16933. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  16934. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  16935. width: width, height: height,
  16936. subdivisions: subdivisions,
  16937. minHeight: minHeight, maxHeight: maxHeight,
  16938. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  16939. });
  16940. vertexData.applyToMesh(ground, updatable);
  16941. ground._setReady(true);
  16942. //execute ready callback, if set
  16943. if (onReady) {
  16944. onReady(ground);
  16945. }
  16946. };
  16947. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  16948. return ground;
  16949. };
  16950. MeshBuilder.CreateTube = function (name, options, scene) {
  16951. var path = options.path;
  16952. var radius = options.radius || 1;
  16953. var tessellation = options.tessellation || 64;
  16954. var radiusFunction = options.radiusFunction;
  16955. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  16956. var updatable = options.updatable;
  16957. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  16958. var instance = options.instance;
  16959. options.arc = (options.arc <= 0 || options.arc > 1) ? 1 : options.arc || 1;
  16960. // tube geometry
  16961. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  16962. var tangents = path3D.getTangents();
  16963. var normals = path3D.getNormals();
  16964. var distances = path3D.getDistances();
  16965. var pi2 = Math.PI * 2;
  16966. var step = pi2 / tessellation * arc;
  16967. var returnRadius = function () { return radius; };
  16968. var radiusFunctionFinal = radiusFunction || returnRadius;
  16969. var circlePath;
  16970. var rad;
  16971. var normal;
  16972. var rotated;
  16973. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  16974. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  16975. for (var i = 0; i < path.length; i++) {
  16976. rad = radiusFunctionFinal(i, distances[i]); // current radius
  16977. circlePath = Array(); // current circle array
  16978. normal = normals[i]; // current normal
  16979. for (var t = 0; t < tessellation; t++) {
  16980. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  16981. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  16982. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  16983. rotated.scaleInPlace(rad).addInPlace(path[i]);
  16984. circlePath[t] = rotated;
  16985. }
  16986. circlePaths[index] = circlePath;
  16987. index++;
  16988. }
  16989. // cap
  16990. var capPath = function (nbPoints, pathIndex) {
  16991. var pointCap = Array();
  16992. for (var i = 0; i < nbPoints; i++) {
  16993. pointCap.push(path[pathIndex]);
  16994. }
  16995. return pointCap;
  16996. };
  16997. switch (cap) {
  16998. case BABYLON.Mesh.NO_CAP:
  16999. break;
  17000. case BABYLON.Mesh.CAP_START:
  17001. circlePaths[0] = capPath(tessellation, 0);
  17002. circlePaths[1] = circlePaths[2].slice(0);
  17003. break;
  17004. case BABYLON.Mesh.CAP_END:
  17005. circlePaths[index] = circlePaths[index - 1].slice(0);
  17006. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  17007. break;
  17008. case BABYLON.Mesh.CAP_ALL:
  17009. circlePaths[0] = capPath(tessellation, 0);
  17010. circlePaths[1] = circlePaths[2].slice(0);
  17011. circlePaths[index] = circlePaths[index - 1].slice(0);
  17012. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  17013. break;
  17014. default:
  17015. break;
  17016. }
  17017. return circlePaths;
  17018. };
  17019. var path3D;
  17020. var pathArray;
  17021. if (instance) {
  17022. var arc = options.arc || instance.arc;
  17023. path3D = (instance.path3D).update(path);
  17024. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  17025. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  17026. instance.path3D = path3D;
  17027. instance.pathArray = pathArray;
  17028. instance.arc = arc;
  17029. return instance;
  17030. }
  17031. // tube creation
  17032. path3D = new BABYLON.Path3D(path);
  17033. var newPathArray = new Array();
  17034. cap = (cap < 0 || cap > 3) ? 0 : cap;
  17035. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  17036. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation }, scene);
  17037. tube.pathArray = pathArray;
  17038. tube.path3D = path3D;
  17039. tube.tessellation = tessellation;
  17040. tube.cap = cap;
  17041. tube.arc = options.arc;
  17042. return tube;
  17043. };
  17044. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  17045. var polyhedron = new BABYLON.Mesh(name, scene);
  17046. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  17047. vertexData.applyToMesh(polyhedron, options.updatable);
  17048. return polyhedron;
  17049. };
  17050. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  17051. var indices = sourceMesh.getIndices();
  17052. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17053. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17054. var position = options.position || BABYLON.Vector3.Zero();
  17055. var normal = options.normal || BABYLON.Vector3.Up();
  17056. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  17057. var angle = options.angle || 0;
  17058. // Getting correct rotation
  17059. if (!normal) {
  17060. var target = new BABYLON.Vector3(0, 0, 1);
  17061. var camera = sourceMesh.getScene().activeCamera;
  17062. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  17063. normal = camera.globalPosition.subtract(cameraWorldTarget);
  17064. }
  17065. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  17066. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  17067. var pitch = Math.atan2(normal.y, len);
  17068. // Matrix
  17069. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  17070. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  17071. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  17072. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  17073. var vertexData = new BABYLON.VertexData();
  17074. vertexData.indices = [];
  17075. vertexData.positions = [];
  17076. vertexData.normals = [];
  17077. vertexData.uvs = [];
  17078. var currentVertexDataIndex = 0;
  17079. var extractDecalVector3 = function (indexId) {
  17080. var vertexId = indices[indexId];
  17081. var result = new BABYLON.PositionNormalVertex();
  17082. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  17083. // Send vector to decal local world
  17084. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  17085. // Get normal
  17086. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  17087. return result;
  17088. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  17089. var clip = function (vertices, axis) {
  17090. if (vertices.length === 0) {
  17091. return vertices;
  17092. }
  17093. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  17094. var clipVertices = function (v0, v1) {
  17095. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  17096. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  17097. };
  17098. var result = new Array();
  17099. for (var index = 0; index < vertices.length; index += 3) {
  17100. var v1Out;
  17101. var v2Out;
  17102. var v3Out;
  17103. var total = 0;
  17104. var nV1, nV2, nV3, nV4;
  17105. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  17106. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  17107. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  17108. v1Out = d1 > 0;
  17109. v2Out = d2 > 0;
  17110. v3Out = d3 > 0;
  17111. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  17112. switch (total) {
  17113. case 0:
  17114. result.push(vertices[index]);
  17115. result.push(vertices[index + 1]);
  17116. result.push(vertices[index + 2]);
  17117. break;
  17118. case 1:
  17119. if (v1Out) {
  17120. nV1 = vertices[index + 1];
  17121. nV2 = vertices[index + 2];
  17122. nV3 = clipVertices(vertices[index], nV1);
  17123. nV4 = clipVertices(vertices[index], nV2);
  17124. }
  17125. if (v2Out) {
  17126. nV1 = vertices[index];
  17127. nV2 = vertices[index + 2];
  17128. nV3 = clipVertices(vertices[index + 1], nV1);
  17129. nV4 = clipVertices(vertices[index + 1], nV2);
  17130. result.push(nV3);
  17131. result.push(nV2.clone());
  17132. result.push(nV1.clone());
  17133. result.push(nV2.clone());
  17134. result.push(nV3.clone());
  17135. result.push(nV4);
  17136. break;
  17137. }
  17138. if (v3Out) {
  17139. nV1 = vertices[index];
  17140. nV2 = vertices[index + 1];
  17141. nV3 = clipVertices(vertices[index + 2], nV1);
  17142. nV4 = clipVertices(vertices[index + 2], nV2);
  17143. }
  17144. result.push(nV1.clone());
  17145. result.push(nV2.clone());
  17146. result.push(nV3);
  17147. result.push(nV4);
  17148. result.push(nV3.clone());
  17149. result.push(nV2.clone());
  17150. break;
  17151. case 2:
  17152. if (!v1Out) {
  17153. nV1 = vertices[index].clone();
  17154. nV2 = clipVertices(nV1, vertices[index + 1]);
  17155. nV3 = clipVertices(nV1, vertices[index + 2]);
  17156. result.push(nV1);
  17157. result.push(nV2);
  17158. result.push(nV3);
  17159. }
  17160. if (!v2Out) {
  17161. nV1 = vertices[index + 1].clone();
  17162. nV2 = clipVertices(nV1, vertices[index + 2]);
  17163. nV3 = clipVertices(nV1, vertices[index]);
  17164. result.push(nV1);
  17165. result.push(nV2);
  17166. result.push(nV3);
  17167. }
  17168. if (!v3Out) {
  17169. nV1 = vertices[index + 2].clone();
  17170. nV2 = clipVertices(nV1, vertices[index]);
  17171. nV3 = clipVertices(nV1, vertices[index + 1]);
  17172. result.push(nV1);
  17173. result.push(nV2);
  17174. result.push(nV3);
  17175. }
  17176. break;
  17177. case 3:
  17178. break;
  17179. }
  17180. }
  17181. return result;
  17182. };
  17183. for (var index = 0; index < indices.length; index += 3) {
  17184. var faceVertices = new Array();
  17185. faceVertices.push(extractDecalVector3(index));
  17186. faceVertices.push(extractDecalVector3(index + 1));
  17187. faceVertices.push(extractDecalVector3(index + 2));
  17188. // Clip
  17189. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  17190. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  17191. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  17192. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  17193. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  17194. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  17195. if (faceVertices.length === 0) {
  17196. continue;
  17197. }
  17198. // Add UVs and get back to world
  17199. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  17200. var vertex = faceVertices[vIndex];
  17201. //TODO check for Int32Array
  17202. vertexData.indices.push(currentVertexDataIndex);
  17203. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  17204. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  17205. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  17206. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  17207. currentVertexDataIndex++;
  17208. }
  17209. }
  17210. // Return mesh
  17211. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  17212. vertexData.applyToMesh(decal);
  17213. decal.position = position.clone();
  17214. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  17215. return decal;
  17216. };
  17217. // Privates
  17218. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance) {
  17219. // extrusion geometry
  17220. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  17221. var tangents = path3D.getTangents();
  17222. var normals = path3D.getNormals();
  17223. var binormals = path3D.getBinormals();
  17224. var distances = path3D.getDistances();
  17225. var angle = 0;
  17226. var returnScale = function () { return scale; };
  17227. var returnRotation = function () { return rotation; };
  17228. var rotate = custom ? rotateFunction : returnRotation;
  17229. var scl = custom ? scaleFunction : returnScale;
  17230. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  17231. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  17232. for (var i = 0; i < curve.length; i++) {
  17233. var shapePath = new Array();
  17234. var angleStep = rotate(i, distances[i]);
  17235. var scaleRatio = scl(i, distances[i]);
  17236. for (var p = 0; p < shape.length; p++) {
  17237. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  17238. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  17239. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  17240. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  17241. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  17242. shapePath[p] = rotated;
  17243. }
  17244. shapePaths[index] = shapePath;
  17245. angle += angleStep;
  17246. index++;
  17247. }
  17248. // cap
  17249. var capPath = function (shapePath) {
  17250. var pointCap = Array();
  17251. var barycenter = BABYLON.Vector3.Zero();
  17252. var i;
  17253. for (i = 0; i < shapePath.length; i++) {
  17254. barycenter.addInPlace(shapePath[i]);
  17255. }
  17256. barycenter.scaleInPlace(1 / shapePath.length);
  17257. for (i = 0; i < shapePath.length; i++) {
  17258. pointCap.push(barycenter);
  17259. }
  17260. return pointCap;
  17261. };
  17262. switch (cap) {
  17263. case BABYLON.Mesh.NO_CAP:
  17264. break;
  17265. case BABYLON.Mesh.CAP_START:
  17266. shapePaths[0] = capPath(shapePaths[2]);
  17267. shapePaths[1] = shapePaths[2].slice(0);
  17268. break;
  17269. case BABYLON.Mesh.CAP_END:
  17270. shapePaths[index] = shapePaths[index - 1];
  17271. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  17272. break;
  17273. case BABYLON.Mesh.CAP_ALL:
  17274. shapePaths[0] = capPath(shapePaths[2]);
  17275. shapePaths[1] = shapePaths[2].slice(0);
  17276. shapePaths[index] = shapePaths[index - 1];
  17277. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  17278. break;
  17279. default:
  17280. break;
  17281. }
  17282. return shapePaths;
  17283. };
  17284. var path3D;
  17285. var pathArray;
  17286. if (instance) {
  17287. path3D = (instance.path3D).update(curve);
  17288. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  17289. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  17290. return instance;
  17291. }
  17292. // extruded shape creation
  17293. path3D = new BABYLON.Path3D(curve);
  17294. var newShapePaths = new Array();
  17295. cap = (cap < 0 || cap > 3) ? 0 : cap;
  17296. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  17297. var extrudedGeneric = BABYLON.Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  17298. extrudedGeneric.pathArray = pathArray;
  17299. extrudedGeneric.path3D = path3D;
  17300. extrudedGeneric.cap = cap;
  17301. return extrudedGeneric;
  17302. };
  17303. return MeshBuilder;
  17304. })();
  17305. BABYLON.MeshBuilder = MeshBuilder;
  17306. })(BABYLON || (BABYLON = {}));
  17307. var BABYLON;
  17308. (function (BABYLON) {
  17309. var BaseTexture = (function () {
  17310. function BaseTexture(scene) {
  17311. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  17312. this.hasAlpha = false;
  17313. this.getAlphaFromRGB = false;
  17314. this.level = 1;
  17315. this.isCube = false;
  17316. this.isRenderTarget = false;
  17317. this.animations = new Array();
  17318. this.coordinatesIndex = 0;
  17319. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  17320. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  17321. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  17322. this.anisotropicFilteringLevel = 4;
  17323. this._scene = scene;
  17324. this._scene.textures.push(this);
  17325. }
  17326. BaseTexture.prototype.getScene = function () {
  17327. return this._scene;
  17328. };
  17329. BaseTexture.prototype.getTextureMatrix = function () {
  17330. return null;
  17331. };
  17332. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  17333. return null;
  17334. };
  17335. BaseTexture.prototype.getInternalTexture = function () {
  17336. return this._texture;
  17337. };
  17338. BaseTexture.prototype.isReady = function () {
  17339. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  17340. return true;
  17341. }
  17342. if (this._texture) {
  17343. return this._texture.isReady;
  17344. }
  17345. return false;
  17346. };
  17347. BaseTexture.prototype.getSize = function () {
  17348. if (this._texture._width) {
  17349. return { width: this._texture._width, height: this._texture._height };
  17350. }
  17351. if (this._texture._size) {
  17352. return { width: this._texture._size, height: this._texture._size };
  17353. }
  17354. return { width: 0, height: 0 };
  17355. };
  17356. BaseTexture.prototype.getBaseSize = function () {
  17357. if (!this.isReady())
  17358. return { width: 0, height: 0 };
  17359. if (this._texture._size) {
  17360. return { width: this._texture._size, height: this._texture._size };
  17361. }
  17362. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  17363. };
  17364. BaseTexture.prototype.scale = function (ratio) {
  17365. };
  17366. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  17367. get: function () {
  17368. return false;
  17369. },
  17370. enumerable: true,
  17371. configurable: true
  17372. });
  17373. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  17374. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  17375. for (var index = 0; index < texturesCache.length; index++) {
  17376. var texturesCacheEntry = texturesCache[index];
  17377. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  17378. texturesCache.splice(index, 1);
  17379. return;
  17380. }
  17381. }
  17382. };
  17383. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  17384. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  17385. for (var index = 0; index < texturesCache.length; index++) {
  17386. var texturesCacheEntry = texturesCache[index];
  17387. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  17388. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  17389. texturesCacheEntry.references++;
  17390. return texturesCacheEntry;
  17391. }
  17392. }
  17393. }
  17394. return null;
  17395. };
  17396. BaseTexture.prototype.delayLoad = function () {
  17397. };
  17398. BaseTexture.prototype.clone = function () {
  17399. return null;
  17400. };
  17401. BaseTexture.prototype.releaseInternalTexture = function () {
  17402. if (this._texture) {
  17403. this._scene.getEngine().releaseInternalTexture(this._texture);
  17404. delete this._texture;
  17405. }
  17406. };
  17407. BaseTexture.prototype.dispose = function () {
  17408. // Animations
  17409. this.getScene().stopAnimation(this);
  17410. // Remove from scene
  17411. var index = this._scene.textures.indexOf(this);
  17412. if (index >= 0) {
  17413. this._scene.textures.splice(index, 1);
  17414. }
  17415. if (this._texture === undefined) {
  17416. return;
  17417. }
  17418. // Release
  17419. this.releaseInternalTexture();
  17420. // Callback
  17421. if (this.onDispose) {
  17422. this.onDispose();
  17423. }
  17424. };
  17425. BaseTexture.prototype.serialize = function () {
  17426. var serializationObject = {};
  17427. if (!this.name) {
  17428. return null;
  17429. }
  17430. serializationObject.name = this.name;
  17431. serializationObject.hasAlpha = this.hasAlpha;
  17432. serializationObject.level = this.level;
  17433. serializationObject.coordinatesIndex = this.coordinatesIndex;
  17434. serializationObject.coordinatesMode = this.coordinatesMode;
  17435. serializationObject.wrapU = this.wrapU;
  17436. serializationObject.wrapV = this.wrapV;
  17437. // Animations
  17438. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  17439. return serializationObject;
  17440. };
  17441. return BaseTexture;
  17442. })();
  17443. BABYLON.BaseTexture = BaseTexture;
  17444. })(BABYLON || (BABYLON = {}));
  17445. var BABYLON;
  17446. (function (BABYLON) {
  17447. var Texture = (function (_super) {
  17448. __extends(Texture, _super);
  17449. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  17450. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  17451. if (onLoad === void 0) { onLoad = null; }
  17452. if (onError === void 0) { onError = null; }
  17453. if (buffer === void 0) { buffer = null; }
  17454. if (deleteBuffer === void 0) { deleteBuffer = false; }
  17455. _super.call(this, scene);
  17456. this.uOffset = 0;
  17457. this.vOffset = 0;
  17458. this.uScale = 1.0;
  17459. this.vScale = 1.0;
  17460. this.uAng = 0;
  17461. this.vAng = 0;
  17462. this.wAng = 0;
  17463. this.name = url;
  17464. this.url = url;
  17465. this._noMipmap = noMipmap;
  17466. this._invertY = invertY;
  17467. this._samplingMode = samplingMode;
  17468. this._buffer = buffer;
  17469. this._deleteBuffer = deleteBuffer;
  17470. if (!url) {
  17471. return;
  17472. }
  17473. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  17474. if (!this._texture) {
  17475. if (!scene.useDelayedTextureLoading) {
  17476. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  17477. if (deleteBuffer) {
  17478. delete this._buffer;
  17479. }
  17480. }
  17481. else {
  17482. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  17483. }
  17484. }
  17485. else {
  17486. BABYLON.Tools.SetImmediate(function () {
  17487. if (onLoad) {
  17488. onLoad();
  17489. }
  17490. });
  17491. }
  17492. }
  17493. Texture.prototype.delayLoad = function () {
  17494. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  17495. return;
  17496. }
  17497. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  17498. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  17499. if (!this._texture) {
  17500. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  17501. if (this._deleteBuffer) {
  17502. delete this._buffer;
  17503. }
  17504. }
  17505. };
  17506. Texture.prototype.updateSamplingMode = function (samplingMode) {
  17507. if (!this._texture) {
  17508. return;
  17509. }
  17510. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  17511. };
  17512. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  17513. x *= this.uScale;
  17514. y *= this.vScale;
  17515. x -= 0.5 * this.uScale;
  17516. y -= 0.5 * this.vScale;
  17517. z -= 0.5;
  17518. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  17519. t.x += 0.5 * this.uScale + this.uOffset;
  17520. t.y += 0.5 * this.vScale + this.vOffset;
  17521. t.z += 0.5;
  17522. };
  17523. Texture.prototype.getTextureMatrix = function () {
  17524. if (this.uOffset === this._cachedUOffset &&
  17525. this.vOffset === this._cachedVOffset &&
  17526. this.uScale === this._cachedUScale &&
  17527. this.vScale === this._cachedVScale &&
  17528. this.uAng === this._cachedUAng &&
  17529. this.vAng === this._cachedVAng &&
  17530. this.wAng === this._cachedWAng) {
  17531. return this._cachedTextureMatrix;
  17532. }
  17533. this._cachedUOffset = this.uOffset;
  17534. this._cachedVOffset = this.vOffset;
  17535. this._cachedUScale = this.uScale;
  17536. this._cachedVScale = this.vScale;
  17537. this._cachedUAng = this.uAng;
  17538. this._cachedVAng = this.vAng;
  17539. this._cachedWAng = this.wAng;
  17540. if (!this._cachedTextureMatrix) {
  17541. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  17542. this._rowGenerationMatrix = new BABYLON.Matrix();
  17543. this._t0 = BABYLON.Vector3.Zero();
  17544. this._t1 = BABYLON.Vector3.Zero();
  17545. this._t2 = BABYLON.Vector3.Zero();
  17546. }
  17547. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  17548. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  17549. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  17550. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  17551. this._t1.subtractInPlace(this._t0);
  17552. this._t2.subtractInPlace(this._t0);
  17553. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  17554. this._cachedTextureMatrix.m[0] = this._t1.x;
  17555. this._cachedTextureMatrix.m[1] = this._t1.y;
  17556. this._cachedTextureMatrix.m[2] = this._t1.z;
  17557. this._cachedTextureMatrix.m[4] = this._t2.x;
  17558. this._cachedTextureMatrix.m[5] = this._t2.y;
  17559. this._cachedTextureMatrix.m[6] = this._t2.z;
  17560. this._cachedTextureMatrix.m[8] = this._t0.x;
  17561. this._cachedTextureMatrix.m[9] = this._t0.y;
  17562. this._cachedTextureMatrix.m[10] = this._t0.z;
  17563. return this._cachedTextureMatrix;
  17564. };
  17565. Texture.prototype.getReflectionTextureMatrix = function () {
  17566. if (this.uOffset === this._cachedUOffset &&
  17567. this.vOffset === this._cachedVOffset &&
  17568. this.uScale === this._cachedUScale &&
  17569. this.vScale === this._cachedVScale &&
  17570. this.coordinatesMode === this._cachedCoordinatesMode) {
  17571. return this._cachedTextureMatrix;
  17572. }
  17573. if (!this._cachedTextureMatrix) {
  17574. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  17575. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  17576. }
  17577. this._cachedCoordinatesMode = this.coordinatesMode;
  17578. switch (this.coordinatesMode) {
  17579. case Texture.PLANAR_MODE:
  17580. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  17581. this._cachedTextureMatrix[0] = this.uScale;
  17582. this._cachedTextureMatrix[5] = this.vScale;
  17583. this._cachedTextureMatrix[12] = this.uOffset;
  17584. this._cachedTextureMatrix[13] = this.vOffset;
  17585. break;
  17586. case Texture.PROJECTION_MODE:
  17587. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  17588. this._projectionModeMatrix.m[0] = 0.5;
  17589. this._projectionModeMatrix.m[5] = -0.5;
  17590. this._projectionModeMatrix.m[10] = 0.0;
  17591. this._projectionModeMatrix.m[12] = 0.5;
  17592. this._projectionModeMatrix.m[13] = 0.5;
  17593. this._projectionModeMatrix.m[14] = 1.0;
  17594. this._projectionModeMatrix.m[15] = 1.0;
  17595. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  17596. break;
  17597. default:
  17598. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  17599. break;
  17600. }
  17601. return this._cachedTextureMatrix;
  17602. };
  17603. Texture.prototype.clone = function () {
  17604. var newTexture = new Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  17605. // Base texture
  17606. newTexture.hasAlpha = this.hasAlpha;
  17607. newTexture.level = this.level;
  17608. newTexture.wrapU = this.wrapU;
  17609. newTexture.wrapV = this.wrapV;
  17610. newTexture.coordinatesIndex = this.coordinatesIndex;
  17611. newTexture.coordinatesMode = this.coordinatesMode;
  17612. // Texture
  17613. newTexture.uOffset = this.uOffset;
  17614. newTexture.vOffset = this.vOffset;
  17615. newTexture.uScale = this.uScale;
  17616. newTexture.vScale = this.vScale;
  17617. newTexture.uAng = this.uAng;
  17618. newTexture.vAng = this.vAng;
  17619. newTexture.wAng = this.wAng;
  17620. return newTexture;
  17621. };
  17622. Texture.prototype.serialize = function () {
  17623. if (!this.name) {
  17624. return null;
  17625. }
  17626. var serializationObject = _super.prototype.serialize.call(this);
  17627. serializationObject.uOffset = this.uOffset;
  17628. serializationObject.vOffset = this.vOffset;
  17629. serializationObject.uScale = this.uScale;
  17630. serializationObject.vScale = this.vScale;
  17631. serializationObject.uAng = this.uAng;
  17632. serializationObject.vAng = this.vAng;
  17633. serializationObject.wAng = this.wAng;
  17634. return serializationObject;
  17635. };
  17636. // Statics
  17637. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  17638. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  17639. if (onLoad === void 0) { onLoad = null; }
  17640. if (onError === void 0) { onError = null; }
  17641. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  17642. };
  17643. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  17644. if (parsedTexture.isCube) {
  17645. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  17646. }
  17647. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  17648. return null;
  17649. }
  17650. var texture;
  17651. if (parsedTexture.mirrorPlane) {
  17652. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  17653. texture._waitingRenderList = parsedTexture.renderList;
  17654. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  17655. }
  17656. else if (parsedTexture.isRenderTarget) {
  17657. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  17658. texture._waitingRenderList = parsedTexture.renderList;
  17659. }
  17660. else {
  17661. if (parsedTexture.base64String) {
  17662. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  17663. }
  17664. else {
  17665. texture = new Texture(rootUrl + parsedTexture.name, scene);
  17666. }
  17667. }
  17668. texture.name = parsedTexture.name;
  17669. texture.hasAlpha = parsedTexture.hasAlpha;
  17670. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  17671. texture.level = parsedTexture.level;
  17672. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  17673. texture.coordinatesMode = parsedTexture.coordinatesMode;
  17674. texture.uOffset = parsedTexture.uOffset;
  17675. texture.vOffset = parsedTexture.vOffset;
  17676. texture.uScale = parsedTexture.uScale;
  17677. texture.vScale = parsedTexture.vScale;
  17678. texture.uAng = parsedTexture.uAng;
  17679. texture.vAng = parsedTexture.vAng;
  17680. texture.wAng = parsedTexture.wAng;
  17681. texture.wrapU = parsedTexture.wrapU;
  17682. texture.wrapV = parsedTexture.wrapV;
  17683. // Animations
  17684. if (parsedTexture.animations) {
  17685. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  17686. var parsedAnimation = parsedTexture.animations[animationIndex];
  17687. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  17688. }
  17689. }
  17690. return texture;
  17691. };
  17692. // Constants
  17693. Texture.NEAREST_SAMPLINGMODE = 1;
  17694. Texture.BILINEAR_SAMPLINGMODE = 2;
  17695. Texture.TRILINEAR_SAMPLINGMODE = 3;
  17696. Texture.EXPLICIT_MODE = 0;
  17697. Texture.SPHERICAL_MODE = 1;
  17698. Texture.PLANAR_MODE = 2;
  17699. Texture.CUBIC_MODE = 3;
  17700. Texture.PROJECTION_MODE = 4;
  17701. Texture.SKYBOX_MODE = 5;
  17702. Texture.INVCUBIC_MODE = 6;
  17703. Texture.EQUIRECTANGULAR_MODE = 7;
  17704. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  17705. Texture.CLAMP_ADDRESSMODE = 0;
  17706. Texture.WRAP_ADDRESSMODE = 1;
  17707. Texture.MIRROR_ADDRESSMODE = 2;
  17708. return Texture;
  17709. })(BABYLON.BaseTexture);
  17710. BABYLON.Texture = Texture;
  17711. })(BABYLON || (BABYLON = {}));
  17712. var BABYLON;
  17713. (function (BABYLON) {
  17714. var CubeTexture = (function (_super) {
  17715. __extends(CubeTexture, _super);
  17716. function CubeTexture(rootUrl, scene, extensions, noMipmap, files) {
  17717. _super.call(this, scene);
  17718. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  17719. this.name = rootUrl;
  17720. this.url = rootUrl;
  17721. this._noMipmap = noMipmap;
  17722. this.hasAlpha = false;
  17723. if (!rootUrl && !files) {
  17724. return;
  17725. }
  17726. this._texture = this._getFromCache(rootUrl, noMipmap);
  17727. if (!files) {
  17728. if (!extensions) {
  17729. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  17730. }
  17731. files = [];
  17732. for (var index = 0; index < extensions.length; index++) {
  17733. files.push(rootUrl + extensions[index]);
  17734. }
  17735. this._extensions = extensions;
  17736. }
  17737. this._files = files;
  17738. if (!this._texture) {
  17739. if (!scene.useDelayedTextureLoading) {
  17740. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap);
  17741. }
  17742. else {
  17743. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  17744. }
  17745. }
  17746. this.isCube = true;
  17747. this._textureMatrix = BABYLON.Matrix.Identity();
  17748. }
  17749. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  17750. return new CubeTexture("", scene, null, noMipmap, files);
  17751. };
  17752. CubeTexture.prototype.clone = function () {
  17753. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap, this._files);
  17754. // Base texture
  17755. newTexture.level = this.level;
  17756. newTexture.wrapU = this.wrapU;
  17757. newTexture.wrapV = this.wrapV;
  17758. newTexture.coordinatesIndex = this.coordinatesIndex;
  17759. newTexture.coordinatesMode = this.coordinatesMode;
  17760. return newTexture;
  17761. };
  17762. // Methods
  17763. CubeTexture.prototype.delayLoad = function () {
  17764. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  17765. return;
  17766. }
  17767. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  17768. this._texture = this._getFromCache(this.url, this._noMipmap);
  17769. if (!this._texture) {
  17770. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  17771. }
  17772. };
  17773. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  17774. return this._textureMatrix;
  17775. };
  17776. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  17777. var texture = null;
  17778. if ((parsedTexture.name || parsedTexture.extensions) && !parsedTexture.isRenderTarget) {
  17779. texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  17780. texture.name = parsedTexture.name;
  17781. texture.hasAlpha = parsedTexture.hasAlpha;
  17782. texture.level = parsedTexture.level;
  17783. texture.coordinatesMode = parsedTexture.coordinatesMode;
  17784. }
  17785. return texture;
  17786. };
  17787. CubeTexture.prototype.serialize = function () {
  17788. if (!this.name) {
  17789. return null;
  17790. }
  17791. var serializationObject = {};
  17792. serializationObject.name = this.name;
  17793. serializationObject.hasAlpha = this.hasAlpha;
  17794. serializationObject.isCube = true;
  17795. serializationObject.level = this.level;
  17796. serializationObject.coordinatesMode = this.coordinatesMode;
  17797. return serializationObject;
  17798. };
  17799. return CubeTexture;
  17800. })(BABYLON.BaseTexture);
  17801. BABYLON.CubeTexture = CubeTexture;
  17802. })(BABYLON || (BABYLON = {}));
  17803. var BABYLON;
  17804. (function (BABYLON) {
  17805. var RenderTargetTexture = (function (_super) {
  17806. __extends(RenderTargetTexture, _super);
  17807. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube) {
  17808. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  17809. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  17810. if (isCube === void 0) { isCube = false; }
  17811. _super.call(this, null, scene, !generateMipMaps);
  17812. this.isCube = isCube;
  17813. this.renderList = new Array();
  17814. this.renderParticles = true;
  17815. this.renderSprites = false;
  17816. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  17817. this._currentRefreshId = -1;
  17818. this._refreshRate = 1;
  17819. this.name = name;
  17820. this.isRenderTarget = true;
  17821. this._size = size;
  17822. this._generateMipMaps = generateMipMaps;
  17823. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  17824. if (isCube) {
  17825. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  17826. this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  17827. this._textureMatrix = BABYLON.Matrix.Identity();
  17828. }
  17829. else {
  17830. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  17831. }
  17832. // Rendering groups
  17833. this._renderingManager = new BABYLON.RenderingManager(scene);
  17834. }
  17835. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  17836. get: function () {
  17837. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  17838. },
  17839. enumerable: true,
  17840. configurable: true
  17841. });
  17842. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  17843. get: function () {
  17844. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  17845. },
  17846. enumerable: true,
  17847. configurable: true
  17848. });
  17849. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  17850. get: function () {
  17851. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  17852. },
  17853. enumerable: true,
  17854. configurable: true
  17855. });
  17856. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  17857. this._currentRefreshId = -1;
  17858. };
  17859. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  17860. get: function () {
  17861. return this._refreshRate;
  17862. },
  17863. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  17864. set: function (value) {
  17865. this._refreshRate = value;
  17866. this.resetRefreshCounter();
  17867. },
  17868. enumerable: true,
  17869. configurable: true
  17870. });
  17871. RenderTargetTexture.prototype._shouldRender = function () {
  17872. if (this._currentRefreshId === -1) {
  17873. this._currentRefreshId = 1;
  17874. return true;
  17875. }
  17876. if (this.refreshRate === this._currentRefreshId) {
  17877. this._currentRefreshId = 1;
  17878. return true;
  17879. }
  17880. this._currentRefreshId++;
  17881. return false;
  17882. };
  17883. RenderTargetTexture.prototype.isReady = function () {
  17884. if (!this.getScene().renderTargetsEnabled) {
  17885. return false;
  17886. }
  17887. return _super.prototype.isReady.call(this);
  17888. };
  17889. RenderTargetTexture.prototype.getRenderSize = function () {
  17890. return this._size;
  17891. };
  17892. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  17893. get: function () {
  17894. return true;
  17895. },
  17896. enumerable: true,
  17897. configurable: true
  17898. });
  17899. RenderTargetTexture.prototype.scale = function (ratio) {
  17900. var newSize = this._size * ratio;
  17901. this.resize(newSize, this._generateMipMaps);
  17902. };
  17903. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  17904. if (this.isCube) {
  17905. return this._textureMatrix;
  17906. }
  17907. return _super.prototype.getReflectionTextureMatrix.call(this);
  17908. };
  17909. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  17910. this.releaseInternalTexture();
  17911. if (this.isCube) {
  17912. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
  17913. }
  17914. else {
  17915. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  17916. }
  17917. };
  17918. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  17919. var scene = this.getScene();
  17920. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  17921. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  17922. }
  17923. if (this._waitingRenderList) {
  17924. this.renderList = [];
  17925. for (var index = 0; index < this._waitingRenderList.length; index++) {
  17926. var id = this._waitingRenderList[index];
  17927. this.renderList.push(scene.getMeshByID(id));
  17928. }
  17929. delete this._waitingRenderList;
  17930. }
  17931. if (this.renderList && this.renderList.length === 0) {
  17932. return;
  17933. }
  17934. // Prepare renderingManager
  17935. this._renderingManager.reset();
  17936. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  17937. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  17938. var mesh = currentRenderList[meshIndex];
  17939. if (mesh) {
  17940. if (!mesh.isReady()) {
  17941. // Reset _currentRefreshId
  17942. this.resetRefreshCounter();
  17943. continue;
  17944. }
  17945. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  17946. mesh._activate(scene.getRenderId());
  17947. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  17948. var subMesh = mesh.subMeshes[subIndex];
  17949. scene._activeIndices += subMesh.indexCount;
  17950. this._renderingManager.dispatch(subMesh);
  17951. }
  17952. }
  17953. }
  17954. }
  17955. if (this.isCube) {
  17956. for (var face = 0; face < 6; face++) {
  17957. this.renderToTarget(face, currentRenderList, useCameraPostProcess, dumpForDebug);
  17958. scene.incrementRenderId();
  17959. }
  17960. }
  17961. else {
  17962. this.renderToTarget(0, currentRenderList, useCameraPostProcess, dumpForDebug);
  17963. }
  17964. if (this.onAfterUnbind) {
  17965. this.onAfterUnbind();
  17966. }
  17967. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  17968. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  17969. }
  17970. scene.resetCachedMaterial();
  17971. };
  17972. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, useCameraPostProcess, dumpForDebug) {
  17973. var scene = this.getScene();
  17974. var engine = scene.getEngine();
  17975. // Bind
  17976. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  17977. if (this.isCube) {
  17978. engine.bindFramebuffer(this._texture, faceIndex);
  17979. }
  17980. else {
  17981. engine.bindFramebuffer(this._texture);
  17982. }
  17983. }
  17984. if (this.onBeforeRender) {
  17985. this.onBeforeRender(faceIndex);
  17986. }
  17987. // Clear
  17988. if (this.onClear) {
  17989. this.onClear(engine);
  17990. }
  17991. else {
  17992. engine.clear(scene.clearColor, true, true);
  17993. }
  17994. if (!this._doNotChangeAspectRatio) {
  17995. scene.updateTransformMatrix(true);
  17996. }
  17997. // Render
  17998. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  17999. if (useCameraPostProcess) {
  18000. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  18001. }
  18002. if (!this._doNotChangeAspectRatio) {
  18003. scene.updateTransformMatrix(true);
  18004. }
  18005. if (this.onAfterRender) {
  18006. this.onAfterRender(faceIndex);
  18007. }
  18008. // Dump ?
  18009. if (dumpForDebug) {
  18010. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  18011. }
  18012. // Unbind
  18013. if (!this.isCube || faceIndex === 5) {
  18014. if (this.isCube) {
  18015. if (faceIndex === 5) {
  18016. engine.generateMipMapsForCubemap(this._texture);
  18017. }
  18018. }
  18019. engine.unBindFramebuffer(this._texture, this.isCube);
  18020. }
  18021. };
  18022. RenderTargetTexture.prototype.clone = function () {
  18023. var textureSize = this.getSize();
  18024. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  18025. // Base texture
  18026. newTexture.hasAlpha = this.hasAlpha;
  18027. newTexture.level = this.level;
  18028. // RenderTarget Texture
  18029. newTexture.coordinatesMode = this.coordinatesMode;
  18030. newTexture.renderList = this.renderList.slice(0);
  18031. return newTexture;
  18032. };
  18033. RenderTargetTexture.prototype.serialize = function () {
  18034. if (!this.name) {
  18035. return null;
  18036. }
  18037. var serializationObject = _super.prototype.serialize.call(this);
  18038. serializationObject.renderTargetSize = this.getRenderSize();
  18039. serializationObject.renderList = [];
  18040. for (var index = 0; index < this.renderList.length; index++) {
  18041. serializationObject.renderList.push(this.renderList[index].id);
  18042. }
  18043. return serializationObject;
  18044. };
  18045. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  18046. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  18047. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  18048. return RenderTargetTexture;
  18049. })(BABYLON.Texture);
  18050. BABYLON.RenderTargetTexture = RenderTargetTexture;
  18051. })(BABYLON || (BABYLON = {}));
  18052. var BABYLON;
  18053. (function (BABYLON) {
  18054. var ProceduralTexture = (function (_super) {
  18055. __extends(ProceduralTexture, _super);
  18056. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  18057. if (generateMipMaps === void 0) { generateMipMaps = true; }
  18058. if (isCube === void 0) { isCube = false; }
  18059. _super.call(this, null, scene, !generateMipMaps);
  18060. this.isCube = isCube;
  18061. this.isEnabled = true;
  18062. this._currentRefreshId = -1;
  18063. this._refreshRate = 1;
  18064. this._vertexDeclaration = [2];
  18065. this._vertexStrideSize = 2 * 4;
  18066. this._uniforms = new Array();
  18067. this._samplers = new Array();
  18068. this._textures = new Array();
  18069. this._floats = new Array();
  18070. this._floatsArrays = {};
  18071. this._colors3 = new Array();
  18072. this._colors4 = new Array();
  18073. this._vectors2 = new Array();
  18074. this._vectors3 = new Array();
  18075. this._matrices = new Array();
  18076. this._fallbackTextureUsed = false;
  18077. scene._proceduralTextures.push(this);
  18078. this.name = name;
  18079. this.isRenderTarget = true;
  18080. this._size = size;
  18081. this._generateMipMaps = generateMipMaps;
  18082. this.setFragment(fragment);
  18083. this._fallbackTexture = fallbackTexture;
  18084. if (isCube) {
  18085. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  18086. this.setFloat("face", 0);
  18087. }
  18088. else {
  18089. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  18090. }
  18091. // VBO
  18092. var vertices = [];
  18093. vertices.push(1, 1);
  18094. vertices.push(-1, 1);
  18095. vertices.push(-1, -1);
  18096. vertices.push(1, -1);
  18097. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  18098. // Indices
  18099. var indices = [];
  18100. indices.push(0);
  18101. indices.push(1);
  18102. indices.push(2);
  18103. indices.push(0);
  18104. indices.push(2);
  18105. indices.push(3);
  18106. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  18107. }
  18108. ProceduralTexture.prototype.reset = function () {
  18109. if (this._effect === undefined) {
  18110. return;
  18111. }
  18112. var engine = this.getScene().getEngine();
  18113. engine._releaseEffect(this._effect);
  18114. };
  18115. ProceduralTexture.prototype.isReady = function () {
  18116. var _this = this;
  18117. var engine = this.getScene().getEngine();
  18118. var shaders;
  18119. if (!this._fragment) {
  18120. return false;
  18121. }
  18122. if (this._fallbackTextureUsed) {
  18123. return true;
  18124. }
  18125. if (this._fragment.fragmentElement !== undefined) {
  18126. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  18127. }
  18128. else {
  18129. shaders = { vertex: "procedural", fragment: this._fragment };
  18130. }
  18131. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  18132. _this.releaseInternalTexture();
  18133. if (_this._fallbackTexture) {
  18134. _this._texture = _this._fallbackTexture._texture;
  18135. _this._texture.references++;
  18136. }
  18137. _this._fallbackTextureUsed = true;
  18138. });
  18139. return this._effect.isReady();
  18140. };
  18141. ProceduralTexture.prototype.resetRefreshCounter = function () {
  18142. this._currentRefreshId = -1;
  18143. };
  18144. ProceduralTexture.prototype.setFragment = function (fragment) {
  18145. this._fragment = fragment;
  18146. };
  18147. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  18148. get: function () {
  18149. return this._refreshRate;
  18150. },
  18151. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  18152. set: function (value) {
  18153. this._refreshRate = value;
  18154. this.resetRefreshCounter();
  18155. },
  18156. enumerable: true,
  18157. configurable: true
  18158. });
  18159. ProceduralTexture.prototype._shouldRender = function () {
  18160. if (!this.isEnabled || !this.isReady() || !this._texture) {
  18161. return false;
  18162. }
  18163. if (this._fallbackTextureUsed) {
  18164. return false;
  18165. }
  18166. if (this._currentRefreshId === -1) {
  18167. this._currentRefreshId = 1;
  18168. return true;
  18169. }
  18170. if (this.refreshRate === this._currentRefreshId) {
  18171. this._currentRefreshId = 1;
  18172. return true;
  18173. }
  18174. this._currentRefreshId++;
  18175. return false;
  18176. };
  18177. ProceduralTexture.prototype.getRenderSize = function () {
  18178. return this._size;
  18179. };
  18180. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  18181. if (this._fallbackTextureUsed) {
  18182. return;
  18183. }
  18184. this.releaseInternalTexture();
  18185. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  18186. };
  18187. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  18188. if (this._uniforms.indexOf(uniformName) === -1) {
  18189. this._uniforms.push(uniformName);
  18190. }
  18191. };
  18192. ProceduralTexture.prototype.setTexture = function (name, texture) {
  18193. if (this._samplers.indexOf(name) === -1) {
  18194. this._samplers.push(name);
  18195. }
  18196. this._textures[name] = texture;
  18197. return this;
  18198. };
  18199. ProceduralTexture.prototype.setFloat = function (name, value) {
  18200. this._checkUniform(name);
  18201. this._floats[name] = value;
  18202. return this;
  18203. };
  18204. ProceduralTexture.prototype.setFloats = function (name, value) {
  18205. this._checkUniform(name);
  18206. this._floatsArrays[name] = value;
  18207. return this;
  18208. };
  18209. ProceduralTexture.prototype.setColor3 = function (name, value) {
  18210. this._checkUniform(name);
  18211. this._colors3[name] = value;
  18212. return this;
  18213. };
  18214. ProceduralTexture.prototype.setColor4 = function (name, value) {
  18215. this._checkUniform(name);
  18216. this._colors4[name] = value;
  18217. return this;
  18218. };
  18219. ProceduralTexture.prototype.setVector2 = function (name, value) {
  18220. this._checkUniform(name);
  18221. this._vectors2[name] = value;
  18222. return this;
  18223. };
  18224. ProceduralTexture.prototype.setVector3 = function (name, value) {
  18225. this._checkUniform(name);
  18226. this._vectors3[name] = value;
  18227. return this;
  18228. };
  18229. ProceduralTexture.prototype.setMatrix = function (name, value) {
  18230. this._checkUniform(name);
  18231. this._matrices[name] = value;
  18232. return this;
  18233. };
  18234. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  18235. var scene = this.getScene();
  18236. var engine = scene.getEngine();
  18237. // Render
  18238. engine.enableEffect(this._effect);
  18239. engine.setState(false);
  18240. // Texture
  18241. for (var name in this._textures) {
  18242. this._effect.setTexture(name, this._textures[name]);
  18243. }
  18244. // Float
  18245. for (name in this._floats) {
  18246. this._effect.setFloat(name, this._floats[name]);
  18247. }
  18248. // Floats
  18249. for (name in this._floatsArrays) {
  18250. this._effect.setArray(name, this._floatsArrays[name]);
  18251. }
  18252. // Color3
  18253. for (name in this._colors3) {
  18254. this._effect.setColor3(name, this._colors3[name]);
  18255. }
  18256. // Color4
  18257. for (name in this._colors4) {
  18258. var color = this._colors4[name];
  18259. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  18260. }
  18261. // Vector2
  18262. for (name in this._vectors2) {
  18263. this._effect.setVector2(name, this._vectors2[name]);
  18264. }
  18265. // Vector3
  18266. for (name in this._vectors3) {
  18267. this._effect.setVector3(name, this._vectors3[name]);
  18268. }
  18269. // Matrix
  18270. for (name in this._matrices) {
  18271. this._effect.setMatrix(name, this._matrices[name]);
  18272. }
  18273. // VBOs
  18274. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  18275. if (this.isCube) {
  18276. for (var face = 0; face < 6; face++) {
  18277. engine.bindFramebuffer(this._texture, face);
  18278. this._effect.setFloat("face", face);
  18279. // Clear
  18280. engine.clear(scene.clearColor, true, true);
  18281. // Draw order
  18282. engine.draw(true, 0, 6);
  18283. // Mipmaps
  18284. if (face === 5) {
  18285. engine.generateMipMapsForCubemap(this._texture);
  18286. }
  18287. }
  18288. }
  18289. else {
  18290. engine.bindFramebuffer(this._texture);
  18291. // Clear
  18292. engine.clear(scene.clearColor, true, true);
  18293. // Draw order
  18294. engine.draw(true, 0, 6);
  18295. }
  18296. // Unbind
  18297. engine.unBindFramebuffer(this._texture, this.isCube);
  18298. if (this.onGenerated) {
  18299. this.onGenerated();
  18300. }
  18301. };
  18302. ProceduralTexture.prototype.clone = function () {
  18303. var textureSize = this.getSize();
  18304. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  18305. // Base texture
  18306. newTexture.hasAlpha = this.hasAlpha;
  18307. newTexture.level = this.level;
  18308. // RenderTarget Texture
  18309. newTexture.coordinatesMode = this.coordinatesMode;
  18310. return newTexture;
  18311. };
  18312. ProceduralTexture.prototype.dispose = function () {
  18313. var index = this.getScene()._proceduralTextures.indexOf(this);
  18314. if (index >= 0) {
  18315. this.getScene()._proceduralTextures.splice(index, 1);
  18316. }
  18317. _super.prototype.dispose.call(this);
  18318. };
  18319. return ProceduralTexture;
  18320. })(BABYLON.Texture);
  18321. BABYLON.ProceduralTexture = ProceduralTexture;
  18322. })(BABYLON || (BABYLON = {}));
  18323. var BABYLON;
  18324. (function (BABYLON) {
  18325. var MirrorTexture = (function (_super) {
  18326. __extends(MirrorTexture, _super);
  18327. function MirrorTexture(name, size, scene, generateMipMaps) {
  18328. var _this = this;
  18329. _super.call(this, name, size, scene, generateMipMaps, true);
  18330. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  18331. this._transformMatrix = BABYLON.Matrix.Zero();
  18332. this._mirrorMatrix = BABYLON.Matrix.Zero();
  18333. this.onBeforeRender = function () {
  18334. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  18335. _this._savedViewMatrix = scene.getViewMatrix();
  18336. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  18337. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  18338. scene.clipPlane = _this.mirrorPlane;
  18339. scene.getEngine().cullBackFaces = false;
  18340. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  18341. };
  18342. this.onAfterRender = function () {
  18343. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  18344. scene.getEngine().cullBackFaces = true;
  18345. scene._mirroredCameraPosition = null;
  18346. delete scene.clipPlane;
  18347. };
  18348. }
  18349. MirrorTexture.prototype.clone = function () {
  18350. var textureSize = this.getSize();
  18351. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  18352. // Base texture
  18353. newTexture.hasAlpha = this.hasAlpha;
  18354. newTexture.level = this.level;
  18355. // Mirror Texture
  18356. newTexture.mirrorPlane = this.mirrorPlane.clone();
  18357. newTexture.renderList = this.renderList.slice(0);
  18358. return newTexture;
  18359. };
  18360. MirrorTexture.prototype.serialize = function () {
  18361. if (!this.name) {
  18362. return null;
  18363. }
  18364. var serializationObject = _super.prototype.serialize.call(this);
  18365. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  18366. return serializationObject;
  18367. };
  18368. return MirrorTexture;
  18369. })(BABYLON.RenderTargetTexture);
  18370. BABYLON.MirrorTexture = MirrorTexture;
  18371. })(BABYLON || (BABYLON = {}));
  18372. var BABYLON;
  18373. (function (BABYLON) {
  18374. /**
  18375. * Creates a refraction texture used by refraction channel of the standard material.
  18376. * @param name the texture name
  18377. * @param size size of the underlying texture
  18378. * @param scene root scene
  18379. */
  18380. var RefractionTexture = (function (_super) {
  18381. __extends(RefractionTexture, _super);
  18382. function RefractionTexture(name, size, scene, generateMipMaps) {
  18383. var _this = this;
  18384. _super.call(this, name, size, scene, generateMipMaps, true);
  18385. this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  18386. this.depth = 2.0;
  18387. this.onBeforeRender = function () {
  18388. scene.clipPlane = _this.refractionPlane;
  18389. };
  18390. this.onAfterRender = function () {
  18391. delete scene.clipPlane;
  18392. };
  18393. }
  18394. RefractionTexture.prototype.clone = function () {
  18395. var textureSize = this.getSize();
  18396. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  18397. // Base texture
  18398. newTexture.hasAlpha = this.hasAlpha;
  18399. newTexture.level = this.level;
  18400. // Refraction Texture
  18401. newTexture.refractionPlane = this.refractionPlane.clone();
  18402. newTexture.renderList = this.renderList.slice(0);
  18403. newTexture.depth = this.depth;
  18404. return newTexture;
  18405. };
  18406. RefractionTexture.prototype.serialize = function () {
  18407. if (!this.name) {
  18408. return null;
  18409. }
  18410. var serializationObject = _super.prototype.serialize.call(this);
  18411. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  18412. serializationObject.depth = this.depth;
  18413. return serializationObject;
  18414. };
  18415. return RefractionTexture;
  18416. })(BABYLON.RenderTargetTexture);
  18417. BABYLON.RefractionTexture = RefractionTexture;
  18418. })(BABYLON || (BABYLON = {}));
  18419. var BABYLON;
  18420. (function (BABYLON) {
  18421. var DynamicTexture = (function (_super) {
  18422. __extends(DynamicTexture, _super);
  18423. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  18424. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  18425. _super.call(this, null, scene, !generateMipMaps);
  18426. this.name = name;
  18427. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  18428. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  18429. this._generateMipMaps = generateMipMaps;
  18430. if (options.getContext) {
  18431. this._canvas = options;
  18432. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  18433. }
  18434. else {
  18435. this._canvas = document.createElement("canvas");
  18436. if (options.width) {
  18437. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  18438. }
  18439. else {
  18440. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  18441. }
  18442. }
  18443. var textureSize = this.getSize();
  18444. this._canvas.width = textureSize.width;
  18445. this._canvas.height = textureSize.height;
  18446. this._context = this._canvas.getContext("2d");
  18447. }
  18448. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  18449. get: function () {
  18450. return true;
  18451. },
  18452. enumerable: true,
  18453. configurable: true
  18454. });
  18455. DynamicTexture.prototype.scale = function (ratio) {
  18456. var textureSize = this.getSize();
  18457. textureSize.width *= ratio;
  18458. textureSize.height *= ratio;
  18459. this._canvas.width = textureSize.width;
  18460. this._canvas.height = textureSize.height;
  18461. this.releaseInternalTexture();
  18462. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  18463. };
  18464. DynamicTexture.prototype.getContext = function () {
  18465. return this._context;
  18466. };
  18467. DynamicTexture.prototype.clear = function () {
  18468. var size = this.getSize();
  18469. this._context.fillRect(0, 0, size.width, size.height);
  18470. };
  18471. DynamicTexture.prototype.update = function (invertY) {
  18472. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  18473. };
  18474. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  18475. if (update === void 0) { update = true; }
  18476. var size = this.getSize();
  18477. if (clearColor) {
  18478. this._context.fillStyle = clearColor;
  18479. this._context.fillRect(0, 0, size.width, size.height);
  18480. }
  18481. this._context.font = font;
  18482. if (x === null) {
  18483. var textSize = this._context.measureText(text);
  18484. x = (size.width - textSize.width) / 2;
  18485. }
  18486. this._context.fillStyle = color;
  18487. this._context.fillText(text, x, y);
  18488. if (update) {
  18489. this.update(invertY);
  18490. }
  18491. };
  18492. DynamicTexture.prototype.clone = function () {
  18493. var textureSize = this.getSize();
  18494. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  18495. // Base texture
  18496. newTexture.hasAlpha = this.hasAlpha;
  18497. newTexture.level = this.level;
  18498. // Dynamic Texture
  18499. newTexture.wrapU = this.wrapU;
  18500. newTexture.wrapV = this.wrapV;
  18501. return newTexture;
  18502. };
  18503. return DynamicTexture;
  18504. })(BABYLON.Texture);
  18505. BABYLON.DynamicTexture = DynamicTexture;
  18506. })(BABYLON || (BABYLON = {}));
  18507. var BABYLON;
  18508. (function (BABYLON) {
  18509. var VideoTexture = (function (_super) {
  18510. __extends(VideoTexture, _super);
  18511. function VideoTexture(name, urls, scene, generateMipMaps, invertY, samplingMode) {
  18512. var _this = this;
  18513. if (generateMipMaps === void 0) { generateMipMaps = false; }
  18514. if (invertY === void 0) { invertY = false; }
  18515. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  18516. _super.call(this, null, scene, !generateMipMaps, invertY);
  18517. this._autoLaunch = true;
  18518. this.name = name;
  18519. this.video = document.createElement("video");
  18520. this.video.autoplay = false;
  18521. this.video.loop = true;
  18522. this.video.addEventListener("canplaythrough", function () {
  18523. if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
  18524. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  18525. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  18526. }
  18527. else {
  18528. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  18529. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  18530. generateMipMaps = false;
  18531. }
  18532. _this._texture = scene.getEngine().createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, generateMipMaps, samplingMode, false);
  18533. _this._texture.isReady = true;
  18534. });
  18535. urls.forEach(function (url) {
  18536. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  18537. var source = document.createElement("source");
  18538. source.src = url;
  18539. _this.video.appendChild(source);
  18540. });
  18541. this._lastUpdate = BABYLON.Tools.Now;
  18542. }
  18543. VideoTexture.prototype.update = function () {
  18544. if (this._autoLaunch) {
  18545. this._autoLaunch = false;
  18546. this.video.play();
  18547. }
  18548. var now = BABYLON.Tools.Now;
  18549. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  18550. return false;
  18551. }
  18552. this._lastUpdate = now;
  18553. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  18554. return true;
  18555. };
  18556. return VideoTexture;
  18557. })(BABYLON.Texture);
  18558. BABYLON.VideoTexture = VideoTexture;
  18559. })(BABYLON || (BABYLON = {}));
  18560. var BABYLON;
  18561. (function (BABYLON) {
  18562. var CustomProceduralTexture = (function (_super) {
  18563. __extends(CustomProceduralTexture, _super);
  18564. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  18565. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  18566. this._animate = true;
  18567. this._time = 0;
  18568. this._texturePath = texturePath;
  18569. //Try to load json
  18570. this.loadJson(texturePath);
  18571. this.refreshRate = 1;
  18572. }
  18573. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  18574. var _this = this;
  18575. var that = this;
  18576. function noConfigFile() {
  18577. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  18578. try {
  18579. that.setFragment(that._texturePath);
  18580. }
  18581. catch (ex) {
  18582. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  18583. }
  18584. }
  18585. var configFileUrl = jsonUrl + "/config.json";
  18586. var xhr = new XMLHttpRequest();
  18587. xhr.open("GET", configFileUrl, true);
  18588. xhr.addEventListener("load", function () {
  18589. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  18590. try {
  18591. _this._config = JSON.parse(xhr.response);
  18592. _this.updateShaderUniforms();
  18593. _this.updateTextures();
  18594. _this.setFragment(_this._texturePath + "/custom");
  18595. _this._animate = _this._config.animate;
  18596. _this.refreshRate = _this._config.refreshrate;
  18597. }
  18598. catch (ex) {
  18599. noConfigFile();
  18600. }
  18601. }
  18602. else {
  18603. noConfigFile();
  18604. }
  18605. }, false);
  18606. xhr.addEventListener("error", function () {
  18607. noConfigFile();
  18608. }, false);
  18609. try {
  18610. xhr.send();
  18611. }
  18612. catch (ex) {
  18613. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  18614. }
  18615. };
  18616. CustomProceduralTexture.prototype.isReady = function () {
  18617. if (!_super.prototype.isReady.call(this)) {
  18618. return false;
  18619. }
  18620. for (var name in this._textures) {
  18621. var texture = this._textures[name];
  18622. if (!texture.isReady()) {
  18623. return false;
  18624. }
  18625. }
  18626. return true;
  18627. };
  18628. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  18629. if (this._animate) {
  18630. this._time += this.getScene().getAnimationRatio() * 0.03;
  18631. this.updateShaderUniforms();
  18632. }
  18633. _super.prototype.render.call(this, useCameraPostProcess);
  18634. };
  18635. CustomProceduralTexture.prototype.updateTextures = function () {
  18636. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  18637. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  18638. }
  18639. };
  18640. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  18641. if (this._config) {
  18642. for (var j = 0; j < this._config.uniforms.length; j++) {
  18643. var uniform = this._config.uniforms[j];
  18644. switch (uniform.type) {
  18645. case "float":
  18646. this.setFloat(uniform.name, uniform.value);
  18647. break;
  18648. case "color3":
  18649. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  18650. break;
  18651. case "color4":
  18652. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  18653. break;
  18654. case "vector2":
  18655. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  18656. break;
  18657. case "vector3":
  18658. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  18659. break;
  18660. }
  18661. }
  18662. }
  18663. this.setFloat("time", this._time);
  18664. };
  18665. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  18666. get: function () {
  18667. return this._animate;
  18668. },
  18669. set: function (value) {
  18670. this._animate = value;
  18671. },
  18672. enumerable: true,
  18673. configurable: true
  18674. });
  18675. return CustomProceduralTexture;
  18676. })(BABYLON.ProceduralTexture);
  18677. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  18678. })(BABYLON || (BABYLON = {}));
  18679. var BABYLON;
  18680. (function (BABYLON) {
  18681. var EffectFallbacks = (function () {
  18682. function EffectFallbacks() {
  18683. this._defines = {};
  18684. this._currentRank = 32;
  18685. this._maxRank = -1;
  18686. }
  18687. EffectFallbacks.prototype.addFallback = function (rank, define) {
  18688. if (!this._defines[rank]) {
  18689. if (rank < this._currentRank) {
  18690. this._currentRank = rank;
  18691. }
  18692. if (rank > this._maxRank) {
  18693. this._maxRank = rank;
  18694. }
  18695. this._defines[rank] = new Array();
  18696. }
  18697. this._defines[rank].push(define);
  18698. };
  18699. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  18700. this._meshRank = rank;
  18701. this._mesh = mesh;
  18702. if (rank > this._maxRank) {
  18703. this._maxRank = rank;
  18704. }
  18705. };
  18706. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  18707. get: function () {
  18708. return this._currentRank <= this._maxRank;
  18709. },
  18710. enumerable: true,
  18711. configurable: true
  18712. });
  18713. EffectFallbacks.prototype.reduce = function (currentDefines) {
  18714. var currentFallbacks = this._defines[this._currentRank];
  18715. for (var index = 0; index < currentFallbacks.length; index++) {
  18716. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  18717. }
  18718. if (this._mesh && this._currentRank === this._meshRank) {
  18719. this._mesh.computeBonesUsingShaders = false;
  18720. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  18721. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  18722. }
  18723. this._currentRank++;
  18724. return currentDefines;
  18725. };
  18726. return EffectFallbacks;
  18727. })();
  18728. BABYLON.EffectFallbacks = EffectFallbacks;
  18729. var Effect = (function () {
  18730. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  18731. var _this = this;
  18732. this._isReady = false;
  18733. this._compilationError = "";
  18734. this._valueCache = [];
  18735. this._engine = engine;
  18736. this.name = baseName;
  18737. this.defines = defines;
  18738. this._uniformsNames = uniformsNames.concat(samplers);
  18739. this._samplers = samplers;
  18740. this._attributesNames = attributesNames;
  18741. this.onError = onError;
  18742. this.onCompiled = onCompiled;
  18743. var vertexSource;
  18744. var fragmentSource;
  18745. if (baseName.vertexElement) {
  18746. vertexSource = document.getElementById(baseName.vertexElement);
  18747. if (!vertexSource) {
  18748. vertexSource = baseName.vertexElement;
  18749. }
  18750. }
  18751. else {
  18752. vertexSource = baseName.vertex || baseName;
  18753. }
  18754. if (baseName.fragmentElement) {
  18755. fragmentSource = document.getElementById(baseName.fragmentElement);
  18756. if (!fragmentSource) {
  18757. fragmentSource = baseName.fragmentElement;
  18758. }
  18759. }
  18760. else {
  18761. fragmentSource = baseName.fragment || baseName;
  18762. }
  18763. this._loadVertexShader(vertexSource, function (vertexCode) {
  18764. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  18765. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  18766. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  18767. _this._prepareEffect(vertexCodeWithIncludes, fragmentCodeWithIncludes, attributesNames, defines, fallbacks);
  18768. });
  18769. });
  18770. });
  18771. });
  18772. }
  18773. // Properties
  18774. Effect.prototype.isReady = function () {
  18775. return this._isReady;
  18776. };
  18777. Effect.prototype.getProgram = function () {
  18778. return this._program;
  18779. };
  18780. Effect.prototype.getAttributesNames = function () {
  18781. return this._attributesNames;
  18782. };
  18783. Effect.prototype.getAttributeLocation = function (index) {
  18784. return this._attributes[index];
  18785. };
  18786. Effect.prototype.getAttributeLocationByName = function (name) {
  18787. var index = this._attributesNames.indexOf(name);
  18788. return this._attributes[index];
  18789. };
  18790. Effect.prototype.getAttributesCount = function () {
  18791. return this._attributes.length;
  18792. };
  18793. Effect.prototype.getUniformIndex = function (uniformName) {
  18794. return this._uniformsNames.indexOf(uniformName);
  18795. };
  18796. Effect.prototype.getUniform = function (uniformName) {
  18797. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  18798. };
  18799. Effect.prototype.getSamplers = function () {
  18800. return this._samplers;
  18801. };
  18802. Effect.prototype.getCompilationError = function () {
  18803. return this._compilationError;
  18804. };
  18805. // Methods
  18806. Effect.prototype._loadVertexShader = function (vertex, callback) {
  18807. // DOM element ?
  18808. if (vertex instanceof HTMLElement) {
  18809. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  18810. callback(vertexCode);
  18811. return;
  18812. }
  18813. // Is in local store ?
  18814. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  18815. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  18816. return;
  18817. }
  18818. var vertexShaderUrl;
  18819. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  18820. vertexShaderUrl = vertex;
  18821. }
  18822. else {
  18823. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  18824. }
  18825. // Vertex shader
  18826. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  18827. };
  18828. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  18829. // DOM element ?
  18830. if (fragment instanceof HTMLElement) {
  18831. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  18832. callback(fragmentCode);
  18833. return;
  18834. }
  18835. // Is in local store ?
  18836. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  18837. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  18838. return;
  18839. }
  18840. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  18841. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  18842. return;
  18843. }
  18844. var fragmentShaderUrl;
  18845. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  18846. fragmentShaderUrl = fragment;
  18847. }
  18848. else {
  18849. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  18850. }
  18851. // Fragment shader
  18852. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  18853. };
  18854. Effect.prototype._dumpShadersName = function () {
  18855. if (this.name.vertexElement) {
  18856. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  18857. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  18858. }
  18859. else if (this.name.vertex) {
  18860. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  18861. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  18862. }
  18863. else {
  18864. BABYLON.Tools.Error("Vertex shader:" + this.name);
  18865. BABYLON.Tools.Error("Fragment shader:" + this.name);
  18866. }
  18867. };
  18868. Effect.prototype._processIncludes = function (sourceCode, callback) {
  18869. var _this = this;
  18870. var regex = /#include<(.+)>(\((.*)\))*/g;
  18871. var match = regex.exec(sourceCode);
  18872. var returnValue = new String(sourceCode);
  18873. while (match != null) {
  18874. var includeFile = match[1];
  18875. if (Effect.IncludesShadersStore[includeFile]) {
  18876. // Substitution
  18877. var includeContent = Effect.IncludesShadersStore[includeFile];
  18878. if (match[2]) {
  18879. var splits = match[2].substr(1, match[2].length - 2).split(",");
  18880. for (var index = 0; index < splits.length; index += 2) {
  18881. var source = new RegExp(splits[index], "g");
  18882. var dest = splits[index + 1];
  18883. includeContent = includeContent.replace(source, dest);
  18884. }
  18885. }
  18886. // Replace
  18887. returnValue = returnValue.replace(match[0], includeContent);
  18888. }
  18889. else {
  18890. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  18891. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  18892. Effect.IncludesShadersStore[includeFile] = fileContent;
  18893. _this._processIncludes(returnValue, callback);
  18894. });
  18895. return;
  18896. }
  18897. match = regex.exec(sourceCode);
  18898. }
  18899. callback(returnValue);
  18900. };
  18901. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  18902. try {
  18903. var engine = this._engine;
  18904. // Precision
  18905. if (!engine.getCaps().highPrecisionShaderSupported) {
  18906. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  18907. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  18908. }
  18909. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  18910. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  18911. this._attributes = engine.getAttributes(this._program, attributesNames);
  18912. for (var index = 0; index < this._samplers.length; index++) {
  18913. var sampler = this.getUniform(this._samplers[index]);
  18914. if (sampler == null) {
  18915. this._samplers.splice(index, 1);
  18916. index--;
  18917. }
  18918. }
  18919. engine.bindSamplers(this);
  18920. this._isReady = true;
  18921. if (this.onCompiled) {
  18922. this.onCompiled(this);
  18923. }
  18924. }
  18925. catch (e) {
  18926. // Is it a problem with precision?
  18927. if (e.message.indexOf("highp") !== -1) {
  18928. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  18929. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  18930. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  18931. return;
  18932. }
  18933. // Let's go through fallbacks then
  18934. if (fallbacks && fallbacks.isMoreFallbacks) {
  18935. BABYLON.Tools.Error("Unable to compile effect with current defines. Trying next fallback.");
  18936. this._dumpShadersName();
  18937. defines = fallbacks.reduce(defines);
  18938. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  18939. }
  18940. else {
  18941. BABYLON.Tools.Error("Unable to compile effect: ");
  18942. this._dumpShadersName();
  18943. BABYLON.Tools.Error("Defines: " + defines);
  18944. BABYLON.Tools.Error("Error: " + e.message);
  18945. this._compilationError = e.message;
  18946. if (this.onError) {
  18947. this.onError(this, this._compilationError);
  18948. }
  18949. }
  18950. }
  18951. };
  18952. Object.defineProperty(Effect.prototype, "isSupported", {
  18953. get: function () {
  18954. return this._compilationError === "";
  18955. },
  18956. enumerable: true,
  18957. configurable: true
  18958. });
  18959. Effect.prototype._bindTexture = function (channel, texture) {
  18960. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  18961. };
  18962. Effect.prototype.setTexture = function (channel, texture) {
  18963. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  18964. };
  18965. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  18966. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  18967. };
  18968. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  18969. if (!this._valueCache[uniformName]) {
  18970. this._valueCache[uniformName] = new BABYLON.Matrix();
  18971. }
  18972. for (var index = 0; index < 16; index++) {
  18973. this._valueCache[uniformName].m[index] = matrix.m[index];
  18974. }
  18975. };
  18976. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  18977. if (!this._valueCache[uniformName]) {
  18978. this._valueCache[uniformName] = [x, y];
  18979. return;
  18980. }
  18981. this._valueCache[uniformName][0] = x;
  18982. this._valueCache[uniformName][1] = y;
  18983. };
  18984. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  18985. if (!this._valueCache[uniformName]) {
  18986. this._valueCache[uniformName] = [x, y, z];
  18987. return;
  18988. }
  18989. this._valueCache[uniformName][0] = x;
  18990. this._valueCache[uniformName][1] = y;
  18991. this._valueCache[uniformName][2] = z;
  18992. };
  18993. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  18994. if (!this._valueCache[uniformName]) {
  18995. this._valueCache[uniformName] = [x, y, z, w];
  18996. return;
  18997. }
  18998. this._valueCache[uniformName][0] = x;
  18999. this._valueCache[uniformName][1] = y;
  19000. this._valueCache[uniformName][2] = z;
  19001. this._valueCache[uniformName][3] = w;
  19002. };
  19003. Effect.prototype.setArray = function (uniformName, array) {
  19004. this._engine.setArray(this.getUniform(uniformName), array);
  19005. return this;
  19006. };
  19007. Effect.prototype.setArray2 = function (uniformName, array) {
  19008. this._engine.setArray2(this.getUniform(uniformName), array);
  19009. return this;
  19010. };
  19011. Effect.prototype.setArray3 = function (uniformName, array) {
  19012. this._engine.setArray3(this.getUniform(uniformName), array);
  19013. return this;
  19014. };
  19015. Effect.prototype.setArray4 = function (uniformName, array) {
  19016. this._engine.setArray4(this.getUniform(uniformName), array);
  19017. return this;
  19018. };
  19019. Effect.prototype.setMatrices = function (uniformName, matrices) {
  19020. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  19021. return this;
  19022. };
  19023. Effect.prototype.setMatrix = function (uniformName, matrix) {
  19024. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  19025. // return this;
  19026. // this._cacheMatrix(uniformName, matrix);
  19027. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  19028. return this;
  19029. };
  19030. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  19031. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  19032. return this;
  19033. };
  19034. Effect.prototype.setMatrix2x2 = function (uniformname, matrix) {
  19035. this._engine.setMatrix2x2(this.getUniform(uniformname), matrix);
  19036. return this;
  19037. };
  19038. Effect.prototype.setFloat = function (uniformName, value) {
  19039. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  19040. return this;
  19041. this._valueCache[uniformName] = value;
  19042. this._engine.setFloat(this.getUniform(uniformName), value);
  19043. return this;
  19044. };
  19045. Effect.prototype.setBool = function (uniformName, bool) {
  19046. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  19047. return this;
  19048. this._valueCache[uniformName] = bool;
  19049. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  19050. return this;
  19051. };
  19052. Effect.prototype.setVector2 = function (uniformName, vector2) {
  19053. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  19054. return this;
  19055. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  19056. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  19057. return this;
  19058. };
  19059. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  19060. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  19061. return this;
  19062. this._cacheFloat2(uniformName, x, y);
  19063. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  19064. return this;
  19065. };
  19066. Effect.prototype.setVector3 = function (uniformName, vector3) {
  19067. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  19068. return this;
  19069. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  19070. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  19071. return this;
  19072. };
  19073. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  19074. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  19075. return this;
  19076. this._cacheFloat3(uniformName, x, y, z);
  19077. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  19078. return this;
  19079. };
  19080. Effect.prototype.setVector4 = function (uniformName, vector4) {
  19081. 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)
  19082. return this;
  19083. this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w);
  19084. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  19085. return this;
  19086. };
  19087. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  19088. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  19089. return this;
  19090. this._cacheFloat4(uniformName, x, y, z, w);
  19091. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  19092. return this;
  19093. };
  19094. Effect.prototype.setColor3 = function (uniformName, color3) {
  19095. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  19096. return this;
  19097. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  19098. this._engine.setColor3(this.getUniform(uniformName), color3);
  19099. return this;
  19100. };
  19101. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  19102. 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)
  19103. return this;
  19104. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  19105. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  19106. return this;
  19107. };
  19108. // Statics
  19109. Effect.ShadersStore = {};
  19110. Effect.IncludesShadersStore = {};
  19111. return Effect;
  19112. })();
  19113. BABYLON.Effect = Effect;
  19114. })(BABYLON || (BABYLON = {}));
  19115. var BABYLON;
  19116. (function (BABYLON) {
  19117. var MaterialDefines = (function () {
  19118. function MaterialDefines() {
  19119. }
  19120. MaterialDefines.prototype.isEqual = function (other) {
  19121. for (var index = 0; index < this._keys.length; index++) {
  19122. var prop = this._keys[index];
  19123. if (this[prop] !== other[prop]) {
  19124. return false;
  19125. }
  19126. }
  19127. return true;
  19128. };
  19129. MaterialDefines.prototype.cloneTo = function (other) {
  19130. for (var index = 0; index < this._keys.length; index++) {
  19131. var prop = this._keys[index];
  19132. other[prop] = this[prop];
  19133. }
  19134. };
  19135. MaterialDefines.prototype.reset = function () {
  19136. for (var index = 0; index < this._keys.length; index++) {
  19137. var prop = this._keys[index];
  19138. if (typeof (this[prop]) === "number") {
  19139. this[prop] = 0;
  19140. }
  19141. else {
  19142. this[prop] = false;
  19143. }
  19144. }
  19145. };
  19146. MaterialDefines.prototype.toString = function () {
  19147. var result = "";
  19148. for (var index = 0; index < this._keys.length; index++) {
  19149. var prop = this._keys[index];
  19150. if (typeof (this[prop]) === "number") {
  19151. result += "#define " + prop + " " + this[prop] + "\n";
  19152. }
  19153. else if (this[prop]) {
  19154. result += "#define " + prop + "\n";
  19155. }
  19156. }
  19157. return result;
  19158. };
  19159. return MaterialDefines;
  19160. })();
  19161. BABYLON.MaterialDefines = MaterialDefines;
  19162. var Material = (function () {
  19163. function Material(name, scene, doNotAdd) {
  19164. this.name = name;
  19165. this.checkReadyOnEveryCall = false;
  19166. this.checkReadyOnlyOnce = false;
  19167. this.state = "";
  19168. this.alpha = 1.0;
  19169. this.backFaceCulling = true;
  19170. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  19171. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  19172. this.disableDepthWrite = false;
  19173. this.fogEnabled = true;
  19174. this._wasPreviouslyReady = false;
  19175. this._fillMode = Material.TriangleFillMode;
  19176. this.pointSize = 1.0;
  19177. this.zOffset = 0;
  19178. this.id = name;
  19179. this._scene = scene;
  19180. if (!doNotAdd) {
  19181. scene.materials.push(this);
  19182. }
  19183. }
  19184. Object.defineProperty(Material, "TriangleFillMode", {
  19185. get: function () {
  19186. return Material._TriangleFillMode;
  19187. },
  19188. enumerable: true,
  19189. configurable: true
  19190. });
  19191. Object.defineProperty(Material, "WireFrameFillMode", {
  19192. get: function () {
  19193. return Material._WireFrameFillMode;
  19194. },
  19195. enumerable: true,
  19196. configurable: true
  19197. });
  19198. Object.defineProperty(Material, "PointFillMode", {
  19199. get: function () {
  19200. return Material._PointFillMode;
  19201. },
  19202. enumerable: true,
  19203. configurable: true
  19204. });
  19205. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  19206. get: function () {
  19207. return Material._ClockWiseSideOrientation;
  19208. },
  19209. enumerable: true,
  19210. configurable: true
  19211. });
  19212. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  19213. get: function () {
  19214. return Material._CounterClockWiseSideOrientation;
  19215. },
  19216. enumerable: true,
  19217. configurable: true
  19218. });
  19219. Object.defineProperty(Material.prototype, "wireframe", {
  19220. get: function () {
  19221. return this._fillMode === Material.WireFrameFillMode;
  19222. },
  19223. set: function (value) {
  19224. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  19225. },
  19226. enumerable: true,
  19227. configurable: true
  19228. });
  19229. Object.defineProperty(Material.prototype, "pointsCloud", {
  19230. get: function () {
  19231. return this._fillMode === Material.PointFillMode;
  19232. },
  19233. set: function (value) {
  19234. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  19235. },
  19236. enumerable: true,
  19237. configurable: true
  19238. });
  19239. Object.defineProperty(Material.prototype, "fillMode", {
  19240. get: function () {
  19241. return this._fillMode;
  19242. },
  19243. set: function (value) {
  19244. this._fillMode = value;
  19245. },
  19246. enumerable: true,
  19247. configurable: true
  19248. });
  19249. Object.defineProperty(Material.prototype, "isFrozen", {
  19250. get: function () {
  19251. return this.checkReadyOnlyOnce;
  19252. },
  19253. enumerable: true,
  19254. configurable: true
  19255. });
  19256. Material.prototype.freeze = function () {
  19257. this.checkReadyOnlyOnce = true;
  19258. };
  19259. Material.prototype.unfreeze = function () {
  19260. this.checkReadyOnlyOnce = false;
  19261. };
  19262. Material.prototype.isReady = function (mesh, useInstances) {
  19263. return true;
  19264. };
  19265. Material.prototype.getEffect = function () {
  19266. return this._effect;
  19267. };
  19268. Material.prototype.getScene = function () {
  19269. return this._scene;
  19270. };
  19271. Material.prototype.needAlphaBlending = function () {
  19272. return (this.alpha < 1.0);
  19273. };
  19274. Material.prototype.needAlphaTesting = function () {
  19275. return false;
  19276. };
  19277. Material.prototype.getAlphaTestTexture = function () {
  19278. return null;
  19279. };
  19280. Material.prototype.trackCreation = function (onCompiled, onError) {
  19281. };
  19282. Material.prototype.markDirty = function () {
  19283. this._wasPreviouslyReady = false;
  19284. };
  19285. Material.prototype._preBind = function () {
  19286. var engine = this._scene.getEngine();
  19287. engine.enableEffect(this._effect);
  19288. engine.setState(this.backFaceCulling, this.zOffset, false, this.sideOrientation === Material.ClockWiseSideOrientation);
  19289. };
  19290. Material.prototype.bind = function (world, mesh) {
  19291. this._scene._cachedMaterial = this;
  19292. if (this.onBind) {
  19293. this.onBind(this, mesh);
  19294. }
  19295. if (this.disableDepthWrite) {
  19296. var engine = this._scene.getEngine();
  19297. this._cachedDepthWriteState = engine.getDepthWrite();
  19298. engine.setDepthWrite(false);
  19299. }
  19300. };
  19301. Material.prototype.bindOnlyWorldMatrix = function (world) {
  19302. };
  19303. Material.prototype.unbind = function () {
  19304. if (this.disableDepthWrite) {
  19305. var engine = this._scene.getEngine();
  19306. engine.setDepthWrite(this._cachedDepthWriteState);
  19307. }
  19308. };
  19309. Material.prototype.clone = function (name) {
  19310. return null;
  19311. };
  19312. Material.prototype.getBindedMeshes = function () {
  19313. var result = new Array();
  19314. for (var index = 0; index < this._scene.meshes.length; index++) {
  19315. var mesh = this._scene.meshes[index];
  19316. if (mesh.material === this) {
  19317. result.push(mesh);
  19318. }
  19319. }
  19320. return result;
  19321. };
  19322. Material.prototype.dispose = function (forceDisposeEffect) {
  19323. // Animations
  19324. this.getScene().stopAnimation(this);
  19325. // Remove from scene
  19326. var index = this._scene.materials.indexOf(this);
  19327. if (index >= 0) {
  19328. this._scene.materials.splice(index, 1);
  19329. }
  19330. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  19331. if (forceDisposeEffect && this._effect) {
  19332. this._scene.getEngine()._releaseEffect(this._effect);
  19333. this._effect = null;
  19334. }
  19335. // Remove from meshes
  19336. for (index = 0; index < this._scene.meshes.length; index++) {
  19337. var mesh = this._scene.meshes[index];
  19338. if (mesh.material === this) {
  19339. mesh.material = null;
  19340. }
  19341. }
  19342. // Callback
  19343. if (this.onDispose) {
  19344. this.onDispose();
  19345. }
  19346. };
  19347. Material.prototype.copyTo = function (other) {
  19348. other.checkReadyOnlyOnce = this.checkReadyOnlyOnce;
  19349. other.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  19350. other.alpha = this.alpha;
  19351. other.fillMode = this.fillMode;
  19352. other.backFaceCulling = this.backFaceCulling;
  19353. other.fogEnabled = this.fogEnabled;
  19354. other.wireframe = this.wireframe;
  19355. other.zOffset = this.zOffset;
  19356. other.alphaMode = this.alphaMode;
  19357. other.sideOrientation = this.sideOrientation;
  19358. other.disableDepthWrite = this.disableDepthWrite;
  19359. other.pointSize = this.pointSize;
  19360. other.pointsCloud = this.pointsCloud;
  19361. };
  19362. Material.prototype.serialize = function () {
  19363. var serializationObject = {};
  19364. serializationObject.name = this.name;
  19365. serializationObject.alpha = this.alpha;
  19366. serializationObject.id = this.id;
  19367. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19368. serializationObject.backFaceCulling = this.backFaceCulling;
  19369. serializationObject.checkReadyOnlyOnce = this.checkReadyOnlyOnce;
  19370. serializationObject.disableDepthWrite = this.disableDepthWrite;
  19371. return serializationObject;
  19372. };
  19373. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  19374. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  19375. multiMaterial.id = parsedMultiMaterial.id;
  19376. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  19377. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  19378. var subMatId = parsedMultiMaterial.materials[matIndex];
  19379. if (subMatId) {
  19380. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  19381. }
  19382. else {
  19383. multiMaterial.subMaterials.push(null);
  19384. }
  19385. }
  19386. return multiMaterial;
  19387. };
  19388. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  19389. if (!parsedMaterial.customType) {
  19390. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  19391. }
  19392. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  19393. return materialType.Parse(parsedMaterial, scene, rootUrl);
  19394. ;
  19395. };
  19396. Material._TriangleFillMode = 0;
  19397. Material._WireFrameFillMode = 1;
  19398. Material._PointFillMode = 2;
  19399. Material._ClockWiseSideOrientation = 0;
  19400. Material._CounterClockWiseSideOrientation = 1;
  19401. return Material;
  19402. })();
  19403. BABYLON.Material = Material;
  19404. })(BABYLON || (BABYLON = {}));
  19405. var BABYLON;
  19406. (function (BABYLON) {
  19407. var maxSimultaneousLights = 4;
  19408. var FresnelParameters = (function () {
  19409. function FresnelParameters() {
  19410. this.isEnabled = true;
  19411. this.leftColor = BABYLON.Color3.White();
  19412. this.rightColor = BABYLON.Color3.Black();
  19413. this.bias = 0;
  19414. this.power = 1;
  19415. }
  19416. FresnelParameters.prototype.clone = function () {
  19417. var newFresnelParameters = new FresnelParameters();
  19418. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  19419. return new FresnelParameters;
  19420. };
  19421. FresnelParameters.prototype.serialize = function () {
  19422. var serializationObject = {};
  19423. serializationObject.isEnabled = this.isEnabled;
  19424. serializationObject.leftColor = this.leftColor;
  19425. serializationObject.rightColor = this.rightColor;
  19426. serializationObject.bias = this.bias;
  19427. serializationObject.power = this.power;
  19428. return serializationObject;
  19429. };
  19430. FresnelParameters.Parse = function (parsedFresnelParameters) {
  19431. var fresnelParameters = new FresnelParameters();
  19432. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  19433. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  19434. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  19435. fresnelParameters.bias = parsedFresnelParameters.bias;
  19436. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  19437. return fresnelParameters;
  19438. };
  19439. return FresnelParameters;
  19440. })();
  19441. BABYLON.FresnelParameters = FresnelParameters;
  19442. var StandardMaterialDefines = (function (_super) {
  19443. __extends(StandardMaterialDefines, _super);
  19444. function StandardMaterialDefines() {
  19445. _super.call(this);
  19446. this.DIFFUSE = false;
  19447. this.AMBIENT = false;
  19448. this.OPACITY = false;
  19449. this.OPACITYRGB = false;
  19450. this.REFLECTION = false;
  19451. this.EMISSIVE = false;
  19452. this.SPECULAR = false;
  19453. this.BUMP = false;
  19454. this.SPECULAROVERALPHA = false;
  19455. this.CLIPPLANE = false;
  19456. this.ALPHATEST = false;
  19457. this.ALPHAFROMDIFFUSE = false;
  19458. this.POINTSIZE = false;
  19459. this.FOG = false;
  19460. this.LIGHT0 = false;
  19461. this.LIGHT1 = false;
  19462. this.LIGHT2 = false;
  19463. this.LIGHT3 = false;
  19464. this.SPOTLIGHT0 = false;
  19465. this.SPOTLIGHT1 = false;
  19466. this.SPOTLIGHT2 = false;
  19467. this.SPOTLIGHT3 = false;
  19468. this.HEMILIGHT0 = false;
  19469. this.HEMILIGHT1 = false;
  19470. this.HEMILIGHT2 = false;
  19471. this.HEMILIGHT3 = false;
  19472. this.POINTLIGHT0 = false;
  19473. this.POINTLIGHT1 = false;
  19474. this.POINTLIGHT2 = false;
  19475. this.POINTLIGHT3 = false;
  19476. this.DIRLIGHT0 = false;
  19477. this.DIRLIGHT1 = false;
  19478. this.DIRLIGHT2 = false;
  19479. this.DIRLIGHT3 = false;
  19480. this.SPECULARTERM = false;
  19481. this.SHADOW0 = false;
  19482. this.SHADOW1 = false;
  19483. this.SHADOW2 = false;
  19484. this.SHADOW3 = false;
  19485. this.SHADOWS = false;
  19486. this.SHADOWVSM0 = false;
  19487. this.SHADOWVSM1 = false;
  19488. this.SHADOWVSM2 = false;
  19489. this.SHADOWVSM3 = false;
  19490. this.SHADOWPCF0 = false;
  19491. this.SHADOWPCF1 = false;
  19492. this.SHADOWPCF2 = false;
  19493. this.SHADOWPCF3 = false;
  19494. this.DIFFUSEFRESNEL = false;
  19495. this.OPACITYFRESNEL = false;
  19496. this.REFLECTIONFRESNEL = false;
  19497. this.REFRACTIONFRESNEL = false;
  19498. this.EMISSIVEFRESNEL = false;
  19499. this.FRESNEL = false;
  19500. this.NORMAL = false;
  19501. this.UV1 = false;
  19502. this.UV2 = false;
  19503. this.VERTEXCOLOR = false;
  19504. this.VERTEXALPHA = false;
  19505. this.NUM_BONE_INFLUENCERS = 0;
  19506. this.BonesPerMesh = 0;
  19507. this.INSTANCES = false;
  19508. this.GLOSSINESS = false;
  19509. this.ROUGHNESS = false;
  19510. this.EMISSIVEASILLUMINATION = false;
  19511. this.LINKEMISSIVEWITHDIFFUSE = false;
  19512. this.REFLECTIONFRESNELFROMSPECULAR = false;
  19513. this.LIGHTMAP = false;
  19514. this.USELIGHTMAPASSHADOWMAP = false;
  19515. this.REFLECTIONMAP_3D = false;
  19516. this.REFLECTIONMAP_SPHERICAL = false;
  19517. this.REFLECTIONMAP_PLANAR = false;
  19518. this.REFLECTIONMAP_CUBIC = false;
  19519. this.REFLECTIONMAP_PROJECTION = false;
  19520. this.REFLECTIONMAP_SKYBOX = false;
  19521. this.REFLECTIONMAP_EXPLICIT = false;
  19522. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  19523. this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  19524. this.INVERTCUBICMAP = false;
  19525. this.LOGARITHMICDEPTH = false;
  19526. this.REFRACTION = false;
  19527. this.REFRACTIONMAP_3D = false;
  19528. this._keys = Object.keys(this);
  19529. }
  19530. return StandardMaterialDefines;
  19531. })(BABYLON.MaterialDefines);
  19532. var StandardMaterial = (function (_super) {
  19533. __extends(StandardMaterial, _super);
  19534. function StandardMaterial(name, scene) {
  19535. var _this = this;
  19536. _super.call(this, name, scene);
  19537. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  19538. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  19539. this.specularColor = new BABYLON.Color3(1, 1, 1);
  19540. this.specularPower = 64;
  19541. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  19542. this.useAlphaFromDiffuseTexture = false;
  19543. this.useEmissiveAsIllumination = false;
  19544. this.linkEmissiveWithDiffuse = false;
  19545. this.useReflectionFresnelFromSpecular = false;
  19546. this.useSpecularOverAlpha = false;
  19547. this.disableLighting = false;
  19548. this.roughness = 0;
  19549. this.indexOfRefraction = 0.98;
  19550. this.invertRefractionY = true;
  19551. this.useLightmapAsShadowmap = false;
  19552. this.useGlossinessFromSpecularMapAlpha = false;
  19553. this._renderTargets = new BABYLON.SmartArray(16);
  19554. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  19555. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  19556. this._defines = new StandardMaterialDefines();
  19557. this._cachedDefines = new StandardMaterialDefines();
  19558. this._cachedDefines.BonesPerMesh = -1;
  19559. this.getRenderTargetTextures = function () {
  19560. _this._renderTargets.reset();
  19561. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  19562. _this._renderTargets.push(_this.reflectionTexture);
  19563. }
  19564. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  19565. _this._renderTargets.push(_this.refractionTexture);
  19566. }
  19567. return _this._renderTargets;
  19568. };
  19569. }
  19570. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  19571. get: function () {
  19572. return this._useLogarithmicDepth;
  19573. },
  19574. set: function (value) {
  19575. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  19576. },
  19577. enumerable: true,
  19578. configurable: true
  19579. });
  19580. StandardMaterial.prototype.needAlphaBlending = function () {
  19581. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  19582. };
  19583. StandardMaterial.prototype.needAlphaTesting = function () {
  19584. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  19585. };
  19586. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  19587. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  19588. };
  19589. StandardMaterial.prototype.getAlphaTestTexture = function () {
  19590. return this.diffuseTexture;
  19591. };
  19592. // Methods
  19593. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  19594. if (!mesh) {
  19595. return true;
  19596. }
  19597. if (this._defines.INSTANCES !== useInstances) {
  19598. return false;
  19599. }
  19600. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  19601. return true;
  19602. }
  19603. return false;
  19604. };
  19605. StandardMaterial.PrepareDefinesForLights = function (scene, mesh, defines) {
  19606. var lightIndex = 0;
  19607. var needNormals = false;
  19608. for (var index = 0; index < scene.lights.length; index++) {
  19609. var light = scene.lights[index];
  19610. if (!light.isEnabled()) {
  19611. continue;
  19612. }
  19613. // Excluded check
  19614. if (light._excludedMeshesIds.length > 0) {
  19615. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  19616. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  19617. if (excludedMesh) {
  19618. light.excludedMeshes.push(excludedMesh);
  19619. }
  19620. }
  19621. light._excludedMeshesIds = [];
  19622. }
  19623. // Included check
  19624. if (light._includedOnlyMeshesIds.length > 0) {
  19625. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  19626. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  19627. if (includedOnlyMesh) {
  19628. light.includedOnlyMeshes.push(includedOnlyMesh);
  19629. }
  19630. }
  19631. light._includedOnlyMeshesIds = [];
  19632. }
  19633. if (!light.canAffectMesh(mesh)) {
  19634. continue;
  19635. }
  19636. needNormals = true;
  19637. defines["LIGHT" + lightIndex] = true;
  19638. var type;
  19639. if (light instanceof BABYLON.SpotLight) {
  19640. type = "SPOTLIGHT" + lightIndex;
  19641. }
  19642. else if (light instanceof BABYLON.HemisphericLight) {
  19643. type = "HEMILIGHT" + lightIndex;
  19644. }
  19645. else if (light instanceof BABYLON.PointLight) {
  19646. type = "POINTLIGHT" + lightIndex;
  19647. }
  19648. else {
  19649. type = "DIRLIGHT" + lightIndex;
  19650. }
  19651. defines[type] = true;
  19652. // Specular
  19653. if (!light.specular.equalsFloats(0, 0, 0) && defines["SPECULARTERM"] !== undefined) {
  19654. defines["SPECULARTERM"] = true;
  19655. }
  19656. // Shadows
  19657. if (scene.shadowsEnabled) {
  19658. var shadowGenerator = light.getShadowGenerator();
  19659. if (mesh && mesh.receiveShadows && shadowGenerator) {
  19660. defines["SHADOW" + lightIndex] = true;
  19661. defines["SHADOWS"] = true;
  19662. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  19663. defines["SHADOWVSM" + lightIndex] = true;
  19664. }
  19665. if (shadowGenerator.usePoissonSampling) {
  19666. defines["SHADOWPCF" + lightIndex] = true;
  19667. }
  19668. }
  19669. }
  19670. lightIndex++;
  19671. if (lightIndex === maxSimultaneousLights)
  19672. break;
  19673. }
  19674. return needNormals;
  19675. };
  19676. StandardMaterial.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  19677. var shadowGenerator = light.getShadowGenerator();
  19678. if (mesh.receiveShadows && shadowGenerator) {
  19679. if (!light.needCube()) {
  19680. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  19681. }
  19682. else {
  19683. if (!depthValuesAlreadySet) {
  19684. depthValuesAlreadySet = true;
  19685. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  19686. }
  19687. }
  19688. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  19689. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  19690. }
  19691. return depthValuesAlreadySet;
  19692. };
  19693. StandardMaterial.BindLights = function (scene, mesh, effect, defines) {
  19694. var lightIndex = 0;
  19695. var depthValuesAlreadySet = false;
  19696. for (var index = 0; index < scene.lights.length; index++) {
  19697. var light = scene.lights[index];
  19698. if (!light.isEnabled()) {
  19699. continue;
  19700. }
  19701. if (!light.canAffectMesh(mesh)) {
  19702. continue;
  19703. }
  19704. if (light instanceof BABYLON.PointLight) {
  19705. // Point Light
  19706. light.transferToEffect(effect, "vLightData" + lightIndex);
  19707. }
  19708. else if (light instanceof BABYLON.DirectionalLight) {
  19709. // Directional Light
  19710. light.transferToEffect(effect, "vLightData" + lightIndex);
  19711. }
  19712. else if (light instanceof BABYLON.SpotLight) {
  19713. // Spot Light
  19714. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  19715. }
  19716. else if (light instanceof BABYLON.HemisphericLight) {
  19717. // Hemispheric Light
  19718. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  19719. }
  19720. light.diffuse.scaleToRef(light.intensity, StandardMaterial._scaledDiffuse);
  19721. effect.setColor4("vLightDiffuse" + lightIndex, StandardMaterial._scaledDiffuse, light.range);
  19722. if (defines["SPECULARTERM"]) {
  19723. light.specular.scaleToRef(light.intensity, StandardMaterial._scaledSpecular);
  19724. effect.setColor3("vLightSpecular" + lightIndex, StandardMaterial._scaledSpecular);
  19725. }
  19726. // Shadows
  19727. if (scene.shadowsEnabled) {
  19728. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  19729. }
  19730. lightIndex++;
  19731. if (lightIndex === maxSimultaneousLights)
  19732. break;
  19733. }
  19734. };
  19735. StandardMaterial.HandleFallbacksForShadows = function (defines, fallbacks) {
  19736. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  19737. if (!defines["LIGHT" + lightIndex]) {
  19738. continue;
  19739. }
  19740. if (lightIndex > 0) {
  19741. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  19742. }
  19743. if (defines["SHADOW" + lightIndex]) {
  19744. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  19745. }
  19746. if (defines["SHADOWPCF" + lightIndex]) {
  19747. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  19748. }
  19749. if (defines["SHADOWVSM" + lightIndex]) {
  19750. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  19751. }
  19752. }
  19753. };
  19754. StandardMaterial.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  19755. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  19756. fallbacks.addCPUSkinningFallback(0, mesh);
  19757. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19758. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19759. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  19760. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  19761. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  19762. }
  19763. }
  19764. };
  19765. StandardMaterial.PrepareAttributesForInstances = function (attribs, defines) {
  19766. if (defines["INSTANCES"]) {
  19767. attribs.push("world0");
  19768. attribs.push("world1");
  19769. attribs.push("world2");
  19770. attribs.push("world3");
  19771. }
  19772. };
  19773. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  19774. if (this.isFrozen) {
  19775. if (this._wasPreviouslyReady) {
  19776. return true;
  19777. }
  19778. }
  19779. var scene = this.getScene();
  19780. if (!this.checkReadyOnEveryCall) {
  19781. if (this._renderId === scene.getRenderId()) {
  19782. if (this._checkCache(scene, mesh, useInstances)) {
  19783. return true;
  19784. }
  19785. }
  19786. }
  19787. var engine = scene.getEngine();
  19788. var needNormals = false;
  19789. var needUVs = false;
  19790. this._defines.reset();
  19791. // Textures
  19792. if (scene.texturesEnabled) {
  19793. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  19794. if (!this.diffuseTexture.isReady()) {
  19795. return false;
  19796. }
  19797. else {
  19798. needUVs = true;
  19799. this._defines.DIFFUSE = true;
  19800. }
  19801. }
  19802. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  19803. if (!this.ambientTexture.isReady()) {
  19804. return false;
  19805. }
  19806. else {
  19807. needUVs = true;
  19808. this._defines.AMBIENT = true;
  19809. }
  19810. }
  19811. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  19812. if (!this.opacityTexture.isReady()) {
  19813. return false;
  19814. }
  19815. else {
  19816. needUVs = true;
  19817. this._defines.OPACITY = true;
  19818. if (this.opacityTexture.getAlphaFromRGB) {
  19819. this._defines.OPACITYRGB = true;
  19820. }
  19821. }
  19822. }
  19823. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  19824. if (!this.reflectionTexture.isReady()) {
  19825. return false;
  19826. }
  19827. else {
  19828. needNormals = true;
  19829. this._defines.REFLECTION = true;
  19830. if (this.roughness > 0) {
  19831. this._defines.ROUGHNESS = true;
  19832. }
  19833. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  19834. this._defines.INVERTCUBICMAP = true;
  19835. }
  19836. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  19837. switch (this.reflectionTexture.coordinatesMode) {
  19838. case BABYLON.Texture.CUBIC_MODE:
  19839. case BABYLON.Texture.INVCUBIC_MODE:
  19840. this._defines.REFLECTIONMAP_CUBIC = true;
  19841. break;
  19842. case BABYLON.Texture.EXPLICIT_MODE:
  19843. this._defines.REFLECTIONMAP_EXPLICIT = true;
  19844. break;
  19845. case BABYLON.Texture.PLANAR_MODE:
  19846. this._defines.REFLECTIONMAP_PLANAR = true;
  19847. break;
  19848. case BABYLON.Texture.PROJECTION_MODE:
  19849. this._defines.REFLECTIONMAP_PROJECTION = true;
  19850. break;
  19851. case BABYLON.Texture.SKYBOX_MODE:
  19852. this._defines.REFLECTIONMAP_SKYBOX = true;
  19853. break;
  19854. case BABYLON.Texture.SPHERICAL_MODE:
  19855. this._defines.REFLECTIONMAP_SPHERICAL = true;
  19856. break;
  19857. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  19858. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  19859. break;
  19860. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  19861. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  19862. break;
  19863. }
  19864. }
  19865. }
  19866. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  19867. if (!this.emissiveTexture.isReady()) {
  19868. return false;
  19869. }
  19870. else {
  19871. needUVs = true;
  19872. this._defines.EMISSIVE = true;
  19873. }
  19874. }
  19875. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  19876. if (!this.lightmapTexture.isReady()) {
  19877. return false;
  19878. }
  19879. else {
  19880. needUVs = true;
  19881. this._defines.LIGHTMAP = true;
  19882. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  19883. }
  19884. }
  19885. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  19886. if (!this.specularTexture.isReady()) {
  19887. return false;
  19888. }
  19889. else {
  19890. needUVs = true;
  19891. this._defines.SPECULAR = true;
  19892. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  19893. }
  19894. }
  19895. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  19896. if (!this.bumpTexture.isReady()) {
  19897. return false;
  19898. }
  19899. else {
  19900. needUVs = true;
  19901. this._defines.BUMP = true;
  19902. }
  19903. }
  19904. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  19905. if (!this.refractionTexture.isReady()) {
  19906. return false;
  19907. }
  19908. else {
  19909. needUVs = true;
  19910. this._defines.REFRACTION = true;
  19911. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  19912. }
  19913. }
  19914. }
  19915. // Effect
  19916. if (scene.clipPlane) {
  19917. this._defines.CLIPPLANE = true;
  19918. }
  19919. if (engine.getAlphaTesting()) {
  19920. this._defines.ALPHATEST = true;
  19921. }
  19922. if (this._shouldUseAlphaFromDiffuseTexture()) {
  19923. this._defines.ALPHAFROMDIFFUSE = true;
  19924. }
  19925. if (this.useEmissiveAsIllumination) {
  19926. this._defines.EMISSIVEASILLUMINATION = true;
  19927. }
  19928. if (this.linkEmissiveWithDiffuse) {
  19929. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  19930. }
  19931. if (this.useReflectionFresnelFromSpecular) {
  19932. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  19933. }
  19934. if (this.useLogarithmicDepth) {
  19935. this._defines.LOGARITHMICDEPTH = true;
  19936. }
  19937. // Point size
  19938. if (this.pointsCloud || scene.forcePointsCloud) {
  19939. this._defines.POINTSIZE = true;
  19940. }
  19941. // Fog
  19942. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  19943. this._defines.FOG = true;
  19944. }
  19945. if (scene.lightsEnabled && !this.disableLighting) {
  19946. needNormals = StandardMaterial.PrepareDefinesForLights(scene, mesh, this._defines);
  19947. }
  19948. if (StandardMaterial.FresnelEnabled) {
  19949. // Fresnel
  19950. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  19951. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  19952. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  19953. this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled ||
  19954. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  19955. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  19956. this._defines.DIFFUSEFRESNEL = true;
  19957. }
  19958. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  19959. this._defines.OPACITYFRESNEL = true;
  19960. }
  19961. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  19962. this._defines.REFLECTIONFRESNEL = true;
  19963. }
  19964. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  19965. this._defines.REFRACTIONFRESNEL = true;
  19966. }
  19967. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  19968. this._defines.EMISSIVEFRESNEL = true;
  19969. }
  19970. needNormals = true;
  19971. this._defines.FRESNEL = true;
  19972. }
  19973. }
  19974. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  19975. this._defines.SPECULAROVERALPHA = true;
  19976. }
  19977. // Attribs
  19978. if (mesh) {
  19979. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19980. this._defines.NORMAL = true;
  19981. }
  19982. if (needUVs) {
  19983. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  19984. this._defines.UV1 = true;
  19985. }
  19986. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  19987. this._defines.UV2 = true;
  19988. }
  19989. }
  19990. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  19991. this._defines.VERTEXCOLOR = true;
  19992. if (mesh.hasVertexAlpha) {
  19993. this._defines.VERTEXALPHA = true;
  19994. }
  19995. }
  19996. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  19997. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  19998. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  19999. }
  20000. // Instances
  20001. if (useInstances) {
  20002. this._defines.INSTANCES = true;
  20003. }
  20004. }
  20005. // Get correct effect
  20006. if (!this._defines.isEqual(this._cachedDefines)) {
  20007. this._defines.cloneTo(this._cachedDefines);
  20008. scene.resetCachedMaterial();
  20009. // Fallbacks
  20010. var fallbacks = new BABYLON.EffectFallbacks();
  20011. if (this._defines.REFLECTION) {
  20012. fallbacks.addFallback(0, "REFLECTION");
  20013. }
  20014. if (this._defines.SPECULAR) {
  20015. fallbacks.addFallback(0, "SPECULAR");
  20016. }
  20017. if (this._defines.BUMP) {
  20018. fallbacks.addFallback(0, "BUMP");
  20019. }
  20020. if (this._defines.SPECULAROVERALPHA) {
  20021. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  20022. }
  20023. if (this._defines.FOG) {
  20024. fallbacks.addFallback(1, "FOG");
  20025. }
  20026. if (this._defines.POINTSIZE) {
  20027. fallbacks.addFallback(0, "POINTSIZE");
  20028. }
  20029. if (this._defines.LOGARITHMICDEPTH) {
  20030. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  20031. }
  20032. StandardMaterial.HandleFallbacksForShadows(this._defines, fallbacks);
  20033. if (this._defines.SPECULARTERM) {
  20034. fallbacks.addFallback(0, "SPECULARTERM");
  20035. }
  20036. if (this._defines.DIFFUSEFRESNEL) {
  20037. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  20038. }
  20039. if (this._defines.OPACITYFRESNEL) {
  20040. fallbacks.addFallback(2, "OPACITYFRESNEL");
  20041. }
  20042. if (this._defines.REFLECTIONFRESNEL) {
  20043. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  20044. }
  20045. if (this._defines.EMISSIVEFRESNEL) {
  20046. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  20047. }
  20048. if (this._defines.FRESNEL) {
  20049. fallbacks.addFallback(4, "FRESNEL");
  20050. }
  20051. //Attributes
  20052. var attribs = [BABYLON.VertexBuffer.PositionKind];
  20053. if (this._defines.NORMAL) {
  20054. attribs.push(BABYLON.VertexBuffer.NormalKind);
  20055. }
  20056. if (this._defines.UV1) {
  20057. attribs.push(BABYLON.VertexBuffer.UVKind);
  20058. }
  20059. if (this._defines.UV2) {
  20060. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  20061. }
  20062. if (this._defines.VERTEXCOLOR) {
  20063. attribs.push(BABYLON.VertexBuffer.ColorKind);
  20064. }
  20065. StandardMaterial.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  20066. StandardMaterial.PrepareAttributesForInstances(attribs, this._defines);
  20067. // Legacy browser patch
  20068. var shaderName = "default";
  20069. if (!scene.getEngine().getCaps().standardDerivatives) {
  20070. shaderName = "legacydefault";
  20071. }
  20072. var join = this._defines.toString();
  20073. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  20074. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  20075. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  20076. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  20077. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  20078. "vFogInfos", "vFogColor", "pointSize",
  20079. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  20080. "mBones",
  20081. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  20082. "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3", "depthValues",
  20083. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  20084. "logarithmicDepthConstant"
  20085. ], ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler",
  20086. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  20087. ], join, fallbacks, this.onCompiled, this.onError);
  20088. }
  20089. if (!this._effect.isReady()) {
  20090. return false;
  20091. }
  20092. this._renderId = scene.getRenderId();
  20093. this._wasPreviouslyReady = true;
  20094. if (mesh) {
  20095. if (!mesh._materialDefines) {
  20096. mesh._materialDefines = new StandardMaterialDefines();
  20097. }
  20098. this._defines.cloneTo(mesh._materialDefines);
  20099. }
  20100. return true;
  20101. };
  20102. StandardMaterial.prototype.unbind = function () {
  20103. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  20104. this._effect.setTexture("reflection2DSampler", null);
  20105. }
  20106. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  20107. this._effect.setTexture("refraction2DSampler", null);
  20108. }
  20109. _super.prototype.unbind.call(this);
  20110. };
  20111. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  20112. this._effect.setMatrix("world", world);
  20113. };
  20114. StandardMaterial.prototype.bind = function (world, mesh) {
  20115. var scene = this.getScene();
  20116. // Matrices
  20117. this.bindOnlyWorldMatrix(world);
  20118. // Bones
  20119. StandardMaterial.ApplyBonesParameters(mesh, this._effect);
  20120. if (scene.getCachedMaterial() !== this) {
  20121. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  20122. if (StandardMaterial.FresnelEnabled) {
  20123. // Fresnel
  20124. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  20125. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  20126. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  20127. }
  20128. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  20129. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  20130. }
  20131. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  20132. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  20133. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  20134. }
  20135. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  20136. this._effect.setColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  20137. this._effect.setColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  20138. }
  20139. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  20140. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  20141. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  20142. }
  20143. }
  20144. // Textures
  20145. if (scene.texturesEnabled) {
  20146. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  20147. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  20148. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  20149. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  20150. }
  20151. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  20152. this._effect.setTexture("ambientSampler", this.ambientTexture);
  20153. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  20154. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  20155. }
  20156. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  20157. this._effect.setTexture("opacitySampler", this.opacityTexture);
  20158. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  20159. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  20160. }
  20161. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  20162. if (this.reflectionTexture.isCube) {
  20163. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  20164. }
  20165. else {
  20166. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  20167. }
  20168. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  20169. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  20170. }
  20171. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  20172. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  20173. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  20174. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  20175. }
  20176. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  20177. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  20178. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  20179. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  20180. }
  20181. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  20182. this._effect.setTexture("specularSampler", this.specularTexture);
  20183. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  20184. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  20185. }
  20186. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  20187. this._effect.setTexture("bumpSampler", this.bumpTexture);
  20188. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  20189. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  20190. }
  20191. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  20192. var depth = 1.0;
  20193. if (this.refractionTexture.isCube) {
  20194. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  20195. }
  20196. else {
  20197. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  20198. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  20199. if (this.refractionTexture.depth) {
  20200. depth = this.refractionTexture.depth;
  20201. }
  20202. }
  20203. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  20204. }
  20205. }
  20206. // Clip plane
  20207. if (scene.clipPlane) {
  20208. var clipPlane = scene.clipPlane;
  20209. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  20210. }
  20211. // Point size
  20212. if (this.pointsCloud) {
  20213. this._effect.setFloat("pointSize", this.pointSize);
  20214. }
  20215. // Colors
  20216. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  20217. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  20218. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  20219. if (this._defines.SPECULARTERM) {
  20220. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  20221. }
  20222. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  20223. }
  20224. if (scene.getCachedMaterial() !== this || !this.isFrozen) {
  20225. // Diffuse
  20226. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  20227. // Lights
  20228. if (scene.lightsEnabled && !this.disableLighting) {
  20229. StandardMaterial.BindLights(scene, mesh, this._effect, this._defines);
  20230. }
  20231. // View
  20232. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture || this.refractionTexture) {
  20233. this._effect.setMatrix("view", scene.getViewMatrix());
  20234. }
  20235. // Fog
  20236. StandardMaterial.ApplyFogParameters(scene, mesh, this._effect);
  20237. // Log. depth
  20238. if (this._defines.LOGARITHMICDEPTH) {
  20239. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  20240. }
  20241. }
  20242. _super.prototype.bind.call(this, world, mesh);
  20243. };
  20244. StandardMaterial.ApplyFogParameters = function (scene, mesh, effect) {
  20245. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  20246. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  20247. effect.setColor3("vFogColor", scene.fogColor);
  20248. }
  20249. };
  20250. StandardMaterial.ApplyBonesParameters = function (mesh, effect) {
  20251. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  20252. effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  20253. }
  20254. };
  20255. StandardMaterial.prototype.getAnimatables = function () {
  20256. var results = [];
  20257. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  20258. results.push(this.diffuseTexture);
  20259. }
  20260. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  20261. results.push(this.ambientTexture);
  20262. }
  20263. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  20264. results.push(this.opacityTexture);
  20265. }
  20266. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  20267. results.push(this.reflectionTexture);
  20268. }
  20269. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  20270. results.push(this.emissiveTexture);
  20271. }
  20272. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  20273. results.push(this.specularTexture);
  20274. }
  20275. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  20276. results.push(this.bumpTexture);
  20277. }
  20278. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  20279. results.push(this.lightmapTexture);
  20280. }
  20281. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  20282. results.push(this.refractionTexture);
  20283. }
  20284. return results;
  20285. };
  20286. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  20287. if (this.diffuseTexture) {
  20288. this.diffuseTexture.dispose();
  20289. }
  20290. if (this.ambientTexture) {
  20291. this.ambientTexture.dispose();
  20292. }
  20293. if (this.opacityTexture) {
  20294. this.opacityTexture.dispose();
  20295. }
  20296. if (this.reflectionTexture) {
  20297. this.reflectionTexture.dispose();
  20298. }
  20299. if (this.emissiveTexture) {
  20300. this.emissiveTexture.dispose();
  20301. }
  20302. if (this.specularTexture) {
  20303. this.specularTexture.dispose();
  20304. }
  20305. if (this.bumpTexture) {
  20306. this.bumpTexture.dispose();
  20307. }
  20308. if (this.lightmapTexture) {
  20309. this.lightmapTexture.dispose();
  20310. }
  20311. if (this.refractionTexture) {
  20312. this.refractionTexture.dispose();
  20313. }
  20314. _super.prototype.dispose.call(this, forceDisposeEffect);
  20315. };
  20316. StandardMaterial.prototype.clone = function (name) {
  20317. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  20318. // Base material
  20319. this.copyTo(newStandardMaterial);
  20320. // Standard material
  20321. if (this.diffuseTexture && this.diffuseTexture.clone) {
  20322. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  20323. }
  20324. if (this.ambientTexture && this.ambientTexture.clone) {
  20325. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  20326. }
  20327. if (this.opacityTexture && this.opacityTexture.clone) {
  20328. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  20329. }
  20330. if (this.reflectionTexture && this.reflectionTexture.clone) {
  20331. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  20332. }
  20333. if (this.emissiveTexture && this.emissiveTexture.clone) {
  20334. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  20335. }
  20336. if (this.specularTexture && this.specularTexture.clone) {
  20337. newStandardMaterial.specularTexture = this.specularTexture.clone();
  20338. }
  20339. if (this.bumpTexture && this.bumpTexture.clone) {
  20340. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  20341. }
  20342. if (this.lightmapTexture && this.lightmapTexture.clone) {
  20343. newStandardMaterial.lightmapTexture = this.lightmapTexture.clone();
  20344. newStandardMaterial.useLightmapAsShadowmap = this.useLightmapAsShadowmap;
  20345. }
  20346. if (this.refractionTexture && this.refractionTexture.clone) {
  20347. newStandardMaterial.refractionTexture = this.refractionTexture.clone();
  20348. }
  20349. newStandardMaterial.ambientColor = this.ambientColor.clone();
  20350. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  20351. newStandardMaterial.specularColor = this.specularColor.clone();
  20352. newStandardMaterial.specularPower = this.specularPower;
  20353. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  20354. newStandardMaterial.useAlphaFromDiffuseTexture = this.useAlphaFromDiffuseTexture;
  20355. newStandardMaterial.useEmissiveAsIllumination = this.useEmissiveAsIllumination;
  20356. newStandardMaterial.useGlossinessFromSpecularMapAlpha = this.useGlossinessFromSpecularMapAlpha;
  20357. newStandardMaterial.useReflectionFresnelFromSpecular = this.useReflectionFresnelFromSpecular;
  20358. newStandardMaterial.useSpecularOverAlpha = this.useSpecularOverAlpha;
  20359. newStandardMaterial.roughness = this.roughness;
  20360. newStandardMaterial.indexOfRefraction = this.indexOfRefraction;
  20361. newStandardMaterial.invertRefractionY = this.invertRefractionY;
  20362. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.clone) {
  20363. newStandardMaterial.diffuseFresnelParameters = this.diffuseFresnelParameters.clone();
  20364. }
  20365. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.clone) {
  20366. newStandardMaterial.emissiveFresnelParameters = this.emissiveFresnelParameters.clone();
  20367. }
  20368. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.clone) {
  20369. newStandardMaterial.reflectionFresnelParameters = this.reflectionFresnelParameters.clone();
  20370. }
  20371. if (this.refractionFresnelParameters && this.refractionFresnelParameters.clone) {
  20372. newStandardMaterial.refractionFresnelParameters = this.refractionFresnelParameters.clone();
  20373. }
  20374. if (this.opacityFresnelParameters && this.opacityFresnelParameters.clone) {
  20375. newStandardMaterial.opacityFresnelParameters = this.opacityFresnelParameters.clone();
  20376. }
  20377. return newStandardMaterial;
  20378. };
  20379. StandardMaterial.prototype.serialize = function () {
  20380. var serializationObject = _super.prototype.serialize.call(this);
  20381. serializationObject.ambient = this.ambientColor.asArray();
  20382. serializationObject.diffuse = this.diffuseColor.asArray();
  20383. serializationObject.specular = this.specularColor.asArray();
  20384. serializationObject.specularPower = this.specularPower;
  20385. serializationObject.emissive = this.emissiveColor.asArray();
  20386. serializationObject.useReflectionFresnelFromSpecular = this.useReflectionFresnelFromSpecular;
  20387. serializationObject.useEmissiveAsIllumination = this.useEmissiveAsIllumination;
  20388. serializationObject.indexOfRefraction = this.indexOfRefraction;
  20389. serializationObject.invertRefractionY = this.invertRefractionY;
  20390. if (this.diffuseTexture) {
  20391. serializationObject.diffuseTexture = this.diffuseTexture.serialize();
  20392. }
  20393. if (this.diffuseFresnelParameters) {
  20394. serializationObject.diffuseFresnelParameters = this.diffuseFresnelParameters.serialize();
  20395. }
  20396. if (this.ambientTexture) {
  20397. serializationObject.ambientTexture = this.ambientTexture.serialize();
  20398. }
  20399. if (this.opacityTexture) {
  20400. serializationObject.opacityTexture = this.opacityTexture.serialize();
  20401. }
  20402. if (this.opacityFresnelParameters) {
  20403. serializationObject.opacityFresnelParameters = this.diffuseFresnelParameters.serialize();
  20404. }
  20405. if (this.reflectionTexture) {
  20406. serializationObject.reflectionTexture = this.reflectionTexture.serialize();
  20407. }
  20408. if (this.reflectionFresnelParameters) {
  20409. serializationObject.reflectionFresnelParameters = this.reflectionFresnelParameters.serialize();
  20410. }
  20411. if (this.refractionFresnelParameters) {
  20412. serializationObject.refractionFresnelParameters = this.refractionFresnelParameters.serialize();
  20413. }
  20414. if (this.emissiveTexture) {
  20415. serializationObject.emissiveTexture = this.emissiveTexture.serialize();
  20416. }
  20417. if (this.lightmapTexture) {
  20418. serializationObject.lightmapTexture = this.lightmapTexture.serialize();
  20419. serializationObject.useLightmapAsShadowmap = this.useLightmapAsShadowmap;
  20420. }
  20421. if (this.emissiveFresnelParameters) {
  20422. serializationObject.emissiveFresnelParameters = this.emissiveFresnelParameters.serialize();
  20423. }
  20424. if (this.specularTexture) {
  20425. serializationObject.specularTexture = this.specularTexture.serialize();
  20426. }
  20427. if (this.bumpTexture) {
  20428. serializationObject.bumpTexture = this.bumpTexture.serialize();
  20429. }
  20430. if (this.refractionTexture) {
  20431. serializationObject.refractionTexture = this.refractionTexture.serialize();
  20432. }
  20433. return serializationObject;
  20434. };
  20435. StandardMaterial.Parse = function (source, scene, rootUrl) {
  20436. var material = new StandardMaterial(source.name, scene);
  20437. material.ambientColor = BABYLON.Color3.FromArray(source.ambient);
  20438. material.diffuseColor = BABYLON.Color3.FromArray(source.diffuse);
  20439. material.specularColor = BABYLON.Color3.FromArray(source.specular);
  20440. material.specularPower = source.specularPower;
  20441. material.emissiveColor = BABYLON.Color3.FromArray(source.emissive);
  20442. material.useReflectionFresnelFromSpecular = source.useReflectionFresnelFromSpecular;
  20443. material.useEmissiveAsIllumination = source.useEmissiveAsIllumination;
  20444. material.indexOfRefraction = source.indexOfRefraction;
  20445. material.invertRefractionY = source.invertRefractionY;
  20446. material.alpha = source.alpha;
  20447. material.id = source.id;
  20448. if (source.disableDepthWrite) {
  20449. material.disableDepthWrite = source.disableDepthWrite;
  20450. }
  20451. BABYLON.Tags.AddTagsTo(material, source.tags);
  20452. material.backFaceCulling = source.backFaceCulling;
  20453. material.wireframe = source.wireframe;
  20454. if (source.diffuseTexture) {
  20455. material.diffuseTexture = BABYLON.Texture.Parse(source.diffuseTexture, scene, rootUrl);
  20456. }
  20457. if (source.diffuseFresnelParameters) {
  20458. material.diffuseFresnelParameters = FresnelParameters.Parse(source.diffuseFresnelParameters);
  20459. }
  20460. if (source.ambientTexture) {
  20461. material.ambientTexture = BABYLON.Texture.Parse(source.ambientTexture, scene, rootUrl);
  20462. }
  20463. if (source.opacityTexture) {
  20464. material.opacityTexture = BABYLON.Texture.Parse(source.opacityTexture, scene, rootUrl);
  20465. }
  20466. if (source.opacityFresnelParameters) {
  20467. material.opacityFresnelParameters = FresnelParameters.Parse(source.opacityFresnelParameters);
  20468. }
  20469. if (source.reflectionTexture) {
  20470. material.reflectionTexture = BABYLON.Texture.Parse(source.reflectionTexture, scene, rootUrl);
  20471. }
  20472. if (source.reflectionFresnelParameters) {
  20473. material.reflectionFresnelParameters = FresnelParameters.Parse(source.reflectionFresnelParameters);
  20474. }
  20475. if (source.refractionFresnelParameters) {
  20476. material.refractionFresnelParameters = FresnelParameters.Parse(source.refractionFresnelParameters);
  20477. }
  20478. if (source.emissiveTexture) {
  20479. material.emissiveTexture = BABYLON.Texture.Parse(source.emissiveTexture, scene, rootUrl);
  20480. }
  20481. if (source.lightmapTexture) {
  20482. material.lightmapTexture = BABYLON.Texture.Parse(source.lightmapTexture, scene, rootUrl);
  20483. material.useLightmapAsShadowmap = source.useLightmapAsShadowmap;
  20484. }
  20485. if (source.emissiveFresnelParameters) {
  20486. material.emissiveFresnelParameters = FresnelParameters.Parse(source.emissiveFresnelParameters);
  20487. }
  20488. if (source.specularTexture) {
  20489. material.specularTexture = BABYLON.Texture.Parse(source.specularTexture, scene, rootUrl);
  20490. }
  20491. if (source.bumpTexture) {
  20492. material.bumpTexture = BABYLON.Texture.Parse(source.bumpTexture, scene, rootUrl);
  20493. }
  20494. if (source.refractionTexture) {
  20495. material.refractionTexture = BABYLON.Texture.Parse(source.refractionTexture, scene, rootUrl);
  20496. }
  20497. if (source.checkReadyOnlyOnce) {
  20498. material.checkReadyOnlyOnce = source.checkReadyOnlyOnce;
  20499. }
  20500. return material;
  20501. };
  20502. StandardMaterial._scaledDiffuse = new BABYLON.Color3();
  20503. StandardMaterial._scaledSpecular = new BABYLON.Color3();
  20504. // Statics
  20505. // Flags used to enable or disable a type of texture for all Standard Materials
  20506. StandardMaterial.DiffuseTextureEnabled = true;
  20507. StandardMaterial.AmbientTextureEnabled = true;
  20508. StandardMaterial.OpacityTextureEnabled = true;
  20509. StandardMaterial.ReflectionTextureEnabled = true;
  20510. StandardMaterial.EmissiveTextureEnabled = true;
  20511. StandardMaterial.SpecularTextureEnabled = true;
  20512. StandardMaterial.BumpTextureEnabled = true;
  20513. StandardMaterial.FresnelEnabled = true;
  20514. StandardMaterial.LightmapTextureEnabled = true;
  20515. StandardMaterial.RefractionTextureEnabled = true;
  20516. return StandardMaterial;
  20517. })(BABYLON.Material);
  20518. BABYLON.StandardMaterial = StandardMaterial;
  20519. })(BABYLON || (BABYLON = {}));
  20520. var BABYLON;
  20521. (function (BABYLON) {
  20522. var MultiMaterial = (function (_super) {
  20523. __extends(MultiMaterial, _super);
  20524. function MultiMaterial(name, scene) {
  20525. _super.call(this, name, scene, true);
  20526. this.subMaterials = new Array();
  20527. scene.multiMaterials.push(this);
  20528. }
  20529. // Properties
  20530. MultiMaterial.prototype.getSubMaterial = function (index) {
  20531. if (index < 0 || index >= this.subMaterials.length) {
  20532. return this.getScene().defaultMaterial;
  20533. }
  20534. return this.subMaterials[index];
  20535. };
  20536. // Methods
  20537. MultiMaterial.prototype.isReady = function (mesh) {
  20538. for (var index = 0; index < this.subMaterials.length; index++) {
  20539. var subMaterial = this.subMaterials[index];
  20540. if (subMaterial) {
  20541. if (!this.subMaterials[index].isReady(mesh)) {
  20542. return false;
  20543. }
  20544. }
  20545. }
  20546. return true;
  20547. };
  20548. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  20549. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  20550. for (var index = 0; index < this.subMaterials.length; index++) {
  20551. var subMaterial = null;
  20552. if (cloneChildren) {
  20553. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  20554. }
  20555. else {
  20556. subMaterial = this.subMaterials[index];
  20557. }
  20558. newMultiMaterial.subMaterials.push(subMaterial);
  20559. }
  20560. return newMultiMaterial;
  20561. };
  20562. MultiMaterial.prototype.serialize = function () {
  20563. var serializationObject = {};
  20564. serializationObject.name = this.name;
  20565. serializationObject.id = this.id;
  20566. serializationObject.tags = BABYLON.Tags.GetTags(this);
  20567. serializationObject.materials = [];
  20568. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  20569. var subMat = this.subMaterials[matIndex];
  20570. if (subMat) {
  20571. serializationObject.materials.push(subMat.id);
  20572. }
  20573. else {
  20574. serializationObject.materials.push(null);
  20575. }
  20576. }
  20577. return serializationObject;
  20578. };
  20579. return MultiMaterial;
  20580. })(BABYLON.Material);
  20581. BABYLON.MultiMaterial = MultiMaterial;
  20582. })(BABYLON || (BABYLON = {}));
  20583. var BABYLON;
  20584. (function (BABYLON) {
  20585. var SceneLoader = (function () {
  20586. function SceneLoader() {
  20587. }
  20588. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  20589. get: function () {
  20590. return SceneLoader._ForceFullSceneLoadingForIncremental;
  20591. },
  20592. set: function (value) {
  20593. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  20594. },
  20595. enumerable: true,
  20596. configurable: true
  20597. });
  20598. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  20599. get: function () {
  20600. return SceneLoader._ShowLoadingScreen;
  20601. },
  20602. set: function (value) {
  20603. SceneLoader._ShowLoadingScreen = value;
  20604. },
  20605. enumerable: true,
  20606. configurable: true
  20607. });
  20608. SceneLoader._getPluginForFilename = function (sceneFilename) {
  20609. var dotPosition = sceneFilename.lastIndexOf(".");
  20610. var queryStringPosition = sceneFilename.indexOf("?");
  20611. if (queryStringPosition === -1) {
  20612. queryStringPosition = sceneFilename.length;
  20613. }
  20614. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  20615. for (var index = 0; index < this._registeredPlugins.length; index++) {
  20616. var plugin = this._registeredPlugins[index];
  20617. if (plugin.extensions.indexOf(extension) !== -1) {
  20618. return plugin;
  20619. }
  20620. }
  20621. return this._registeredPlugins[this._registeredPlugins.length - 1];
  20622. };
  20623. // Public functions
  20624. SceneLoader.GetPluginForExtension = function (extension) {
  20625. for (var index = 0; index < this._registeredPlugins.length; index++) {
  20626. var plugin = this._registeredPlugins[index];
  20627. if (plugin.extensions.indexOf(extension) !== -1) {
  20628. return plugin;
  20629. }
  20630. }
  20631. return null;
  20632. };
  20633. SceneLoader.RegisterPlugin = function (plugin) {
  20634. plugin.extensions = plugin.extensions.toLowerCase();
  20635. SceneLoader._registeredPlugins.push(plugin);
  20636. };
  20637. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  20638. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  20639. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  20640. return;
  20641. }
  20642. var loadingToken = {};
  20643. scene._addPendingData(loadingToken);
  20644. var manifestChecked = function (success) {
  20645. scene.database = database;
  20646. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  20647. var importMeshFromData = function (data) {
  20648. var meshes = [];
  20649. var particleSystems = [];
  20650. var skeletons = [];
  20651. try {
  20652. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  20653. if (onerror) {
  20654. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  20655. }
  20656. scene._removePendingData(loadingToken);
  20657. return;
  20658. }
  20659. }
  20660. catch (e) {
  20661. if (onerror) {
  20662. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename + ' (Exception: ' + e + ')');
  20663. }
  20664. scene._removePendingData(loadingToken);
  20665. return;
  20666. }
  20667. if (onsuccess) {
  20668. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  20669. onsuccess(meshes, particleSystems, skeletons);
  20670. scene._removePendingData(loadingToken);
  20671. }
  20672. };
  20673. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  20674. // Direct load
  20675. importMeshFromData(sceneFilename.substr(5));
  20676. return;
  20677. }
  20678. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  20679. importMeshFromData(data);
  20680. }, progressCallBack, database);
  20681. };
  20682. if (scene.getEngine().enableOfflineSupport) {
  20683. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  20684. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  20685. }
  20686. else {
  20687. manifestChecked(true);
  20688. }
  20689. };
  20690. /**
  20691. * Load a scene
  20692. * @param rootUrl a string that defines the root url for scene and resources
  20693. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  20694. * @param engine is the instance of BABYLON.Engine to use to create the scene
  20695. */
  20696. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  20697. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  20698. };
  20699. /**
  20700. * Append a scene
  20701. * @param rootUrl a string that defines the root url for scene and resources
  20702. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  20703. * @param scene is the instance of BABYLON.Scene to append to
  20704. */
  20705. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  20706. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  20707. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  20708. return;
  20709. }
  20710. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  20711. var database;
  20712. var loadingToken = {};
  20713. scene._addPendingData(loadingToken);
  20714. if (SceneLoader.ShowLoadingScreen) {
  20715. scene.getEngine().displayLoadingUI();
  20716. }
  20717. var loadSceneFromData = function (data) {
  20718. scene.database = database;
  20719. if (!plugin.load(scene, data, rootUrl)) {
  20720. if (onerror) {
  20721. onerror(scene);
  20722. }
  20723. scene._removePendingData(loadingToken);
  20724. scene.getEngine().hideLoadingUI();
  20725. return;
  20726. }
  20727. if (onsuccess) {
  20728. onsuccess(scene);
  20729. }
  20730. scene._removePendingData(loadingToken);
  20731. if (SceneLoader.ShowLoadingScreen) {
  20732. scene.executeWhenReady(function () {
  20733. scene.getEngine().hideLoadingUI();
  20734. });
  20735. }
  20736. };
  20737. var manifestChecked = function (success) {
  20738. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  20739. };
  20740. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  20741. // Direct load
  20742. loadSceneFromData(sceneFilename.substr(5));
  20743. return;
  20744. }
  20745. if (rootUrl.indexOf("file:") === -1) {
  20746. if (scene.getEngine().enableOfflineSupport) {
  20747. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  20748. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  20749. }
  20750. else {
  20751. manifestChecked(true);
  20752. }
  20753. }
  20754. else {
  20755. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  20756. }
  20757. };
  20758. // Flags
  20759. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  20760. SceneLoader._ShowLoadingScreen = true;
  20761. // Members
  20762. SceneLoader._registeredPlugins = new Array();
  20763. return SceneLoader;
  20764. })();
  20765. BABYLON.SceneLoader = SceneLoader;
  20766. ;
  20767. })(BABYLON || (BABYLON = {}));
  20768. var BABYLON;
  20769. (function (BABYLON) {
  20770. var Internals;
  20771. (function (Internals) {
  20772. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  20773. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  20774. var parsedMaterial = parsedData.materials[index];
  20775. if (parsedMaterial.id === id) {
  20776. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  20777. }
  20778. }
  20779. return null;
  20780. };
  20781. var isDescendantOf = function (mesh, names, hierarchyIds) {
  20782. names = (names instanceof Array) ? names : [names];
  20783. for (var i in names) {
  20784. if (mesh.name === names[i]) {
  20785. hierarchyIds.push(mesh.id);
  20786. return true;
  20787. }
  20788. }
  20789. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  20790. hierarchyIds.push(mesh.id);
  20791. return true;
  20792. }
  20793. return false;
  20794. };
  20795. BABYLON.SceneLoader.RegisterPlugin({
  20796. extensions: ".babylon",
  20797. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  20798. var parsedData = JSON.parse(data);
  20799. var loadedSkeletonsIds = [];
  20800. var loadedMaterialsIds = [];
  20801. var hierarchyIds = [];
  20802. var index;
  20803. var cache;
  20804. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  20805. var parsedMesh = parsedData.meshes[index];
  20806. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  20807. if (meshesNames instanceof Array) {
  20808. // Remove found mesh name from list.
  20809. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  20810. }
  20811. //Geometry?
  20812. if (parsedMesh.geometryId) {
  20813. //does the file contain geometries?
  20814. if (parsedData.geometries) {
  20815. //find the correct geometry and add it to the scene
  20816. var found = false;
  20817. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  20818. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  20819. return;
  20820. }
  20821. else {
  20822. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  20823. if (parsedGeometryData.id === parsedMesh.geometryId) {
  20824. switch (geometryType) {
  20825. case "boxes":
  20826. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  20827. break;
  20828. case "spheres":
  20829. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  20830. break;
  20831. case "cylinders":
  20832. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  20833. break;
  20834. case "toruses":
  20835. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  20836. break;
  20837. case "grounds":
  20838. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  20839. break;
  20840. case "planes":
  20841. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  20842. break;
  20843. case "torusKnots":
  20844. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  20845. break;
  20846. case "vertexData":
  20847. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  20848. break;
  20849. }
  20850. found = true;
  20851. }
  20852. });
  20853. }
  20854. });
  20855. if (!found) {
  20856. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  20857. }
  20858. }
  20859. }
  20860. // Material ?
  20861. if (parsedMesh.materialId) {
  20862. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  20863. if (!materialFound && parsedData.multiMaterials) {
  20864. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  20865. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  20866. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  20867. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  20868. var subMatId = parsedMultiMaterial.materials[matIndex];
  20869. loadedMaterialsIds.push(subMatId);
  20870. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  20871. }
  20872. loadedMaterialsIds.push(parsedMultiMaterial.id);
  20873. BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  20874. materialFound = true;
  20875. break;
  20876. }
  20877. }
  20878. }
  20879. if (!materialFound) {
  20880. loadedMaterialsIds.push(parsedMesh.materialId);
  20881. if (!parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl)) {
  20882. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  20883. }
  20884. }
  20885. }
  20886. // Skeleton ?
  20887. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  20888. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  20889. if (!skeletonAlreadyLoaded) {
  20890. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  20891. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  20892. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  20893. skeletons.push(BABYLON.Skeleton.Parse(parsedSkeleton, scene));
  20894. loadedSkeletonsIds.push(parsedSkeleton.id);
  20895. }
  20896. }
  20897. }
  20898. }
  20899. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  20900. meshes.push(mesh);
  20901. }
  20902. }
  20903. // Connecting parents
  20904. var currentMesh;
  20905. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  20906. currentMesh = scene.meshes[index];
  20907. if (currentMesh._waitingParentId) {
  20908. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  20909. currentMesh._waitingParentId = undefined;
  20910. }
  20911. }
  20912. // freeze and compute world matrix application
  20913. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  20914. currentMesh = scene.meshes[index];
  20915. if (currentMesh._waitingFreezeWorldMatrix) {
  20916. currentMesh.freezeWorldMatrix();
  20917. currentMesh._waitingFreezeWorldMatrix = undefined;
  20918. }
  20919. else {
  20920. currentMesh.computeWorldMatrix(true);
  20921. }
  20922. }
  20923. // Particles
  20924. if (parsedData.particleSystems) {
  20925. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  20926. var parsedParticleSystem = parsedData.particleSystems[index];
  20927. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  20928. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  20929. }
  20930. }
  20931. }
  20932. return true;
  20933. },
  20934. load: function (scene, data, rootUrl) {
  20935. var parsedData = JSON.parse(data);
  20936. // Scene
  20937. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  20938. scene.autoClear = parsedData.autoClear;
  20939. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  20940. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  20941. if (parsedData.gravity) {
  20942. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  20943. }
  20944. // Fog
  20945. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  20946. scene.fogMode = parsedData.fogMode;
  20947. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  20948. scene.fogStart = parsedData.fogStart;
  20949. scene.fogEnd = parsedData.fogEnd;
  20950. scene.fogDensity = parsedData.fogDensity;
  20951. }
  20952. //Physics
  20953. if (parsedData.physicsEnabled) {
  20954. var physicsPlugin;
  20955. if (parsedData.physicsEngine === "cannon") {
  20956. physicsPlugin = new BABYLON.CannonJSPlugin();
  20957. }
  20958. else if (parsedData.physicsEngine === "oimo") {
  20959. physicsPlugin = new BABYLON.OimoJSPlugin();
  20960. }
  20961. //else - default engine, which is currently oimo
  20962. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  20963. scene.enablePhysics(physicsGravity, physicsPlugin);
  20964. }
  20965. //collisions, if defined. otherwise, default is true
  20966. if (parsedData.collisionsEnabled != undefined) {
  20967. scene.collisionsEnabled = parsedData.collisionsEnabled;
  20968. }
  20969. scene.workerCollisions = !!parsedData.workerCollisions;
  20970. var index;
  20971. var cache;
  20972. // Lights
  20973. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  20974. var parsedLight = parsedData.lights[index];
  20975. BABYLON.Light.Parse(parsedLight, scene);
  20976. }
  20977. // Animations
  20978. if (parsedData.animations) {
  20979. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  20980. var parsedAnimation = parsedData.animations[index];
  20981. scene.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20982. }
  20983. }
  20984. // Materials
  20985. if (parsedData.materials) {
  20986. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  20987. var parsedMaterial = parsedData.materials[index];
  20988. BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  20989. }
  20990. }
  20991. if (parsedData.multiMaterials) {
  20992. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  20993. var parsedMultiMaterial = parsedData.multiMaterials[index];
  20994. BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  20995. }
  20996. }
  20997. // Skeletons
  20998. if (parsedData.skeletons) {
  20999. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  21000. var parsedSkeleton = parsedData.skeletons[index];
  21001. BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  21002. }
  21003. }
  21004. // Geometries
  21005. var geometries = parsedData.geometries;
  21006. if (geometries) {
  21007. // Boxes
  21008. var boxes = geometries.boxes;
  21009. if (boxes) {
  21010. for (index = 0, cache = boxes.length; index < cache; index++) {
  21011. var parsedBox = boxes[index];
  21012. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  21013. }
  21014. }
  21015. // Spheres
  21016. var spheres = geometries.spheres;
  21017. if (spheres) {
  21018. for (index = 0, cache = spheres.length; index < cache; index++) {
  21019. var parsedSphere = spheres[index];
  21020. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  21021. }
  21022. }
  21023. // Cylinders
  21024. var cylinders = geometries.cylinders;
  21025. if (cylinders) {
  21026. for (index = 0, cache = cylinders.length; index < cache; index++) {
  21027. var parsedCylinder = cylinders[index];
  21028. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  21029. }
  21030. }
  21031. // Toruses
  21032. var toruses = geometries.toruses;
  21033. if (toruses) {
  21034. for (index = 0, cache = toruses.length; index < cache; index++) {
  21035. var parsedTorus = toruses[index];
  21036. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  21037. }
  21038. }
  21039. // Grounds
  21040. var grounds = geometries.grounds;
  21041. if (grounds) {
  21042. for (index = 0, cache = grounds.length; index < cache; index++) {
  21043. var parsedGround = grounds[index];
  21044. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  21045. }
  21046. }
  21047. // Planes
  21048. var planes = geometries.planes;
  21049. if (planes) {
  21050. for (index = 0, cache = planes.length; index < cache; index++) {
  21051. var parsedPlane = planes[index];
  21052. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  21053. }
  21054. }
  21055. // TorusKnots
  21056. var torusKnots = geometries.torusKnots;
  21057. if (torusKnots) {
  21058. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  21059. var parsedTorusKnot = torusKnots[index];
  21060. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  21061. }
  21062. }
  21063. // VertexData
  21064. var vertexData = geometries.vertexData;
  21065. if (vertexData) {
  21066. for (index = 0, cache = vertexData.length; index < cache; index++) {
  21067. var parsedVertexData = vertexData[index];
  21068. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  21069. }
  21070. }
  21071. }
  21072. // Meshes
  21073. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  21074. var parsedMesh = parsedData.meshes[index];
  21075. BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  21076. }
  21077. // Cameras
  21078. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  21079. var parsedCamera = parsedData.cameras[index];
  21080. BABYLON.Camera.Parse(parsedCamera, scene);
  21081. }
  21082. if (parsedData.activeCameraID) {
  21083. scene.setActiveCameraByID(parsedData.activeCameraID);
  21084. }
  21085. // Browsing all the graph to connect the dots
  21086. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  21087. var camera = scene.cameras[index];
  21088. if (camera._waitingParentId) {
  21089. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  21090. camera._waitingParentId = undefined;
  21091. }
  21092. }
  21093. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  21094. var light = scene.lights[index];
  21095. if (light._waitingParentId) {
  21096. light.parent = scene.getLastEntryByID(light._waitingParentId);
  21097. light._waitingParentId = undefined;
  21098. }
  21099. }
  21100. // Sounds
  21101. var loadedSounds = [];
  21102. var loadedSound;
  21103. if (BABYLON.AudioEngine && parsedData.sounds) {
  21104. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  21105. var parsedSound = parsedData.sounds[index];
  21106. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  21107. if (!parsedSound.url)
  21108. parsedSound.url = parsedSound.name;
  21109. if (!loadedSounds[parsedSound.url]) {
  21110. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  21111. loadedSounds[parsedSound.url] = loadedSound;
  21112. }
  21113. else {
  21114. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  21115. }
  21116. }
  21117. else {
  21118. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  21119. }
  21120. }
  21121. }
  21122. loadedSounds = [];
  21123. // Connect parents & children and parse actions
  21124. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  21125. var mesh = scene.meshes[index];
  21126. if (mesh._waitingParentId) {
  21127. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  21128. mesh._waitingParentId = undefined;
  21129. }
  21130. if (mesh._waitingActions) {
  21131. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  21132. mesh._waitingActions = undefined;
  21133. }
  21134. }
  21135. // freeze world matrix application
  21136. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  21137. var currentMesh = scene.meshes[index];
  21138. if (currentMesh._waitingFreezeWorldMatrix) {
  21139. currentMesh.freezeWorldMatrix();
  21140. currentMesh._waitingFreezeWorldMatrix = undefined;
  21141. }
  21142. else {
  21143. currentMesh.computeWorldMatrix(true);
  21144. }
  21145. }
  21146. // Particles Systems
  21147. if (parsedData.particleSystems) {
  21148. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  21149. var parsedParticleSystem = parsedData.particleSystems[index];
  21150. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  21151. }
  21152. }
  21153. // Lens flares
  21154. if (parsedData.lensFlareSystems) {
  21155. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  21156. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  21157. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  21158. }
  21159. }
  21160. // Shadows
  21161. if (parsedData.shadowGenerators) {
  21162. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  21163. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  21164. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  21165. }
  21166. }
  21167. // Actions (scene)
  21168. if (parsedData.actions) {
  21169. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  21170. }
  21171. // Finish
  21172. return true;
  21173. }
  21174. });
  21175. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  21176. })(BABYLON || (BABYLON = {}));
  21177. var BABYLON;
  21178. (function (BABYLON) {
  21179. var SpriteManager = (function () {
  21180. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  21181. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  21182. this.name = name;
  21183. this.cellSize = cellSize;
  21184. this.sprites = new Array();
  21185. this.renderingGroupId = 0;
  21186. this.layerMask = 0x0FFFFFFF;
  21187. this.fogEnabled = true;
  21188. this.isPickable = false;
  21189. this._vertexDeclaration = [4, 4, 4, 4];
  21190. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  21191. this._capacity = capacity;
  21192. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  21193. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21194. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21195. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  21196. this._scene = scene;
  21197. this._scene.spriteManagers.push(this);
  21198. // VBO
  21199. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  21200. var indices = [];
  21201. var index = 0;
  21202. for (var count = 0; count < capacity; count++) {
  21203. indices.push(index);
  21204. indices.push(index + 1);
  21205. indices.push(index + 2);
  21206. indices.push(index);
  21207. indices.push(index + 2);
  21208. indices.push(index + 3);
  21209. index += 4;
  21210. }
  21211. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21212. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  21213. // Effects
  21214. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  21215. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  21216. }
  21217. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  21218. var arrayOffset = index * 16;
  21219. if (offsetX === 0)
  21220. offsetX = this._epsilon;
  21221. else if (offsetX === 1)
  21222. offsetX = 1 - this._epsilon;
  21223. if (offsetY === 0)
  21224. offsetY = this._epsilon;
  21225. else if (offsetY === 1)
  21226. offsetY = 1 - this._epsilon;
  21227. this._vertices[arrayOffset] = sprite.position.x;
  21228. this._vertices[arrayOffset + 1] = sprite.position.y;
  21229. this._vertices[arrayOffset + 2] = sprite.position.z;
  21230. this._vertices[arrayOffset + 3] = sprite.angle;
  21231. this._vertices[arrayOffset + 4] = sprite.width;
  21232. this._vertices[arrayOffset + 5] = sprite.height;
  21233. this._vertices[arrayOffset + 6] = offsetX;
  21234. this._vertices[arrayOffset + 7] = offsetY;
  21235. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  21236. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  21237. var offset = (sprite.cellIndex / rowSize) >> 0;
  21238. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  21239. this._vertices[arrayOffset + 11] = offset;
  21240. // Color
  21241. this._vertices[arrayOffset + 12] = sprite.color.r;
  21242. this._vertices[arrayOffset + 13] = sprite.color.g;
  21243. this._vertices[arrayOffset + 14] = sprite.color.b;
  21244. this._vertices[arrayOffset + 15] = sprite.color.a;
  21245. };
  21246. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  21247. var count = Math.min(this._capacity, this.sprites.length);
  21248. var min = BABYLON.Vector3.Zero();
  21249. var max = BABYLON.Vector3.Zero();
  21250. var distance = Number.MAX_VALUE;
  21251. var currentSprite;
  21252. var cameraSpacePosition = BABYLON.Vector3.Zero();
  21253. var cameraView = camera.getViewMatrix();
  21254. for (var index = 0; index < count; index++) {
  21255. var sprite = this.sprites[index];
  21256. if (!sprite) {
  21257. continue;
  21258. }
  21259. if (predicate) {
  21260. if (!predicate(sprite)) {
  21261. continue;
  21262. }
  21263. }
  21264. else if (!sprite.isPickable) {
  21265. continue;
  21266. }
  21267. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  21268. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  21269. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  21270. if (ray.intersectsBoxMinMax(min, max)) {
  21271. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  21272. if (distance > currentDistance) {
  21273. distance = currentDistance;
  21274. currentSprite = sprite;
  21275. if (fastCheck) {
  21276. break;
  21277. }
  21278. }
  21279. }
  21280. }
  21281. if (currentSprite) {
  21282. var result = new BABYLON.PickingInfo();
  21283. result.hit = true;
  21284. result.pickedSprite = currentSprite;
  21285. result.distance = distance;
  21286. return result;
  21287. }
  21288. return null;
  21289. };
  21290. SpriteManager.prototype.render = function () {
  21291. // Check
  21292. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  21293. return;
  21294. var engine = this._scene.getEngine();
  21295. var baseSize = this._spriteTexture.getBaseSize();
  21296. // Sprites
  21297. var deltaTime = engine.getDeltaTime();
  21298. var max = Math.min(this._capacity, this.sprites.length);
  21299. var rowSize = baseSize.width / this.cellSize;
  21300. var offset = 0;
  21301. for (var index = 0; index < max; index++) {
  21302. var sprite = this.sprites[index];
  21303. if (!sprite) {
  21304. continue;
  21305. }
  21306. sprite._animate(deltaTime);
  21307. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  21308. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  21309. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  21310. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  21311. }
  21312. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  21313. // Render
  21314. var effect = this._effectBase;
  21315. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  21316. effect = this._effectFog;
  21317. }
  21318. engine.enableEffect(effect);
  21319. var viewMatrix = this._scene.getViewMatrix();
  21320. effect.setTexture("diffuseSampler", this._spriteTexture);
  21321. effect.setMatrix("view", viewMatrix);
  21322. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  21323. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  21324. // Fog
  21325. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  21326. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  21327. effect.setColor3("vFogColor", this._scene.fogColor);
  21328. }
  21329. // VBOs
  21330. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  21331. // Draw order
  21332. engine.setDepthFunctionToLessOrEqual();
  21333. effect.setBool("alphaTest", true);
  21334. engine.setColorWrite(false);
  21335. engine.draw(true, 0, max * 6);
  21336. engine.setColorWrite(true);
  21337. effect.setBool("alphaTest", false);
  21338. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21339. engine.draw(true, 0, max * 6);
  21340. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21341. };
  21342. SpriteManager.prototype.dispose = function () {
  21343. if (this._vertexBuffer) {
  21344. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21345. this._vertexBuffer = null;
  21346. }
  21347. if (this._indexBuffer) {
  21348. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21349. this._indexBuffer = null;
  21350. }
  21351. if (this._spriteTexture) {
  21352. this._spriteTexture.dispose();
  21353. this._spriteTexture = null;
  21354. }
  21355. // Remove from scene
  21356. var index = this._scene.spriteManagers.indexOf(this);
  21357. this._scene.spriteManagers.splice(index, 1);
  21358. // Callback
  21359. if (this.onDispose) {
  21360. this.onDispose();
  21361. }
  21362. };
  21363. return SpriteManager;
  21364. })();
  21365. BABYLON.SpriteManager = SpriteManager;
  21366. })(BABYLON || (BABYLON = {}));
  21367. var BABYLON;
  21368. (function (BABYLON) {
  21369. var Sprite = (function () {
  21370. function Sprite(name, manager) {
  21371. this.name = name;
  21372. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21373. this.width = 1.0;
  21374. this.height = 1.0;
  21375. this.angle = 0;
  21376. this.cellIndex = 0;
  21377. this.invertU = 0;
  21378. this.invertV = 0;
  21379. this.animations = new Array();
  21380. this.isPickable = false;
  21381. this._animationStarted = false;
  21382. this._loopAnimation = false;
  21383. this._fromIndex = 0;
  21384. this._toIndex = 0;
  21385. this._delay = 0;
  21386. this._direction = 1;
  21387. this._frameCount = 0;
  21388. this._time = 0;
  21389. this._manager = manager;
  21390. this._manager.sprites.push(this);
  21391. this.position = BABYLON.Vector3.Zero();
  21392. }
  21393. Object.defineProperty(Sprite.prototype, "size", {
  21394. get: function () {
  21395. return this.width;
  21396. },
  21397. set: function (value) {
  21398. this.width = value;
  21399. this.height = value;
  21400. },
  21401. enumerable: true,
  21402. configurable: true
  21403. });
  21404. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  21405. this._fromIndex = from;
  21406. this._toIndex = to;
  21407. this._loopAnimation = loop;
  21408. this._delay = delay;
  21409. this._animationStarted = true;
  21410. this._direction = from < to ? 1 : -1;
  21411. this.cellIndex = from;
  21412. this._time = 0;
  21413. };
  21414. Sprite.prototype.stopAnimation = function () {
  21415. this._animationStarted = false;
  21416. };
  21417. Sprite.prototype._animate = function (deltaTime) {
  21418. if (!this._animationStarted)
  21419. return;
  21420. this._time += deltaTime;
  21421. if (this._time > this._delay) {
  21422. this._time = this._time % this._delay;
  21423. this.cellIndex += this._direction;
  21424. if (this.cellIndex == this._toIndex) {
  21425. if (this._loopAnimation) {
  21426. this.cellIndex = this._fromIndex;
  21427. }
  21428. else {
  21429. this._animationStarted = false;
  21430. if (this.disposeWhenFinishedAnimating) {
  21431. this.dispose();
  21432. }
  21433. }
  21434. }
  21435. }
  21436. };
  21437. Sprite.prototype.dispose = function () {
  21438. for (var i = 0; i < this._manager.sprites.length; i++) {
  21439. if (this._manager.sprites[i] == this) {
  21440. this._manager.sprites.splice(i, 1);
  21441. }
  21442. }
  21443. };
  21444. return Sprite;
  21445. })();
  21446. BABYLON.Sprite = Sprite;
  21447. })(BABYLON || (BABYLON = {}));
  21448. var BABYLON;
  21449. (function (BABYLON) {
  21450. var Layer = (function () {
  21451. function Layer(name, imgUrl, scene, isBackground, color) {
  21452. this.name = name;
  21453. this.scale = new BABYLON.Vector2(1, 1);
  21454. this.offset = new BABYLON.Vector2(0, 0);
  21455. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  21456. this._vertexDeclaration = [2];
  21457. this._vertexStrideSize = 2 * 4;
  21458. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  21459. this.isBackground = isBackground === undefined ? true : isBackground;
  21460. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  21461. this._scene = scene;
  21462. this._scene.layers.push(this);
  21463. // VBO
  21464. var vertices = [];
  21465. vertices.push(1, 1);
  21466. vertices.push(-1, 1);
  21467. vertices.push(-1, -1);
  21468. vertices.push(1, -1);
  21469. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  21470. // Indices
  21471. var indices = [];
  21472. indices.push(0);
  21473. indices.push(1);
  21474. indices.push(2);
  21475. indices.push(0);
  21476. indices.push(2);
  21477. indices.push(3);
  21478. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21479. // Effects
  21480. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  21481. }
  21482. Layer.prototype.render = function () {
  21483. // Check
  21484. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  21485. return;
  21486. var engine = this._scene.getEngine();
  21487. // Render
  21488. engine.enableEffect(this._effect);
  21489. engine.setState(false);
  21490. // Texture
  21491. this._effect.setTexture("textureSampler", this.texture);
  21492. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  21493. // Color
  21494. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  21495. // Scale / offset
  21496. this._effect.setVector2("offset", this.offset);
  21497. this._effect.setVector2("scale", this.scale);
  21498. // VBOs
  21499. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  21500. // Draw order
  21501. engine.setAlphaMode(this.alphaBlendingMode);
  21502. engine.draw(true, 0, 6);
  21503. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21504. };
  21505. Layer.prototype.dispose = function () {
  21506. if (this._vertexBuffer) {
  21507. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21508. this._vertexBuffer = null;
  21509. }
  21510. if (this._indexBuffer) {
  21511. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21512. this._indexBuffer = null;
  21513. }
  21514. if (this.texture) {
  21515. this.texture.dispose();
  21516. this.texture = null;
  21517. }
  21518. // Remove from scene
  21519. var index = this._scene.layers.indexOf(this);
  21520. this._scene.layers.splice(index, 1);
  21521. // Callback
  21522. if (this.onDispose) {
  21523. this.onDispose();
  21524. }
  21525. };
  21526. return Layer;
  21527. })();
  21528. BABYLON.Layer = Layer;
  21529. })(BABYLON || (BABYLON = {}));
  21530. var BABYLON;
  21531. (function (BABYLON) {
  21532. var Particle = (function () {
  21533. function Particle() {
  21534. this.position = BABYLON.Vector3.Zero();
  21535. this.direction = BABYLON.Vector3.Zero();
  21536. this.color = new BABYLON.Color4(0, 0, 0, 0);
  21537. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  21538. this.lifeTime = 1.0;
  21539. this.age = 0;
  21540. this.size = 0;
  21541. this.angle = 0;
  21542. this.angularSpeed = 0;
  21543. }
  21544. Particle.prototype.copyTo = function (other) {
  21545. other.position.copyFrom(this.position);
  21546. other.direction.copyFrom(this.direction);
  21547. other.color.copyFrom(this.color);
  21548. other.colorStep.copyFrom(this.colorStep);
  21549. other.lifeTime = this.lifeTime;
  21550. other.age = this.age;
  21551. other.size = this.size;
  21552. other.angle = this.angle;
  21553. other.angularSpeed = this.angularSpeed;
  21554. };
  21555. return Particle;
  21556. })();
  21557. BABYLON.Particle = Particle;
  21558. })(BABYLON || (BABYLON = {}));
  21559. var BABYLON;
  21560. (function (BABYLON) {
  21561. var randomNumber = function (min, max) {
  21562. if (min === max) {
  21563. return (min);
  21564. }
  21565. var random = Math.random();
  21566. return ((random * (max - min)) + min);
  21567. };
  21568. var ParticleSystem = (function () {
  21569. function ParticleSystem(name, capacity, scene, customEffect) {
  21570. var _this = this;
  21571. this.name = name;
  21572. // Members
  21573. this.animations = [];
  21574. this.renderingGroupId = 0;
  21575. this.emitter = null;
  21576. this.emitRate = 10;
  21577. this.manualEmitCount = -1;
  21578. this.updateSpeed = 0.01;
  21579. this.targetStopDuration = 0;
  21580. this.disposeOnStop = false;
  21581. this.minEmitPower = 1;
  21582. this.maxEmitPower = 1;
  21583. this.minLifeTime = 1;
  21584. this.maxLifeTime = 1;
  21585. this.minSize = 1;
  21586. this.maxSize = 1;
  21587. this.minAngularSpeed = 0;
  21588. this.maxAngularSpeed = 0;
  21589. this.layerMask = 0x0FFFFFFF;
  21590. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  21591. this.forceDepthWrite = false;
  21592. this.gravity = BABYLON.Vector3.Zero();
  21593. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  21594. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  21595. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  21596. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  21597. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21598. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21599. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  21600. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21601. this.particles = new Array();
  21602. this._vertexDeclaration = [3, 4, 4];
  21603. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  21604. this._stockParticles = new Array();
  21605. this._newPartsExcess = 0;
  21606. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  21607. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  21608. this._scaledDirection = BABYLON.Vector3.Zero();
  21609. this._scaledGravity = BABYLON.Vector3.Zero();
  21610. this._currentRenderId = -1;
  21611. this._started = false;
  21612. this._stopped = false;
  21613. this._actualFrame = 0;
  21614. this.id = name;
  21615. this._capacity = capacity;
  21616. this._scene = scene;
  21617. this._customEffect = customEffect;
  21618. scene.particleSystems.push(this);
  21619. // VBO
  21620. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  21621. var indices = [];
  21622. var index = 0;
  21623. for (var count = 0; count < capacity; count++) {
  21624. indices.push(index);
  21625. indices.push(index + 1);
  21626. indices.push(index + 2);
  21627. indices.push(index);
  21628. indices.push(index + 2);
  21629. indices.push(index + 3);
  21630. index += 4;
  21631. }
  21632. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21633. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  21634. // Default behaviors
  21635. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  21636. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  21637. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  21638. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  21639. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  21640. };
  21641. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  21642. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  21643. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  21644. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  21645. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  21646. };
  21647. this.updateFunction = function (particles) {
  21648. for (var index = 0; index < particles.length; index++) {
  21649. var particle = particles[index];
  21650. particle.age += _this._scaledUpdateSpeed;
  21651. if (particle.age >= particle.lifeTime) {
  21652. _this.recycleParticle(particle);
  21653. index--;
  21654. continue;
  21655. }
  21656. else {
  21657. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  21658. particle.color.addInPlace(_this._scaledColorStep);
  21659. if (particle.color.a < 0)
  21660. particle.color.a = 0;
  21661. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  21662. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  21663. particle.position.addInPlace(_this._scaledDirection);
  21664. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  21665. particle.direction.addInPlace(_this._scaledGravity);
  21666. }
  21667. }
  21668. };
  21669. }
  21670. ParticleSystem.prototype.recycleParticle = function (particle) {
  21671. var lastParticle = this.particles.pop();
  21672. if (lastParticle !== particle) {
  21673. lastParticle.copyTo(particle);
  21674. this._stockParticles.push(lastParticle);
  21675. }
  21676. };
  21677. ParticleSystem.prototype.getCapacity = function () {
  21678. return this._capacity;
  21679. };
  21680. ParticleSystem.prototype.isAlive = function () {
  21681. return this._alive;
  21682. };
  21683. ParticleSystem.prototype.isStarted = function () {
  21684. return this._started;
  21685. };
  21686. ParticleSystem.prototype.start = function () {
  21687. this._started = true;
  21688. this._stopped = false;
  21689. this._actualFrame = 0;
  21690. };
  21691. ParticleSystem.prototype.stop = function () {
  21692. this._stopped = true;
  21693. };
  21694. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  21695. var offset = index * 11;
  21696. this._vertices[offset] = particle.position.x;
  21697. this._vertices[offset + 1] = particle.position.y;
  21698. this._vertices[offset + 2] = particle.position.z;
  21699. this._vertices[offset + 3] = particle.color.r;
  21700. this._vertices[offset + 4] = particle.color.g;
  21701. this._vertices[offset + 5] = particle.color.b;
  21702. this._vertices[offset + 6] = particle.color.a;
  21703. this._vertices[offset + 7] = particle.angle;
  21704. this._vertices[offset + 8] = particle.size;
  21705. this._vertices[offset + 9] = offsetX;
  21706. this._vertices[offset + 10] = offsetY;
  21707. };
  21708. ParticleSystem.prototype._update = function (newParticles) {
  21709. // Update current
  21710. this._alive = this.particles.length > 0;
  21711. this.updateFunction(this.particles);
  21712. // Add new ones
  21713. var worldMatrix;
  21714. if (this.emitter.position) {
  21715. worldMatrix = this.emitter.getWorldMatrix();
  21716. }
  21717. else {
  21718. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  21719. }
  21720. var particle;
  21721. for (var index = 0; index < newParticles; index++) {
  21722. if (this.particles.length === this._capacity) {
  21723. break;
  21724. }
  21725. if (this._stockParticles.length !== 0) {
  21726. particle = this._stockParticles.pop();
  21727. particle.age = 0;
  21728. }
  21729. else {
  21730. particle = new BABYLON.Particle();
  21731. }
  21732. this.particles.push(particle);
  21733. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  21734. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  21735. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  21736. particle.size = randomNumber(this.minSize, this.maxSize);
  21737. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  21738. this.startPositionFunction(worldMatrix, particle.position, particle);
  21739. var step = randomNumber(0, 1.0);
  21740. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  21741. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  21742. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  21743. }
  21744. };
  21745. ParticleSystem.prototype._getEffect = function () {
  21746. if (this._customEffect) {
  21747. return this._customEffect;
  21748. }
  21749. ;
  21750. var defines = [];
  21751. if (this._scene.clipPlane) {
  21752. defines.push("#define CLIPPLANE");
  21753. }
  21754. // Effect
  21755. var join = defines.join("\n");
  21756. if (this._cachedDefines !== join) {
  21757. this._cachedDefines = join;
  21758. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  21759. }
  21760. return this._effect;
  21761. };
  21762. ParticleSystem.prototype.animate = function () {
  21763. if (!this._started)
  21764. return;
  21765. var effect = this._getEffect();
  21766. // Check
  21767. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  21768. return;
  21769. if (this._currentRenderId === this._scene.getRenderId()) {
  21770. return;
  21771. }
  21772. this._currentRenderId = this._scene.getRenderId();
  21773. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  21774. // determine the number of particles we need to create
  21775. var newParticles;
  21776. if (this.manualEmitCount > -1) {
  21777. newParticles = this.manualEmitCount;
  21778. this._newPartsExcess = 0;
  21779. this.manualEmitCount = 0;
  21780. }
  21781. else {
  21782. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  21783. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  21784. }
  21785. if (this._newPartsExcess > 1.0) {
  21786. newParticles += this._newPartsExcess >> 0;
  21787. this._newPartsExcess -= this._newPartsExcess >> 0;
  21788. }
  21789. this._alive = false;
  21790. if (!this._stopped) {
  21791. this._actualFrame += this._scaledUpdateSpeed;
  21792. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  21793. this.stop();
  21794. }
  21795. else {
  21796. newParticles = 0;
  21797. }
  21798. this._update(newParticles);
  21799. // Stopped?
  21800. if (this._stopped) {
  21801. if (!this._alive) {
  21802. this._started = false;
  21803. if (this.disposeOnStop) {
  21804. this._scene._toBeDisposed.push(this);
  21805. }
  21806. }
  21807. }
  21808. // Update VBO
  21809. var offset = 0;
  21810. for (var index = 0; index < this.particles.length; index++) {
  21811. var particle = this.particles[index];
  21812. this._appendParticleVertex(offset++, particle, 0, 0);
  21813. this._appendParticleVertex(offset++, particle, 1, 0);
  21814. this._appendParticleVertex(offset++, particle, 1, 1);
  21815. this._appendParticleVertex(offset++, particle, 0, 1);
  21816. }
  21817. var engine = this._scene.getEngine();
  21818. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  21819. };
  21820. ParticleSystem.prototype.render = function () {
  21821. var effect = this._getEffect();
  21822. // Check
  21823. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  21824. return 0;
  21825. var engine = this._scene.getEngine();
  21826. // Render
  21827. engine.enableEffect(effect);
  21828. engine.setState(false);
  21829. var viewMatrix = this._scene.getViewMatrix();
  21830. effect.setTexture("diffuseSampler", this.particleTexture);
  21831. effect.setMatrix("view", viewMatrix);
  21832. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  21833. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  21834. if (this._scene.clipPlane) {
  21835. var clipPlane = this._scene.clipPlane;
  21836. var invView = viewMatrix.clone();
  21837. invView.invert();
  21838. effect.setMatrix("invView", invView);
  21839. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  21840. }
  21841. // VBOs
  21842. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  21843. // Draw order
  21844. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  21845. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  21846. }
  21847. else {
  21848. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21849. }
  21850. if (this.forceDepthWrite) {
  21851. engine.setDepthWrite(true);
  21852. }
  21853. engine.draw(true, 0, this.particles.length * 6);
  21854. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21855. return this.particles.length;
  21856. };
  21857. ParticleSystem.prototype.dispose = function () {
  21858. if (this._vertexBuffer) {
  21859. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21860. this._vertexBuffer = null;
  21861. }
  21862. if (this._indexBuffer) {
  21863. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21864. this._indexBuffer = null;
  21865. }
  21866. if (this.particleTexture) {
  21867. this.particleTexture.dispose();
  21868. this.particleTexture = null;
  21869. }
  21870. // Remove from scene
  21871. var index = this._scene.particleSystems.indexOf(this);
  21872. this._scene.particleSystems.splice(index, 1);
  21873. // Callback
  21874. if (this.onDispose) {
  21875. this.onDispose();
  21876. }
  21877. };
  21878. // Clone
  21879. ParticleSystem.prototype.clone = function (name, newEmitter) {
  21880. var result = new ParticleSystem(name, this._capacity, this._scene);
  21881. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  21882. if (newEmitter === undefined) {
  21883. newEmitter = this.emitter;
  21884. }
  21885. result.emitter = newEmitter;
  21886. if (this.particleTexture) {
  21887. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  21888. }
  21889. result.start();
  21890. return result;
  21891. };
  21892. ParticleSystem.prototype.serialize = function () {
  21893. var serializationObject = {};
  21894. serializationObject.name = this.name;
  21895. // Emitter
  21896. if (this.emitter.position) {
  21897. serializationObject.emitterId = this.emitter.id;
  21898. }
  21899. else {
  21900. serializationObject.emitter = this.emitter.asArray();
  21901. ;
  21902. }
  21903. serializationObject.capacity = this.getCapacity();
  21904. if (this.particleTexture) {
  21905. serializationObject.textureName = this.particleTexture.name;
  21906. }
  21907. // Animations
  21908. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21909. // Particle system
  21910. serializationObject.minAngularSpeed = this.minAngularSpeed;
  21911. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  21912. serializationObject.minSize = this.minSize;
  21913. serializationObject.maxSize = this.maxSize;
  21914. serializationObject.minEmitPower = this.minEmitPower;
  21915. serializationObject.maxEmitPower = this.maxEmitPower;
  21916. serializationObject.minLifeTime = this.minLifeTime;
  21917. serializationObject.maxLifeTime = this.maxLifeTime;
  21918. serializationObject.emitRate = this.emitRate;
  21919. serializationObject.minEmitBox = this.minEmitBox.asArray();
  21920. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  21921. serializationObject.gravity = this.gravity.asArray();
  21922. serializationObject.direction1 = this.direction1.asArray();
  21923. serializationObject.direction2 = this.direction2.asArray();
  21924. serializationObject.color1 = this.color1.asArray();
  21925. serializationObject.color2 = this.color2.asArray();
  21926. serializationObject.colorDead = this.colorDead.asArray();
  21927. serializationObject.updateSpeed = this.updateSpeed;
  21928. serializationObject.targetStopDuration = this.targetStopDuration;
  21929. serializationObject.textureMask = this.textureMask.asArray();
  21930. serializationObject.blendMode = this.blendMode;
  21931. return serializationObject;
  21932. };
  21933. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  21934. var name = parsedParticleSystem.name;
  21935. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene);
  21936. // Texture
  21937. if (parsedParticleSystem.textureName) {
  21938. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  21939. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  21940. }
  21941. // Emitter
  21942. if (parsedParticleSystem.emitterId) {
  21943. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  21944. }
  21945. else {
  21946. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  21947. }
  21948. // Animations
  21949. if (parsedParticleSystem.animations) {
  21950. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  21951. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  21952. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21953. }
  21954. }
  21955. // Particle system
  21956. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  21957. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  21958. particleSystem.minSize = parsedParticleSystem.minSize;
  21959. particleSystem.maxSize = parsedParticleSystem.maxSize;
  21960. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  21961. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  21962. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  21963. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  21964. particleSystem.emitRate = parsedParticleSystem.emitRate;
  21965. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  21966. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  21967. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  21968. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  21969. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  21970. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  21971. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  21972. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  21973. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  21974. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  21975. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  21976. particleSystem.blendMode = parsedParticleSystem.blendMode;
  21977. particleSystem.start();
  21978. return particleSystem;
  21979. };
  21980. // Statics
  21981. ParticleSystem.BLENDMODE_ONEONE = 0;
  21982. ParticleSystem.BLENDMODE_STANDARD = 1;
  21983. return ParticleSystem;
  21984. })();
  21985. BABYLON.ParticleSystem = ParticleSystem;
  21986. })(BABYLON || (BABYLON = {}));
  21987. var BABYLON;
  21988. (function (BABYLON) {
  21989. var AnimationRange = (function () {
  21990. function AnimationRange(name, from, to) {
  21991. this.name = name;
  21992. this.from = from;
  21993. this.to = to;
  21994. }
  21995. return AnimationRange;
  21996. })();
  21997. BABYLON.AnimationRange = AnimationRange;
  21998. /**
  21999. * Composed of a frame, and an action function
  22000. */
  22001. var AnimationEvent = (function () {
  22002. function AnimationEvent(frame, action, onlyOnce) {
  22003. this.frame = frame;
  22004. this.action = action;
  22005. this.onlyOnce = onlyOnce;
  22006. this.isDone = false;
  22007. }
  22008. return AnimationEvent;
  22009. })();
  22010. BABYLON.AnimationEvent = AnimationEvent;
  22011. var Animation = (function () {
  22012. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  22013. this.name = name;
  22014. this.targetProperty = targetProperty;
  22015. this.framePerSecond = framePerSecond;
  22016. this.dataType = dataType;
  22017. this.loopMode = loopMode;
  22018. this._offsetsCache = {};
  22019. this._highLimitsCache = {};
  22020. this._stopped = false;
  22021. // The set of event that will be linked to this animation
  22022. this._events = new Array();
  22023. this.allowMatricesInterpolation = false;
  22024. this._ranges = {};
  22025. this.targetPropertyPath = targetProperty.split(".");
  22026. this.dataType = dataType;
  22027. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  22028. }
  22029. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  22030. var dataType = undefined;
  22031. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  22032. dataType = Animation.ANIMATIONTYPE_FLOAT;
  22033. }
  22034. else if (from instanceof BABYLON.Quaternion) {
  22035. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  22036. }
  22037. else if (from instanceof BABYLON.Vector3) {
  22038. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  22039. }
  22040. else if (from instanceof BABYLON.Vector2) {
  22041. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  22042. }
  22043. else if (from instanceof BABYLON.Color3) {
  22044. dataType = Animation.ANIMATIONTYPE_COLOR3;
  22045. }
  22046. if (dataType == undefined) {
  22047. return null;
  22048. }
  22049. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  22050. var keys = [];
  22051. keys.push({ frame: 0, value: from });
  22052. keys.push({ frame: totalFrame, value: to });
  22053. animation.setKeys(keys);
  22054. if (easingFunction !== undefined) {
  22055. animation.setEasingFunction(easingFunction);
  22056. }
  22057. return animation;
  22058. };
  22059. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  22060. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  22061. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  22062. };
  22063. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  22064. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  22065. node.animations.push(animation);
  22066. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  22067. };
  22068. // Methods
  22069. /**
  22070. * Add an event to this animation.
  22071. */
  22072. Animation.prototype.addEvent = function (event) {
  22073. this._events.push(event);
  22074. };
  22075. /**
  22076. * Remove all events found at the given frame
  22077. * @param frame
  22078. */
  22079. Animation.prototype.removeEvents = function (frame) {
  22080. for (var index = 0; index < this._events.length; index++) {
  22081. if (this._events[index].frame === frame) {
  22082. this._events.splice(index, 1);
  22083. index--;
  22084. }
  22085. }
  22086. };
  22087. Animation.prototype.createRange = function (name, from, to) {
  22088. // check name not already in use; could happen for bones after serialized
  22089. if (!this._ranges[name]) {
  22090. this._ranges[name] = new AnimationRange(name, from, to);
  22091. }
  22092. };
  22093. Animation.prototype.deleteRange = function (name, deleteFrames) {
  22094. if (deleteFrames === void 0) { deleteFrames = true; }
  22095. if (this._ranges[name]) {
  22096. if (deleteFrames) {
  22097. var from = this._ranges[name].from;
  22098. var to = this._ranges[name].to;
  22099. // this loop MUST go high to low for multiple splices to work
  22100. for (var key = this._keys.length - 1; key >= 0; key--) {
  22101. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  22102. this._keys.splice(key, 1);
  22103. }
  22104. }
  22105. }
  22106. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  22107. }
  22108. };
  22109. Animation.prototype.getRange = function (name) {
  22110. return this._ranges[name];
  22111. };
  22112. Animation.prototype.reset = function () {
  22113. this._offsetsCache = {};
  22114. this._highLimitsCache = {};
  22115. this.currentFrame = 0;
  22116. };
  22117. Animation.prototype.isStopped = function () {
  22118. return this._stopped;
  22119. };
  22120. Animation.prototype.getKeys = function () {
  22121. return this._keys;
  22122. };
  22123. Animation.prototype.getHighestFrame = function () {
  22124. var ret = 0;
  22125. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  22126. if (ret < this._keys[key].frame) {
  22127. ret = this._keys[key].frame;
  22128. }
  22129. }
  22130. return ret;
  22131. };
  22132. Animation.prototype.getEasingFunction = function () {
  22133. return this._easingFunction;
  22134. };
  22135. Animation.prototype.setEasingFunction = function (easingFunction) {
  22136. this._easingFunction = easingFunction;
  22137. };
  22138. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  22139. return startValue + (endValue - startValue) * gradient;
  22140. };
  22141. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  22142. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  22143. };
  22144. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  22145. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  22146. };
  22147. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  22148. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  22149. };
  22150. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  22151. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  22152. };
  22153. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  22154. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  22155. };
  22156. Animation.prototype.clone = function () {
  22157. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  22158. if (this._keys) {
  22159. clone.setKeys(this._keys);
  22160. }
  22161. return clone;
  22162. };
  22163. Animation.prototype.setKeys = function (values) {
  22164. this._keys = values.slice(0);
  22165. this._offsetsCache = {};
  22166. this._highLimitsCache = {};
  22167. };
  22168. Animation.prototype._getKeyValue = function (value) {
  22169. if (typeof value === "function") {
  22170. return value();
  22171. }
  22172. return value;
  22173. };
  22174. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  22175. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  22176. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  22177. }
  22178. this.currentFrame = currentFrame;
  22179. // Try to get a hash to find the right key
  22180. 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));
  22181. if (this._keys[startKey].frame >= currentFrame) {
  22182. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  22183. startKey--;
  22184. }
  22185. }
  22186. for (var key = startKey; key < this._keys.length; key++) {
  22187. if (this._keys[key + 1].frame >= currentFrame) {
  22188. var startValue = this._getKeyValue(this._keys[key].value);
  22189. var endValue = this._getKeyValue(this._keys[key + 1].value);
  22190. // gradient : percent of currentFrame between the frame inf and the frame sup
  22191. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  22192. // check for easingFunction and correction of gradient
  22193. if (this._easingFunction != null) {
  22194. gradient = this._easingFunction.ease(gradient);
  22195. }
  22196. switch (this.dataType) {
  22197. // Float
  22198. case Animation.ANIMATIONTYPE_FLOAT:
  22199. switch (loopMode) {
  22200. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22201. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22202. return this.floatInterpolateFunction(startValue, endValue, gradient);
  22203. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22204. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  22205. }
  22206. break;
  22207. // Quaternion
  22208. case Animation.ANIMATIONTYPE_QUATERNION:
  22209. var quaternion = null;
  22210. switch (loopMode) {
  22211. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22212. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22213. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  22214. break;
  22215. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22216. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  22217. break;
  22218. }
  22219. return quaternion;
  22220. // Vector3
  22221. case Animation.ANIMATIONTYPE_VECTOR3:
  22222. switch (loopMode) {
  22223. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22224. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22225. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  22226. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22227. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  22228. }
  22229. // Vector2
  22230. case Animation.ANIMATIONTYPE_VECTOR2:
  22231. switch (loopMode) {
  22232. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22233. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22234. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  22235. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22236. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  22237. }
  22238. // Color3
  22239. case Animation.ANIMATIONTYPE_COLOR3:
  22240. switch (loopMode) {
  22241. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22242. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22243. return this.color3InterpolateFunction(startValue, endValue, gradient);
  22244. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22245. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  22246. }
  22247. // Matrix
  22248. case Animation.ANIMATIONTYPE_MATRIX:
  22249. switch (loopMode) {
  22250. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22251. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22252. if (this.allowMatricesInterpolation) {
  22253. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  22254. }
  22255. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22256. return startValue;
  22257. }
  22258. default:
  22259. break;
  22260. }
  22261. break;
  22262. }
  22263. }
  22264. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  22265. };
  22266. Animation.prototype.setValue = function (currentValue) {
  22267. // Set value
  22268. if (this.targetPropertyPath.length > 1) {
  22269. var property = this._target[this.targetPropertyPath[0]];
  22270. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  22271. property = property[this.targetPropertyPath[index]];
  22272. }
  22273. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  22274. }
  22275. else {
  22276. this._target[this.targetPropertyPath[0]] = currentValue;
  22277. }
  22278. if (this._target.markAsDirty) {
  22279. this._target.markAsDirty(this.targetProperty);
  22280. }
  22281. };
  22282. Animation.prototype.goToFrame = function (frame) {
  22283. if (frame < this._keys[0].frame) {
  22284. frame = this._keys[0].frame;
  22285. }
  22286. else if (frame > this._keys[this._keys.length - 1].frame) {
  22287. frame = this._keys[this._keys.length - 1].frame;
  22288. }
  22289. var currentValue = this._interpolate(frame, 0, this.loopMode);
  22290. this.setValue(currentValue);
  22291. };
  22292. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  22293. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  22294. this._stopped = true;
  22295. return false;
  22296. }
  22297. var returnValue = true;
  22298. // Adding a start key at frame 0 if missing
  22299. if (this._keys[0].frame !== 0) {
  22300. var newKey = { frame: 0, value: this._keys[0].value };
  22301. this._keys.splice(0, 0, newKey);
  22302. }
  22303. // Check limits
  22304. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  22305. from = this._keys[0].frame;
  22306. }
  22307. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  22308. to = this._keys[this._keys.length - 1].frame;
  22309. }
  22310. // Compute ratio
  22311. var range = to - from;
  22312. var offsetValue;
  22313. // ratio represents the frame delta between from and to
  22314. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  22315. var highLimitValue = 0;
  22316. if (ratio > range && !loop) {
  22317. returnValue = false;
  22318. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  22319. }
  22320. else {
  22321. // Get max value if required
  22322. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  22323. var keyOffset = to.toString() + from.toString();
  22324. if (!this._offsetsCache[keyOffset]) {
  22325. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  22326. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  22327. switch (this.dataType) {
  22328. // Float
  22329. case Animation.ANIMATIONTYPE_FLOAT:
  22330. this._offsetsCache[keyOffset] = toValue - fromValue;
  22331. break;
  22332. // Quaternion
  22333. case Animation.ANIMATIONTYPE_QUATERNION:
  22334. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  22335. break;
  22336. // Vector3
  22337. case Animation.ANIMATIONTYPE_VECTOR3:
  22338. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  22339. // Vector2
  22340. case Animation.ANIMATIONTYPE_VECTOR2:
  22341. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  22342. // Color3
  22343. case Animation.ANIMATIONTYPE_COLOR3:
  22344. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  22345. default:
  22346. break;
  22347. }
  22348. this._highLimitsCache[keyOffset] = toValue;
  22349. }
  22350. highLimitValue = this._highLimitsCache[keyOffset];
  22351. offsetValue = this._offsetsCache[keyOffset];
  22352. }
  22353. }
  22354. if (offsetValue === undefined) {
  22355. switch (this.dataType) {
  22356. // Float
  22357. case Animation.ANIMATIONTYPE_FLOAT:
  22358. offsetValue = 0;
  22359. break;
  22360. // Quaternion
  22361. case Animation.ANIMATIONTYPE_QUATERNION:
  22362. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  22363. break;
  22364. // Vector3
  22365. case Animation.ANIMATIONTYPE_VECTOR3:
  22366. offsetValue = BABYLON.Vector3.Zero();
  22367. break;
  22368. // Vector2
  22369. case Animation.ANIMATIONTYPE_VECTOR2:
  22370. offsetValue = BABYLON.Vector2.Zero();
  22371. break;
  22372. // Color3
  22373. case Animation.ANIMATIONTYPE_COLOR3:
  22374. offsetValue = BABYLON.Color3.Black();
  22375. }
  22376. }
  22377. // Compute value
  22378. var repeatCount = (ratio / range) >> 0;
  22379. var currentFrame = returnValue ? from + ratio % range : to;
  22380. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  22381. // Set value
  22382. this.setValue(currentValue);
  22383. // Check events
  22384. for (var index = 0; index < this._events.length; index++) {
  22385. if (currentFrame >= this._events[index].frame) {
  22386. var event = this._events[index];
  22387. if (!event.isDone) {
  22388. // If event should be done only once, remove it.
  22389. if (event.onlyOnce) {
  22390. this._events.splice(index, 1);
  22391. index--;
  22392. }
  22393. event.isDone = true;
  22394. event.action();
  22395. } // Don't do anything if the event has already be done.
  22396. }
  22397. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  22398. // reset event, the animation is looping
  22399. this._events[index].isDone = false;
  22400. }
  22401. }
  22402. if (!returnValue) {
  22403. this._stopped = true;
  22404. }
  22405. return returnValue;
  22406. };
  22407. Animation.prototype.serialize = function () {
  22408. var serializationObject = {};
  22409. serializationObject.name = this.name;
  22410. serializationObject.property = this.targetProperty;
  22411. serializationObject.framePerSecond = this.framePerSecond;
  22412. serializationObject.dataType = this.dataType;
  22413. serializationObject.loopBehavior = this.loopMode;
  22414. var dataType = this.dataType;
  22415. serializationObject.keys = [];
  22416. var keys = this.getKeys();
  22417. for (var index = 0; index < keys.length; index++) {
  22418. var animationKey = keys[index];
  22419. var key = {};
  22420. key.frame = animationKey.frame;
  22421. switch (dataType) {
  22422. case Animation.ANIMATIONTYPE_FLOAT:
  22423. key.values = [animationKey.value];
  22424. break;
  22425. case Animation.ANIMATIONTYPE_QUATERNION:
  22426. case Animation.ANIMATIONTYPE_MATRIX:
  22427. case Animation.ANIMATIONTYPE_VECTOR3:
  22428. case Animation.ANIMATIONTYPE_COLOR3:
  22429. key.values = animationKey.value.asArray();
  22430. break;
  22431. }
  22432. serializationObject.keys.push(key);
  22433. }
  22434. serializationObject.ranges = [];
  22435. for (var name in this._ranges) {
  22436. var range = {};
  22437. range.name = name;
  22438. range.from = this._ranges[name].from;
  22439. range.to = this._ranges[name].to;
  22440. serializationObject.ranges.push(range);
  22441. }
  22442. return serializationObject;
  22443. };
  22444. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  22445. get: function () {
  22446. return Animation._ANIMATIONTYPE_FLOAT;
  22447. },
  22448. enumerable: true,
  22449. configurable: true
  22450. });
  22451. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  22452. get: function () {
  22453. return Animation._ANIMATIONTYPE_VECTOR3;
  22454. },
  22455. enumerable: true,
  22456. configurable: true
  22457. });
  22458. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  22459. get: function () {
  22460. return Animation._ANIMATIONTYPE_VECTOR2;
  22461. },
  22462. enumerable: true,
  22463. configurable: true
  22464. });
  22465. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  22466. get: function () {
  22467. return Animation._ANIMATIONTYPE_QUATERNION;
  22468. },
  22469. enumerable: true,
  22470. configurable: true
  22471. });
  22472. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  22473. get: function () {
  22474. return Animation._ANIMATIONTYPE_MATRIX;
  22475. },
  22476. enumerable: true,
  22477. configurable: true
  22478. });
  22479. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  22480. get: function () {
  22481. return Animation._ANIMATIONTYPE_COLOR3;
  22482. },
  22483. enumerable: true,
  22484. configurable: true
  22485. });
  22486. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  22487. get: function () {
  22488. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  22489. },
  22490. enumerable: true,
  22491. configurable: true
  22492. });
  22493. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  22494. get: function () {
  22495. return Animation._ANIMATIONLOOPMODE_CYCLE;
  22496. },
  22497. enumerable: true,
  22498. configurable: true
  22499. });
  22500. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  22501. get: function () {
  22502. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  22503. },
  22504. enumerable: true,
  22505. configurable: true
  22506. });
  22507. Animation.Parse = function (parsedAnimation) {
  22508. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  22509. var dataType = parsedAnimation.dataType;
  22510. var keys = [];
  22511. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  22512. var key = parsedAnimation.keys[index];
  22513. var data;
  22514. switch (dataType) {
  22515. case Animation.ANIMATIONTYPE_FLOAT:
  22516. data = key.values[0];
  22517. break;
  22518. case Animation.ANIMATIONTYPE_QUATERNION:
  22519. data = BABYLON.Quaternion.FromArray(key.values);
  22520. break;
  22521. case Animation.ANIMATIONTYPE_MATRIX:
  22522. data = BABYLON.Matrix.FromArray(key.values);
  22523. break;
  22524. case Animation.ANIMATIONTYPE_COLOR3:
  22525. data = BABYLON.Color3.FromArray(key.values);
  22526. break;
  22527. case Animation.ANIMATIONTYPE_VECTOR3:
  22528. default:
  22529. data = BABYLON.Vector3.FromArray(key.values);
  22530. break;
  22531. }
  22532. keys.push({
  22533. frame: key.frame,
  22534. value: data
  22535. });
  22536. }
  22537. animation.setKeys(keys);
  22538. if (parsedAnimation.ranges) {
  22539. for (var index = 0; index < parsedAnimation.ranges.length; index++) {
  22540. data = parsedAnimation.ranges[index];
  22541. animation.createRange(data.name, data.from, data.to);
  22542. }
  22543. }
  22544. return animation;
  22545. };
  22546. Animation.AppendSerializedAnimations = function (source, destination) {
  22547. if (source.animations) {
  22548. destination.animations = [];
  22549. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  22550. var animation = source.animations[animationIndex];
  22551. destination.animations.push(animation.serialize());
  22552. }
  22553. }
  22554. };
  22555. // Statics
  22556. Animation._ANIMATIONTYPE_FLOAT = 0;
  22557. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  22558. Animation._ANIMATIONTYPE_QUATERNION = 2;
  22559. Animation._ANIMATIONTYPE_MATRIX = 3;
  22560. Animation._ANIMATIONTYPE_COLOR3 = 4;
  22561. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  22562. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  22563. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  22564. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  22565. return Animation;
  22566. })();
  22567. BABYLON.Animation = Animation;
  22568. })(BABYLON || (BABYLON = {}));
  22569. var BABYLON;
  22570. (function (BABYLON) {
  22571. var Animatable = (function () {
  22572. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  22573. if (fromFrame === void 0) { fromFrame = 0; }
  22574. if (toFrame === void 0) { toFrame = 100; }
  22575. if (loopAnimation === void 0) { loopAnimation = false; }
  22576. if (speedRatio === void 0) { speedRatio = 1.0; }
  22577. this.target = target;
  22578. this.fromFrame = fromFrame;
  22579. this.toFrame = toFrame;
  22580. this.loopAnimation = loopAnimation;
  22581. this.speedRatio = speedRatio;
  22582. this.onAnimationEnd = onAnimationEnd;
  22583. this._animations = new Array();
  22584. this._paused = false;
  22585. this.animationStarted = false;
  22586. if (animations) {
  22587. this.appendAnimations(target, animations);
  22588. }
  22589. this._scene = scene;
  22590. scene._activeAnimatables.push(this);
  22591. }
  22592. // Methods
  22593. Animatable.prototype.getAnimations = function () {
  22594. return this._animations;
  22595. };
  22596. Animatable.prototype.appendAnimations = function (target, animations) {
  22597. for (var index = 0; index < animations.length; index++) {
  22598. var animation = animations[index];
  22599. animation._target = target;
  22600. this._animations.push(animation);
  22601. }
  22602. };
  22603. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  22604. var animations = this._animations;
  22605. for (var index = 0; index < animations.length; index++) {
  22606. if (animations[index].targetProperty === property) {
  22607. return animations[index];
  22608. }
  22609. }
  22610. return null;
  22611. };
  22612. Animatable.prototype.reset = function () {
  22613. var animations = this._animations;
  22614. for (var index = 0; index < animations.length; index++) {
  22615. animations[index].reset();
  22616. }
  22617. this._localDelayOffset = null;
  22618. this._pausedDelay = null;
  22619. };
  22620. Animatable.prototype.goToFrame = function (frame) {
  22621. var animations = this._animations;
  22622. for (var index = 0; index < animations.length; index++) {
  22623. animations[index].goToFrame(frame);
  22624. }
  22625. };
  22626. Animatable.prototype.pause = function () {
  22627. if (this._paused) {
  22628. return;
  22629. }
  22630. this._paused = true;
  22631. };
  22632. Animatable.prototype.restart = function () {
  22633. this._paused = false;
  22634. };
  22635. Animatable.prototype.stop = function () {
  22636. var index = this._scene._activeAnimatables.indexOf(this);
  22637. if (index > -1) {
  22638. this._scene._activeAnimatables.splice(index, 1);
  22639. }
  22640. if (this.onAnimationEnd) {
  22641. this.onAnimationEnd();
  22642. }
  22643. };
  22644. Animatable.prototype._animate = function (delay) {
  22645. if (this._paused) {
  22646. this.animationStarted = false;
  22647. if (!this._pausedDelay) {
  22648. this._pausedDelay = delay;
  22649. }
  22650. return true;
  22651. }
  22652. if (!this._localDelayOffset) {
  22653. this._localDelayOffset = delay;
  22654. }
  22655. else if (this._pausedDelay) {
  22656. this._localDelayOffset += delay - this._pausedDelay;
  22657. this._pausedDelay = null;
  22658. }
  22659. // Animating
  22660. var running = false;
  22661. var animations = this._animations;
  22662. var index;
  22663. for (index = 0; index < animations.length; index++) {
  22664. var animation = animations[index];
  22665. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  22666. running = running || isRunning;
  22667. }
  22668. this.animationStarted = running;
  22669. if (!running) {
  22670. // Remove from active animatables
  22671. index = this._scene._activeAnimatables.indexOf(this);
  22672. this._scene._activeAnimatables.splice(index, 1);
  22673. }
  22674. if (!running && this.onAnimationEnd) {
  22675. this.onAnimationEnd();
  22676. }
  22677. return running;
  22678. };
  22679. return Animatable;
  22680. })();
  22681. BABYLON.Animatable = Animatable;
  22682. })(BABYLON || (BABYLON = {}));
  22683. var BABYLON;
  22684. (function (BABYLON) {
  22685. var EasingFunction = (function () {
  22686. function EasingFunction() {
  22687. // Properties
  22688. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  22689. }
  22690. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  22691. get: function () {
  22692. return EasingFunction._EASINGMODE_EASEIN;
  22693. },
  22694. enumerable: true,
  22695. configurable: true
  22696. });
  22697. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  22698. get: function () {
  22699. return EasingFunction._EASINGMODE_EASEOUT;
  22700. },
  22701. enumerable: true,
  22702. configurable: true
  22703. });
  22704. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  22705. get: function () {
  22706. return EasingFunction._EASINGMODE_EASEINOUT;
  22707. },
  22708. enumerable: true,
  22709. configurable: true
  22710. });
  22711. EasingFunction.prototype.setEasingMode = function (easingMode) {
  22712. var n = Math.min(Math.max(easingMode, 0), 2);
  22713. this._easingMode = n;
  22714. };
  22715. EasingFunction.prototype.getEasingMode = function () {
  22716. return this._easingMode;
  22717. };
  22718. EasingFunction.prototype.easeInCore = function (gradient) {
  22719. throw new Error('You must implement this method');
  22720. };
  22721. EasingFunction.prototype.ease = function (gradient) {
  22722. switch (this._easingMode) {
  22723. case EasingFunction.EASINGMODE_EASEIN:
  22724. return this.easeInCore(gradient);
  22725. case EasingFunction.EASINGMODE_EASEOUT:
  22726. return (1 - this.easeInCore(1 - gradient));
  22727. }
  22728. if (gradient >= 0.5) {
  22729. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  22730. }
  22731. return (this.easeInCore(gradient * 2) * 0.5);
  22732. };
  22733. //Statics
  22734. EasingFunction._EASINGMODE_EASEIN = 0;
  22735. EasingFunction._EASINGMODE_EASEOUT = 1;
  22736. EasingFunction._EASINGMODE_EASEINOUT = 2;
  22737. return EasingFunction;
  22738. })();
  22739. BABYLON.EasingFunction = EasingFunction;
  22740. var CircleEase = (function (_super) {
  22741. __extends(CircleEase, _super);
  22742. function CircleEase() {
  22743. _super.apply(this, arguments);
  22744. }
  22745. CircleEase.prototype.easeInCore = function (gradient) {
  22746. gradient = Math.max(0, Math.min(1, gradient));
  22747. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  22748. };
  22749. return CircleEase;
  22750. })(EasingFunction);
  22751. BABYLON.CircleEase = CircleEase;
  22752. var BackEase = (function (_super) {
  22753. __extends(BackEase, _super);
  22754. function BackEase(amplitude) {
  22755. if (amplitude === void 0) { amplitude = 1; }
  22756. _super.call(this);
  22757. this.amplitude = amplitude;
  22758. }
  22759. BackEase.prototype.easeInCore = function (gradient) {
  22760. var num = Math.max(0, this.amplitude);
  22761. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  22762. };
  22763. return BackEase;
  22764. })(EasingFunction);
  22765. BABYLON.BackEase = BackEase;
  22766. var BounceEase = (function (_super) {
  22767. __extends(BounceEase, _super);
  22768. function BounceEase(bounces, bounciness) {
  22769. if (bounces === void 0) { bounces = 3; }
  22770. if (bounciness === void 0) { bounciness = 2; }
  22771. _super.call(this);
  22772. this.bounces = bounces;
  22773. this.bounciness = bounciness;
  22774. }
  22775. BounceEase.prototype.easeInCore = function (gradient) {
  22776. var y = Math.max(0.0, this.bounces);
  22777. var bounciness = this.bounciness;
  22778. if (bounciness <= 1.0) {
  22779. bounciness = 1.001;
  22780. }
  22781. var num9 = Math.pow(bounciness, y);
  22782. var num5 = 1.0 - bounciness;
  22783. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  22784. var num15 = gradient * num4;
  22785. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  22786. var num3 = Math.floor(num65);
  22787. var num13 = num3 + 1.0;
  22788. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  22789. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  22790. var num7 = (num8 + num12) * 0.5;
  22791. var num6 = gradient - num7;
  22792. var num2 = num7 - num8;
  22793. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  22794. };
  22795. return BounceEase;
  22796. })(EasingFunction);
  22797. BABYLON.BounceEase = BounceEase;
  22798. var CubicEase = (function (_super) {
  22799. __extends(CubicEase, _super);
  22800. function CubicEase() {
  22801. _super.apply(this, arguments);
  22802. }
  22803. CubicEase.prototype.easeInCore = function (gradient) {
  22804. return (gradient * gradient * gradient);
  22805. };
  22806. return CubicEase;
  22807. })(EasingFunction);
  22808. BABYLON.CubicEase = CubicEase;
  22809. var ElasticEase = (function (_super) {
  22810. __extends(ElasticEase, _super);
  22811. function ElasticEase(oscillations, springiness) {
  22812. if (oscillations === void 0) { oscillations = 3; }
  22813. if (springiness === void 0) { springiness = 3; }
  22814. _super.call(this);
  22815. this.oscillations = oscillations;
  22816. this.springiness = springiness;
  22817. }
  22818. ElasticEase.prototype.easeInCore = function (gradient) {
  22819. var num2;
  22820. var num3 = Math.max(0.0, this.oscillations);
  22821. var num = Math.max(0.0, this.springiness);
  22822. if (num == 0) {
  22823. num2 = gradient;
  22824. }
  22825. else {
  22826. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  22827. }
  22828. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  22829. };
  22830. return ElasticEase;
  22831. })(EasingFunction);
  22832. BABYLON.ElasticEase = ElasticEase;
  22833. var ExponentialEase = (function (_super) {
  22834. __extends(ExponentialEase, _super);
  22835. function ExponentialEase(exponent) {
  22836. if (exponent === void 0) { exponent = 2; }
  22837. _super.call(this);
  22838. this.exponent = exponent;
  22839. }
  22840. ExponentialEase.prototype.easeInCore = function (gradient) {
  22841. if (this.exponent <= 0) {
  22842. return gradient;
  22843. }
  22844. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  22845. };
  22846. return ExponentialEase;
  22847. })(EasingFunction);
  22848. BABYLON.ExponentialEase = ExponentialEase;
  22849. var PowerEase = (function (_super) {
  22850. __extends(PowerEase, _super);
  22851. function PowerEase(power) {
  22852. if (power === void 0) { power = 2; }
  22853. _super.call(this);
  22854. this.power = power;
  22855. }
  22856. PowerEase.prototype.easeInCore = function (gradient) {
  22857. var y = Math.max(0.0, this.power);
  22858. return Math.pow(gradient, y);
  22859. };
  22860. return PowerEase;
  22861. })(EasingFunction);
  22862. BABYLON.PowerEase = PowerEase;
  22863. var QuadraticEase = (function (_super) {
  22864. __extends(QuadraticEase, _super);
  22865. function QuadraticEase() {
  22866. _super.apply(this, arguments);
  22867. }
  22868. QuadraticEase.prototype.easeInCore = function (gradient) {
  22869. return (gradient * gradient);
  22870. };
  22871. return QuadraticEase;
  22872. })(EasingFunction);
  22873. BABYLON.QuadraticEase = QuadraticEase;
  22874. var QuarticEase = (function (_super) {
  22875. __extends(QuarticEase, _super);
  22876. function QuarticEase() {
  22877. _super.apply(this, arguments);
  22878. }
  22879. QuarticEase.prototype.easeInCore = function (gradient) {
  22880. return (gradient * gradient * gradient * gradient);
  22881. };
  22882. return QuarticEase;
  22883. })(EasingFunction);
  22884. BABYLON.QuarticEase = QuarticEase;
  22885. var QuinticEase = (function (_super) {
  22886. __extends(QuinticEase, _super);
  22887. function QuinticEase() {
  22888. _super.apply(this, arguments);
  22889. }
  22890. QuinticEase.prototype.easeInCore = function (gradient) {
  22891. return (gradient * gradient * gradient * gradient * gradient);
  22892. };
  22893. return QuinticEase;
  22894. })(EasingFunction);
  22895. BABYLON.QuinticEase = QuinticEase;
  22896. var SineEase = (function (_super) {
  22897. __extends(SineEase, _super);
  22898. function SineEase() {
  22899. _super.apply(this, arguments);
  22900. }
  22901. SineEase.prototype.easeInCore = function (gradient) {
  22902. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  22903. };
  22904. return SineEase;
  22905. })(EasingFunction);
  22906. BABYLON.SineEase = SineEase;
  22907. var BezierCurveEase = (function (_super) {
  22908. __extends(BezierCurveEase, _super);
  22909. function BezierCurveEase(x1, y1, x2, y2) {
  22910. if (x1 === void 0) { x1 = 0; }
  22911. if (y1 === void 0) { y1 = 0; }
  22912. if (x2 === void 0) { x2 = 1; }
  22913. if (y2 === void 0) { y2 = 1; }
  22914. _super.call(this);
  22915. this.x1 = x1;
  22916. this.y1 = y1;
  22917. this.x2 = x2;
  22918. this.y2 = y2;
  22919. }
  22920. BezierCurveEase.prototype.easeInCore = function (gradient) {
  22921. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  22922. };
  22923. return BezierCurveEase;
  22924. })(EasingFunction);
  22925. BABYLON.BezierCurveEase = BezierCurveEase;
  22926. })(BABYLON || (BABYLON = {}));
  22927. var BABYLON;
  22928. (function (BABYLON) {
  22929. var Bone = (function (_super) {
  22930. __extends(Bone, _super);
  22931. function Bone(name, skeleton, parentBone, matrix, restPose) {
  22932. _super.call(this, name, skeleton.getScene());
  22933. this.name = name;
  22934. this.children = new Array();
  22935. this.animations = new Array();
  22936. this._worldTransform = new BABYLON.Matrix();
  22937. this._absoluteTransform = new BABYLON.Matrix();
  22938. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  22939. this._skeleton = skeleton;
  22940. this._matrix = matrix;
  22941. this._baseMatrix = matrix;
  22942. this._restPose = restPose ? restPose : matrix.clone();
  22943. skeleton.bones.push(this);
  22944. if (parentBone) {
  22945. this._parent = parentBone;
  22946. parentBone.children.push(this);
  22947. }
  22948. else {
  22949. this._parent = null;
  22950. }
  22951. this._updateDifferenceMatrix();
  22952. }
  22953. // Members
  22954. Bone.prototype.getParent = function () {
  22955. return this._parent;
  22956. };
  22957. Bone.prototype.getLocalMatrix = function () {
  22958. return this._matrix;
  22959. };
  22960. Bone.prototype.getBaseMatrix = function () {
  22961. return this._baseMatrix;
  22962. };
  22963. Bone.prototype.getRestPose = function () {
  22964. return this._restPose;
  22965. };
  22966. Bone.prototype.returnToRest = function () {
  22967. this.updateMatrix(this._restPose.clone());
  22968. };
  22969. Bone.prototype.getWorldMatrix = function () {
  22970. return this._worldTransform;
  22971. };
  22972. Bone.prototype.getInvertedAbsoluteTransform = function () {
  22973. return this._invertedAbsoluteTransform;
  22974. };
  22975. Bone.prototype.getAbsoluteTransform = function () {
  22976. return this._absoluteTransform;
  22977. };
  22978. // Methods
  22979. Bone.prototype.updateMatrix = function (matrix) {
  22980. this._baseMatrix = matrix.clone();
  22981. this._matrix = matrix.clone();
  22982. this._skeleton._markAsDirty();
  22983. this._updateDifferenceMatrix();
  22984. };
  22985. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  22986. if (!rootMatrix) {
  22987. rootMatrix = this._baseMatrix;
  22988. }
  22989. if (this._parent) {
  22990. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  22991. }
  22992. else {
  22993. this._absoluteTransform.copyFrom(rootMatrix);
  22994. }
  22995. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  22996. for (var index = 0; index < this.children.length; index++) {
  22997. this.children[index]._updateDifferenceMatrix();
  22998. }
  22999. };
  23000. Bone.prototype.markAsDirty = function () {
  23001. this._currentRenderId++;
  23002. this._skeleton._markAsDirty();
  23003. };
  23004. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired) {
  23005. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  23006. // all animation may be coming from a library skeleton, so may need to create animation
  23007. if (this.animations.length === 0) {
  23008. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  23009. }
  23010. // get animation info / verify there is such a range from the source bone
  23011. var sourceRange = source.animations[0].getRange(rangeName);
  23012. if (!sourceRange) {
  23013. return false;
  23014. }
  23015. var from = sourceRange.from;
  23016. var to = sourceRange.to;
  23017. var sourceKeys = source.animations[0].getKeys();
  23018. // rescaling prep
  23019. var sourceBoneLength = source.length;
  23020. var scalingReqd = rescaleAsRequired && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  23021. var ratio = scalingReqd ? this.length / sourceBoneLength : null;
  23022. var destKeys = this.animations[0].getKeys();
  23023. // loop vars declaration / initialization
  23024. var orig;
  23025. var origScale = scalingReqd ? BABYLON.Vector3.Zero() : null;
  23026. var origRotation = scalingReqd ? new BABYLON.Quaternion() : null;
  23027. var origTranslation = scalingReqd ? BABYLON.Vector3.Zero() : null;
  23028. var mat;
  23029. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  23030. orig = sourceKeys[key];
  23031. if (orig.frame >= from && orig.frame <= to) {
  23032. if (scalingReqd) {
  23033. orig.value.decompose(origScale, origRotation, origTranslation);
  23034. origTranslation.scaleInPlace(ratio);
  23035. mat = BABYLON.Matrix.Compose(origScale, origRotation, origTranslation);
  23036. }
  23037. else {
  23038. mat = orig.value;
  23039. }
  23040. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  23041. }
  23042. }
  23043. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  23044. return true;
  23045. };
  23046. return Bone;
  23047. })(BABYLON.Node);
  23048. BABYLON.Bone = Bone;
  23049. })(BABYLON || (BABYLON = {}));
  23050. var BABYLON;
  23051. (function (BABYLON) {
  23052. var Skeleton = (function () {
  23053. function Skeleton(name, id, scene) {
  23054. this.name = name;
  23055. this.id = id;
  23056. this.bones = new Array();
  23057. this.needInitialSkinMatrix = false;
  23058. this._isDirty = true;
  23059. this._meshesWithPoseMatrix = new Array();
  23060. this._identity = BABYLON.Matrix.Identity();
  23061. this._ranges = {};
  23062. this.bones = [];
  23063. this._scene = scene;
  23064. scene.skeletons.push(this);
  23065. this.prepare();
  23066. //make sure it will recalculate the matrix next time prepare is called.
  23067. this._isDirty = true;
  23068. }
  23069. // Members
  23070. Skeleton.prototype.getTransformMatrices = function (mesh) {
  23071. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  23072. return mesh._bonesTransformMatrices;
  23073. }
  23074. return this._transformMatrices;
  23075. };
  23076. Skeleton.prototype.getScene = function () {
  23077. return this._scene;
  23078. };
  23079. // Methods
  23080. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  23081. // check name not already in use
  23082. if (!this._ranges[name]) {
  23083. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  23084. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  23085. if (this.bones[i].animations[0]) {
  23086. this.bones[i].animations[0].createRange(name, from, to);
  23087. }
  23088. }
  23089. }
  23090. };
  23091. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  23092. if (deleteFrames === void 0) { deleteFrames = true; }
  23093. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  23094. if (this.bones[i].animations[0]) {
  23095. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  23096. }
  23097. }
  23098. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  23099. };
  23100. Skeleton.prototype.getAnimationRange = function (name) {
  23101. return this._ranges[name];
  23102. };
  23103. /**
  23104. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  23105. */
  23106. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  23107. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  23108. if (this._ranges[name] || !source.getAnimationRange(name)) {
  23109. return false;
  23110. }
  23111. var ret = true;
  23112. var frameOffset = this._getHighestAnimationFrame() + 1;
  23113. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  23114. var boneDict = {};
  23115. var sourceBones = source.bones;
  23116. for (var i = 0, nBones = sourceBones.length; i < nBones; i++) {
  23117. boneDict[sourceBones[i].name] = sourceBones[i];
  23118. }
  23119. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  23120. var boneName = this.bones[i].name;
  23121. var sourceBone = boneDict[boneName];
  23122. if (sourceBone) {
  23123. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired);
  23124. }
  23125. else {
  23126. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  23127. ret = false;
  23128. }
  23129. }
  23130. // do not call createAnimationRange(), since it also is done to bones, which was already done
  23131. var range = source.getAnimationRange(name);
  23132. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  23133. return ret;
  23134. };
  23135. Skeleton.prototype.returnToRest = function () {
  23136. for (var index = 0; index < this.bones.length; index++) {
  23137. this.bones[index].returnToRest();
  23138. }
  23139. };
  23140. Skeleton.prototype._getHighestAnimationFrame = function () {
  23141. var ret = 0;
  23142. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  23143. if (this.bones[i].animations[0]) {
  23144. var highest = this.bones[i].animations[0].getHighestFrame();
  23145. if (ret < highest) {
  23146. ret = highest;
  23147. }
  23148. }
  23149. }
  23150. return ret;
  23151. };
  23152. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  23153. var range = this.getAnimationRange(name);
  23154. if (!range) {
  23155. return null;
  23156. }
  23157. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  23158. };
  23159. Skeleton.prototype._markAsDirty = function () {
  23160. this._isDirty = true;
  23161. };
  23162. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  23163. this._meshesWithPoseMatrix.push(mesh);
  23164. };
  23165. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  23166. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  23167. if (index > -1) {
  23168. this._meshesWithPoseMatrix.splice(index, 1);
  23169. }
  23170. };
  23171. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  23172. for (var index = 0; index < this.bones.length; index++) {
  23173. var bone = this.bones[index];
  23174. var parentBone = bone.getParent();
  23175. if (parentBone) {
  23176. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  23177. }
  23178. else {
  23179. if (initialSkinMatrix) {
  23180. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  23181. }
  23182. else {
  23183. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  23184. }
  23185. }
  23186. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  23187. }
  23188. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  23189. };
  23190. Skeleton.prototype.prepare = function () {
  23191. if (!this._isDirty) {
  23192. return;
  23193. }
  23194. if (this.needInitialSkinMatrix) {
  23195. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  23196. var mesh = this._meshesWithPoseMatrix[index];
  23197. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  23198. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  23199. }
  23200. var poseMatrix = mesh.getPoseMatrix();
  23201. // Prepare bones
  23202. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  23203. var bone = this.bones[boneIndex];
  23204. if (!bone.getParent()) {
  23205. var matrix = bone.getBaseMatrix();
  23206. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[0]);
  23207. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[0]);
  23208. }
  23209. }
  23210. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  23211. }
  23212. }
  23213. else {
  23214. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  23215. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  23216. }
  23217. this._computeTransformMatrices(this._transformMatrices, null);
  23218. }
  23219. this._isDirty = false;
  23220. this._scene._activeBones += this.bones.length;
  23221. };
  23222. Skeleton.prototype.getAnimatables = function () {
  23223. if (!this._animatables || this._animatables.length !== this.bones.length) {
  23224. this._animatables = [];
  23225. for (var index = 0; index < this.bones.length; index++) {
  23226. this._animatables.push(this.bones[index]);
  23227. }
  23228. }
  23229. return this._animatables;
  23230. };
  23231. Skeleton.prototype.clone = function (name, id) {
  23232. var result = new Skeleton(name, id || name, this._scene);
  23233. for (var index = 0; index < this.bones.length; index++) {
  23234. var source = this.bones[index];
  23235. var parentBone = null;
  23236. if (source.getParent()) {
  23237. var parentIndex = this.bones.indexOf(source.getParent());
  23238. parentBone = result.bones[parentIndex];
  23239. }
  23240. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  23241. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  23242. }
  23243. return result;
  23244. };
  23245. Skeleton.prototype.dispose = function () {
  23246. this._meshesWithPoseMatrix = [];
  23247. // Animations
  23248. this.getScene().stopAnimation(this);
  23249. // Remove from scene
  23250. this.getScene().removeSkeleton(this);
  23251. };
  23252. Skeleton.prototype.serialize = function () {
  23253. var serializationObject = {};
  23254. serializationObject.name = this.name;
  23255. serializationObject.id = this.id;
  23256. serializationObject.bones = [];
  23257. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  23258. for (var index = 0; index < this.bones.length; index++) {
  23259. var bone = this.bones[index];
  23260. var serializedBone = {
  23261. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  23262. name: bone.name,
  23263. matrix: bone.getLocalMatrix().toArray(),
  23264. rest: bone.getRestPose().toArray()
  23265. };
  23266. serializationObject.bones.push(serializedBone);
  23267. if (bone.length) {
  23268. serializedBone.length = bone.length;
  23269. }
  23270. if (bone.animations && bone.animations.length > 0) {
  23271. serializedBone.animation = bone.animations[0].serialize();
  23272. }
  23273. serializationObject.ranges = [];
  23274. for (var name in this._ranges) {
  23275. var range = {};
  23276. range.name = name;
  23277. range.from = this._ranges[name].from;
  23278. range.to = this._ranges[name].to;
  23279. serializationObject.ranges.push(range);
  23280. }
  23281. }
  23282. return serializationObject;
  23283. };
  23284. Skeleton.Parse = function (parsedSkeleton, scene) {
  23285. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  23286. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  23287. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  23288. var parsedBone = parsedSkeleton.bones[index];
  23289. var parentBone = null;
  23290. if (parsedBone.parentBoneIndex > -1) {
  23291. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  23292. }
  23293. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  23294. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  23295. if (parsedBone.length) {
  23296. bone.length = parsedBone.length;
  23297. }
  23298. if (parsedBone.animation) {
  23299. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  23300. }
  23301. }
  23302. // placed after bones, so createAnimationRange can cascade down
  23303. if (parsedSkeleton.ranges) {
  23304. for (var index = 0; index < parsedSkeleton.ranges.length; index++) {
  23305. var data = parsedSkeleton.ranges[index];
  23306. skeleton.createAnimationRange(data.name, data.from, data.to);
  23307. }
  23308. }
  23309. return skeleton;
  23310. };
  23311. return Skeleton;
  23312. })();
  23313. BABYLON.Skeleton = Skeleton;
  23314. })(BABYLON || (BABYLON = {}));
  23315. var BABYLON;
  23316. (function (BABYLON) {
  23317. var PostProcess = (function () {
  23318. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines, textureType) {
  23319. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  23320. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  23321. this.name = name;
  23322. this.width = -1;
  23323. this.height = -1;
  23324. this._reusable = false;
  23325. this._textures = new BABYLON.SmartArray(2);
  23326. this._currentRenderTextureInd = 0;
  23327. if (camera != null) {
  23328. this._camera = camera;
  23329. this._scene = camera.getScene();
  23330. camera.attachPostProcess(this);
  23331. this._engine = this._scene.getEngine();
  23332. }
  23333. else {
  23334. this._engine = engine;
  23335. }
  23336. this._renderRatio = ratio;
  23337. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  23338. this._reusable = reusable || false;
  23339. this._textureType = textureType;
  23340. this._samplers = samplers || [];
  23341. this._samplers.push("textureSampler");
  23342. this._fragmentUrl = fragmentUrl;
  23343. this._parameters = parameters || [];
  23344. this.updateEffect(defines);
  23345. }
  23346. PostProcess.prototype.updateEffect = function (defines) {
  23347. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  23348. };
  23349. PostProcess.prototype.isReusable = function () {
  23350. return this._reusable;
  23351. };
  23352. PostProcess.prototype.activate = function (camera, sourceTexture) {
  23353. camera = camera || this._camera;
  23354. var scene = camera.getScene();
  23355. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  23356. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  23357. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  23358. desiredWidth = this._renderRatio.width || BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  23359. desiredHeight = this._renderRatio.height || BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  23360. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  23361. if (this._textures.length > 0) {
  23362. for (var i = 0; i < this._textures.length; i++) {
  23363. this._engine._releaseTexture(this._textures.data[i]);
  23364. }
  23365. this._textures.reset();
  23366. }
  23367. this.width = desiredWidth;
  23368. this.height = desiredHeight;
  23369. 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 }));
  23370. if (this._reusable) {
  23371. 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 }));
  23372. }
  23373. if (this.onSizeChanged) {
  23374. this.onSizeChanged();
  23375. }
  23376. }
  23377. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  23378. if (this.onActivate) {
  23379. this.onActivate(camera);
  23380. }
  23381. // Clear
  23382. if (this.clearColor) {
  23383. this._engine.clear(this.clearColor, true, true);
  23384. }
  23385. else {
  23386. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  23387. }
  23388. if (this._reusable) {
  23389. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  23390. }
  23391. };
  23392. Object.defineProperty(PostProcess.prototype, "isSupported", {
  23393. get: function () {
  23394. return this._effect.isSupported;
  23395. },
  23396. enumerable: true,
  23397. configurable: true
  23398. });
  23399. PostProcess.prototype.apply = function () {
  23400. // Check
  23401. if (!this._effect.isReady())
  23402. return null;
  23403. // States
  23404. this._engine.enableEffect(this._effect);
  23405. this._engine.setState(false);
  23406. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23407. this._engine.setDepthBuffer(false);
  23408. this._engine.setDepthWrite(false);
  23409. // Texture
  23410. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  23411. // Parameters
  23412. if (this.onApply) {
  23413. this.onApply(this._effect);
  23414. }
  23415. return this._effect;
  23416. };
  23417. PostProcess.prototype.dispose = function (camera) {
  23418. camera = camera || this._camera;
  23419. if (this._textures.length > 0) {
  23420. for (var i = 0; i < this._textures.length; i++) {
  23421. this._engine._releaseTexture(this._textures.data[i]);
  23422. }
  23423. this._textures.reset();
  23424. }
  23425. if (!camera) {
  23426. return;
  23427. }
  23428. camera.detachPostProcess(this);
  23429. var index = camera._postProcesses.indexOf(this);
  23430. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  23431. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  23432. }
  23433. };
  23434. return PostProcess;
  23435. })();
  23436. BABYLON.PostProcess = PostProcess;
  23437. })(BABYLON || (BABYLON = {}));
  23438. var BABYLON;
  23439. (function (BABYLON) {
  23440. var PostProcessManager = (function () {
  23441. function PostProcessManager(scene) {
  23442. this._vertexDeclaration = [2];
  23443. this._vertexStrideSize = 2 * 4;
  23444. this._scene = scene;
  23445. }
  23446. PostProcessManager.prototype._prepareBuffers = function () {
  23447. if (this._vertexBuffer) {
  23448. return;
  23449. }
  23450. // VBO
  23451. var vertices = [];
  23452. vertices.push(1, 1);
  23453. vertices.push(-1, 1);
  23454. vertices.push(-1, -1);
  23455. vertices.push(1, -1);
  23456. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  23457. // Indices
  23458. var indices = [];
  23459. indices.push(0);
  23460. indices.push(1);
  23461. indices.push(2);
  23462. indices.push(0);
  23463. indices.push(2);
  23464. indices.push(3);
  23465. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  23466. };
  23467. // Methods
  23468. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  23469. var postProcesses = this._scene.activeCamera._postProcesses;
  23470. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  23471. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  23472. return false;
  23473. }
  23474. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  23475. return true;
  23476. };
  23477. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  23478. var engine = this._scene.getEngine();
  23479. for (var index = 0; index < postProcesses.length; index++) {
  23480. if (index < postProcesses.length - 1) {
  23481. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  23482. }
  23483. else {
  23484. if (targetTexture) {
  23485. engine.bindFramebuffer(targetTexture);
  23486. }
  23487. else {
  23488. engine.restoreDefaultFramebuffer();
  23489. }
  23490. }
  23491. var pp = postProcesses[index];
  23492. var effect = pp.apply();
  23493. if (effect) {
  23494. if (pp.onBeforeRender) {
  23495. pp.onBeforeRender(effect);
  23496. }
  23497. // VBOs
  23498. this._prepareBuffers();
  23499. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  23500. // Draw order
  23501. engine.draw(true, 0, 6);
  23502. if (pp.onAfterRender) {
  23503. pp.onAfterRender(effect);
  23504. }
  23505. }
  23506. }
  23507. // Restore depth buffer
  23508. engine.setDepthBuffer(true);
  23509. engine.setDepthWrite(true);
  23510. };
  23511. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  23512. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  23513. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  23514. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  23515. return;
  23516. }
  23517. var engine = this._scene.getEngine();
  23518. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  23519. if (index < postProcessesTakenIndices.length - 1) {
  23520. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera, targetTexture);
  23521. }
  23522. else {
  23523. if (targetTexture) {
  23524. engine.bindFramebuffer(targetTexture, faceIndex);
  23525. }
  23526. else {
  23527. engine.restoreDefaultFramebuffer();
  23528. }
  23529. }
  23530. if (doNotPresent) {
  23531. break;
  23532. }
  23533. var pp = postProcesses[postProcessesTakenIndices[index]];
  23534. var effect = pp.apply();
  23535. if (effect) {
  23536. if (pp.onBeforeRender) {
  23537. pp.onBeforeRender(effect);
  23538. }
  23539. // VBOs
  23540. this._prepareBuffers();
  23541. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  23542. // Draw order
  23543. engine.draw(true, 0, 6);
  23544. if (pp.onAfterRender) {
  23545. pp.onAfterRender(effect);
  23546. }
  23547. }
  23548. }
  23549. // Restore depth buffer
  23550. engine.setDepthBuffer(true);
  23551. engine.setDepthWrite(true);
  23552. };
  23553. PostProcessManager.prototype.dispose = function () {
  23554. if (this._vertexBuffer) {
  23555. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  23556. this._vertexBuffer = null;
  23557. }
  23558. if (this._indexBuffer) {
  23559. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  23560. this._indexBuffer = null;
  23561. }
  23562. };
  23563. return PostProcessManager;
  23564. })();
  23565. BABYLON.PostProcessManager = PostProcessManager;
  23566. })(BABYLON || (BABYLON = {}));
  23567. var BABYLON;
  23568. (function (BABYLON) {
  23569. var PassPostProcess = (function (_super) {
  23570. __extends(PassPostProcess, _super);
  23571. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  23572. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  23573. }
  23574. return PassPostProcess;
  23575. })(BABYLON.PostProcess);
  23576. BABYLON.PassPostProcess = PassPostProcess;
  23577. })(BABYLON || (BABYLON = {}));
  23578. var BABYLON;
  23579. (function (BABYLON) {
  23580. var PhysicsEngine = (function () {
  23581. function PhysicsEngine(plugin) {
  23582. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  23583. }
  23584. PhysicsEngine.prototype._initialize = function (gravity) {
  23585. this._currentPlugin.initialize();
  23586. this._setGravity(gravity);
  23587. };
  23588. PhysicsEngine.prototype._runOneStep = function (delta) {
  23589. if (delta > 0.1) {
  23590. delta = 0.1;
  23591. }
  23592. else if (delta <= 0) {
  23593. delta = 1.0 / 60.0;
  23594. }
  23595. this._currentPlugin.runOneStep(delta);
  23596. };
  23597. PhysicsEngine.prototype._setGravity = function (gravity) {
  23598. this.gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  23599. this._currentPlugin.setGravity(this.gravity);
  23600. };
  23601. PhysicsEngine.prototype._getGravity = function () {
  23602. return this._currentPlugin.getGravity();
  23603. };
  23604. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  23605. return this._currentPlugin.registerMesh(mesh, impostor, options);
  23606. };
  23607. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  23608. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  23609. };
  23610. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  23611. this._currentPlugin.unregisterMesh(mesh);
  23612. };
  23613. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  23614. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  23615. };
  23616. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  23617. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  23618. };
  23619. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  23620. this._currentPlugin.updateBodyPosition(mesh);
  23621. };
  23622. PhysicsEngine.prototype.dispose = function () {
  23623. this._currentPlugin.dispose();
  23624. };
  23625. PhysicsEngine.prototype.isSupported = function () {
  23626. return this._currentPlugin.isSupported();
  23627. };
  23628. PhysicsEngine.prototype.getPhysicsBodyOfMesh = function (mesh) {
  23629. return this._currentPlugin.getPhysicsBodyOfMesh(mesh);
  23630. };
  23631. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  23632. return this._currentPlugin.name;
  23633. };
  23634. PhysicsEngine.prototype.getWorldObject = function () {
  23635. return this._currentPlugin.getWorldObject();
  23636. };
  23637. // Statics
  23638. PhysicsEngine.NoImpostor = 0;
  23639. PhysicsEngine.SphereImpostor = 1;
  23640. PhysicsEngine.BoxImpostor = 2;
  23641. PhysicsEngine.PlaneImpostor = 3;
  23642. PhysicsEngine.MeshImpostor = 4;
  23643. PhysicsEngine.CapsuleImpostor = 5;
  23644. PhysicsEngine.ConeImpostor = 6;
  23645. PhysicsEngine.CylinderImpostor = 7;
  23646. PhysicsEngine.ConvexHullImpostor = 8;
  23647. PhysicsEngine.HeightmapImpostor = 9;
  23648. PhysicsEngine.Epsilon = 0.001;
  23649. return PhysicsEngine;
  23650. })();
  23651. BABYLON.PhysicsEngine = PhysicsEngine;
  23652. })(BABYLON || (BABYLON = {}));
  23653. var BABYLON;
  23654. (function (BABYLON) {
  23655. var VertexData = (function () {
  23656. function VertexData() {
  23657. }
  23658. VertexData.prototype.set = function (data, kind) {
  23659. switch (kind) {
  23660. case BABYLON.VertexBuffer.PositionKind:
  23661. this.positions = data;
  23662. break;
  23663. case BABYLON.VertexBuffer.NormalKind:
  23664. this.normals = data;
  23665. break;
  23666. case BABYLON.VertexBuffer.UVKind:
  23667. this.uvs = data;
  23668. break;
  23669. case BABYLON.VertexBuffer.UV2Kind:
  23670. this.uvs2 = data;
  23671. break;
  23672. case BABYLON.VertexBuffer.UV3Kind:
  23673. this.uvs3 = data;
  23674. break;
  23675. case BABYLON.VertexBuffer.UV4Kind:
  23676. this.uvs4 = data;
  23677. break;
  23678. case BABYLON.VertexBuffer.UV5Kind:
  23679. this.uvs5 = data;
  23680. break;
  23681. case BABYLON.VertexBuffer.UV6Kind:
  23682. this.uvs6 = data;
  23683. break;
  23684. case BABYLON.VertexBuffer.ColorKind:
  23685. this.colors = data;
  23686. break;
  23687. case BABYLON.VertexBuffer.MatricesIndicesKind:
  23688. this.matricesIndices = data;
  23689. break;
  23690. case BABYLON.VertexBuffer.MatricesWeightsKind:
  23691. this.matricesWeights = data;
  23692. break;
  23693. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  23694. this.matricesIndicesExtra = data;
  23695. break;
  23696. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  23697. this.matricesWeightsExtra = data;
  23698. break;
  23699. }
  23700. };
  23701. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  23702. this._applyTo(mesh, updatable);
  23703. };
  23704. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  23705. this._applyTo(geometry, updatable);
  23706. };
  23707. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  23708. this._update(mesh);
  23709. };
  23710. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  23711. this._update(geometry);
  23712. };
  23713. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  23714. if (this.positions) {
  23715. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  23716. }
  23717. if (this.normals) {
  23718. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  23719. }
  23720. if (this.uvs) {
  23721. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  23722. }
  23723. if (this.uvs2) {
  23724. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  23725. }
  23726. if (this.uvs3) {
  23727. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  23728. }
  23729. if (this.uvs4) {
  23730. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  23731. }
  23732. if (this.uvs5) {
  23733. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  23734. }
  23735. if (this.uvs6) {
  23736. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  23737. }
  23738. if (this.colors) {
  23739. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  23740. }
  23741. if (this.matricesIndices) {
  23742. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  23743. }
  23744. if (this.matricesWeights) {
  23745. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  23746. }
  23747. if (this.matricesIndicesExtra) {
  23748. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  23749. }
  23750. if (this.matricesWeightsExtra) {
  23751. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  23752. }
  23753. if (this.indices) {
  23754. meshOrGeometry.setIndices(this.indices);
  23755. }
  23756. };
  23757. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  23758. if (this.positions) {
  23759. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  23760. }
  23761. if (this.normals) {
  23762. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  23763. }
  23764. if (this.uvs) {
  23765. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  23766. }
  23767. if (this.uvs2) {
  23768. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  23769. }
  23770. if (this.uvs3) {
  23771. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  23772. }
  23773. if (this.uvs4) {
  23774. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  23775. }
  23776. if (this.uvs5) {
  23777. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  23778. }
  23779. if (this.uvs6) {
  23780. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  23781. }
  23782. if (this.colors) {
  23783. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  23784. }
  23785. if (this.matricesIndices) {
  23786. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  23787. }
  23788. if (this.matricesWeights) {
  23789. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  23790. }
  23791. if (this.matricesIndicesExtra) {
  23792. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  23793. }
  23794. if (this.matricesWeightsExtra) {
  23795. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  23796. }
  23797. if (this.indices) {
  23798. meshOrGeometry.setIndices(this.indices);
  23799. }
  23800. };
  23801. VertexData.prototype.transform = function (matrix) {
  23802. var transformed = BABYLON.Vector3.Zero();
  23803. var index;
  23804. if (this.positions) {
  23805. var position = BABYLON.Vector3.Zero();
  23806. for (index = 0; index < this.positions.length; index += 3) {
  23807. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  23808. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  23809. this.positions[index] = transformed.x;
  23810. this.positions[index + 1] = transformed.y;
  23811. this.positions[index + 2] = transformed.z;
  23812. }
  23813. }
  23814. if (this.normals) {
  23815. var normal = BABYLON.Vector3.Zero();
  23816. for (index = 0; index < this.normals.length; index += 3) {
  23817. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  23818. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  23819. this.normals[index] = transformed.x;
  23820. this.normals[index + 1] = transformed.y;
  23821. this.normals[index + 2] = transformed.z;
  23822. }
  23823. }
  23824. };
  23825. VertexData.prototype.merge = function (other) {
  23826. if (other.indices) {
  23827. if (!this.indices) {
  23828. this.indices = [];
  23829. }
  23830. var offset = this.positions ? this.positions.length / 3 : 0;
  23831. for (var index = 0; index < other.indices.length; index++) {
  23832. //TODO check type - if Int32Array!
  23833. this.indices.push(other.indices[index] + offset);
  23834. }
  23835. }
  23836. this.positions = this._mergeElement(this.positions, other.positions);
  23837. this.normals = this._mergeElement(this.normals, other.normals);
  23838. this.uvs = this._mergeElement(this.uvs, other.uvs);
  23839. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  23840. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  23841. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  23842. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  23843. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  23844. this.colors = this._mergeElement(this.colors, other.colors);
  23845. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  23846. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  23847. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  23848. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  23849. };
  23850. VertexData.prototype._mergeElement = function (source, other) {
  23851. if (!other)
  23852. return source;
  23853. if (!source)
  23854. return other;
  23855. var len = other.length + source.length;
  23856. var isSrcTypedArray = source instanceof Float32Array;
  23857. var isOthTypedArray = other instanceof Float32Array;
  23858. // use non-loop method when the source is Float32Array
  23859. if (isSrcTypedArray) {
  23860. var ret32 = new Float32Array(len);
  23861. ret32.set(source);
  23862. ret32.set(other, source.length);
  23863. return ret32;
  23864. }
  23865. else if (!isOthTypedArray) {
  23866. return source.concat(other);
  23867. }
  23868. else {
  23869. var ret = source.slice(0); // copy source to a separate array
  23870. for (var i = 0, len = other.length; i < len; i++) {
  23871. ret.push(other[i]);
  23872. }
  23873. return ret;
  23874. }
  23875. };
  23876. VertexData.prototype.serialize = function () {
  23877. var serializationObject = this.serialize();
  23878. if (this.positions) {
  23879. serializationObject.positions = this.positions;
  23880. }
  23881. if (this.normals) {
  23882. serializationObject.normals = this.normals;
  23883. }
  23884. if (this.uvs) {
  23885. serializationObject.uvs = this.uvs;
  23886. }
  23887. if (this.uvs2) {
  23888. serializationObject.uvs2 = this.uvs2;
  23889. }
  23890. if (this.uvs3) {
  23891. serializationObject.uvs3 = this.uvs3;
  23892. }
  23893. if (this.uvs4) {
  23894. serializationObject.uvs4 = this.uvs4;
  23895. }
  23896. if (this.uvs5) {
  23897. serializationObject.uvs5 = this.uvs5;
  23898. }
  23899. if (this.uvs6) {
  23900. serializationObject.uvs6 = this.uvs6;
  23901. }
  23902. if (this.colors) {
  23903. serializationObject.colors = this.colors;
  23904. }
  23905. if (this.matricesIndices) {
  23906. serializationObject.matricesIndices = this.matricesIndices;
  23907. serializationObject.matricesIndices._isExpanded = true;
  23908. }
  23909. if (this.matricesWeights) {
  23910. serializationObject.matricesWeights = this.matricesWeights;
  23911. }
  23912. if (this.matricesIndicesExtra) {
  23913. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  23914. serializationObject.matricesIndicesExtra._isExpanded = true;
  23915. }
  23916. if (this.matricesWeightsExtra) {
  23917. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  23918. }
  23919. serializationObject.indices = this.indices;
  23920. return serializationObject;
  23921. };
  23922. // Statics
  23923. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  23924. return VertexData._ExtractFrom(mesh, copyWhenShared);
  23925. };
  23926. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  23927. return VertexData._ExtractFrom(geometry, copyWhenShared);
  23928. };
  23929. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  23930. var result = new VertexData();
  23931. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  23932. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  23933. }
  23934. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  23935. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  23936. }
  23937. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  23938. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  23939. }
  23940. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  23941. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  23942. }
  23943. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  23944. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  23945. }
  23946. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  23947. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  23948. }
  23949. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  23950. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  23951. }
  23952. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  23953. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  23954. }
  23955. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  23956. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  23957. }
  23958. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  23959. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  23960. }
  23961. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  23962. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  23963. }
  23964. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  23965. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  23966. }
  23967. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  23968. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  23969. }
  23970. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  23971. return result;
  23972. };
  23973. VertexData.CreateRibbon = function (options) {
  23974. var pathArray = options.pathArray;
  23975. var closeArray = options.closeArray || false;
  23976. var closePath = options.closePath || false;
  23977. var defaultOffset = Math.floor(pathArray[0].length / 2);
  23978. var offset = options.offset || defaultOffset;
  23979. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  23980. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23981. var positions = [];
  23982. var indices = [];
  23983. var normals = [];
  23984. var uvs = [];
  23985. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  23986. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  23987. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  23988. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  23989. var minlg; // minimal length among all paths from pathArray
  23990. var lg = []; // array of path lengths : nb of vertex per path
  23991. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  23992. var p; // path iterator
  23993. var i; // point iterator
  23994. var j; // point iterator
  23995. // if single path in pathArray
  23996. if (pathArray.length < 2) {
  23997. var ar1 = [];
  23998. var ar2 = [];
  23999. for (i = 0; i < pathArray[0].length - offset; i++) {
  24000. ar1.push(pathArray[0][i]);
  24001. ar2.push(pathArray[0][i + offset]);
  24002. }
  24003. pathArray = [ar1, ar2];
  24004. }
  24005. // positions and horizontal distances (u)
  24006. var idc = 0;
  24007. var closePathCorr = (closePath) ? 1 : 0;
  24008. var path;
  24009. var l;
  24010. minlg = pathArray[0].length;
  24011. var vectlg;
  24012. var dist;
  24013. for (p = 0; p < pathArray.length; p++) {
  24014. uTotalDistance[p] = 0;
  24015. us[p] = [0];
  24016. path = pathArray[p];
  24017. l = path.length;
  24018. minlg = (minlg < l) ? minlg : l;
  24019. j = 0;
  24020. while (j < l) {
  24021. positions.push(path[j].x, path[j].y, path[j].z);
  24022. if (j > 0) {
  24023. vectlg = path[j].subtract(path[j - 1]).length();
  24024. dist = vectlg + uTotalDistance[p];
  24025. us[p].push(dist);
  24026. uTotalDistance[p] = dist;
  24027. }
  24028. j++;
  24029. }
  24030. if (closePath) {
  24031. j--;
  24032. positions.push(path[0].x, path[0].y, path[0].z);
  24033. vectlg = path[j].subtract(path[0]).length();
  24034. dist = vectlg + uTotalDistance[p];
  24035. us[p].push(dist);
  24036. uTotalDistance[p] = dist;
  24037. }
  24038. lg[p] = l + closePathCorr;
  24039. idx[p] = idc;
  24040. idc += (l + closePathCorr);
  24041. }
  24042. // vertical distances (v)
  24043. var path1;
  24044. var path2;
  24045. var vertex1;
  24046. var vertex2;
  24047. for (i = 0; i < minlg + closePathCorr; i++) {
  24048. vTotalDistance[i] = 0;
  24049. vs[i] = [0];
  24050. for (p = 0; p < pathArray.length - 1; p++) {
  24051. path1 = pathArray[p];
  24052. path2 = pathArray[p + 1];
  24053. if (i === minlg) {
  24054. vertex1 = path1[0];
  24055. vertex2 = path2[0];
  24056. }
  24057. else {
  24058. vertex1 = path1[i];
  24059. vertex2 = path2[i];
  24060. }
  24061. vectlg = vertex2.subtract(vertex1).length();
  24062. dist = vectlg + vTotalDistance[i];
  24063. vs[i].push(dist);
  24064. vTotalDistance[i] = dist;
  24065. }
  24066. if (closeArray) {
  24067. path1 = pathArray[p];
  24068. path2 = pathArray[0];
  24069. if (i === minlg) {
  24070. vertex2 = path2[0];
  24071. }
  24072. vectlg = vertex2.subtract(vertex1).length();
  24073. dist = vectlg + vTotalDistance[i];
  24074. vTotalDistance[i] = dist;
  24075. }
  24076. }
  24077. // uvs
  24078. var u;
  24079. var v;
  24080. for (p = 0; p < pathArray.length; p++) {
  24081. for (i = 0; i < minlg + closePathCorr; i++) {
  24082. u = us[p][i] / uTotalDistance[p];
  24083. v = vs[i][p] / vTotalDistance[i];
  24084. uvs.push(u, v);
  24085. }
  24086. }
  24087. // indices
  24088. p = 0; // path index
  24089. var pi = 0; // positions array index
  24090. var l1 = lg[p] - 1; // path1 length
  24091. var l2 = lg[p + 1] - 1; // path2 length
  24092. var min = (l1 < l2) ? l1 : l2; // current path stop index
  24093. var shft = idx[1] - idx[0]; // shift
  24094. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  24095. while (pi <= min && p < path1nb) {
  24096. // 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
  24097. indices.push(pi, pi + shft, pi + 1);
  24098. indices.push(pi + shft + 1, pi + 1, pi + shft);
  24099. pi += 1;
  24100. if (pi === min) {
  24101. p++;
  24102. if (p === lg.length - 1) {
  24103. shft = idx[0] - idx[p];
  24104. l1 = lg[p] - 1;
  24105. l2 = lg[0] - 1;
  24106. }
  24107. else {
  24108. shft = idx[p + 1] - idx[p];
  24109. l1 = lg[p] - 1;
  24110. l2 = lg[p + 1] - 1;
  24111. }
  24112. pi = idx[p];
  24113. min = (l1 < l2) ? l1 + pi : l2 + pi;
  24114. }
  24115. }
  24116. // normals
  24117. VertexData.ComputeNormals(positions, indices, normals);
  24118. if (closePath) {
  24119. var indexFirst = 0;
  24120. var indexLast = 0;
  24121. for (p = 0; p < pathArray.length; p++) {
  24122. indexFirst = idx[p] * 3;
  24123. if (p + 1 < pathArray.length) {
  24124. indexLast = (idx[p + 1] - 1) * 3;
  24125. }
  24126. else {
  24127. indexLast = normals.length - 3;
  24128. }
  24129. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  24130. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  24131. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  24132. normals[indexLast] = normals[indexFirst];
  24133. normals[indexLast + 1] = normals[indexFirst + 1];
  24134. normals[indexLast + 2] = normals[indexFirst + 2];
  24135. }
  24136. }
  24137. // sides
  24138. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24139. // Result
  24140. var vertexData = new VertexData();
  24141. vertexData.indices = indices;
  24142. vertexData.positions = positions;
  24143. vertexData.normals = normals;
  24144. vertexData.uvs = uvs;
  24145. if (closePath) {
  24146. vertexData._idx = idx;
  24147. }
  24148. return vertexData;
  24149. };
  24150. VertexData.CreateBox = function (options) {
  24151. var normalsSource = [
  24152. new BABYLON.Vector3(0, 0, 1),
  24153. new BABYLON.Vector3(0, 0, -1),
  24154. new BABYLON.Vector3(1, 0, 0),
  24155. new BABYLON.Vector3(-1, 0, 0),
  24156. new BABYLON.Vector3(0, 1, 0),
  24157. new BABYLON.Vector3(0, -1, 0)
  24158. ];
  24159. var indices = [];
  24160. var positions = [];
  24161. var normals = [];
  24162. var uvs = [];
  24163. var width = options.width || options.size || 1;
  24164. var height = options.height || options.size || 1;
  24165. var depth = options.depth || options.size || 1;
  24166. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24167. var faceUV = options.faceUV || new Array(6);
  24168. var faceColors = options.faceColors;
  24169. var colors = [];
  24170. // default face colors and UV if undefined
  24171. for (var f = 0; f < 6; f++) {
  24172. if (faceUV[f] === undefined) {
  24173. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  24174. }
  24175. if (faceColors && faceColors[f] === undefined) {
  24176. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  24177. }
  24178. }
  24179. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  24180. // Create each face in turn.
  24181. for (var index = 0; index < normalsSource.length; index++) {
  24182. var normal = normalsSource[index];
  24183. // Get two vectors perpendicular to the face normal and to each other.
  24184. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  24185. var side2 = BABYLON.Vector3.Cross(normal, side1);
  24186. // Six indices (two triangles) per face.
  24187. var verticesLength = positions.length / 3;
  24188. indices.push(verticesLength);
  24189. indices.push(verticesLength + 1);
  24190. indices.push(verticesLength + 2);
  24191. indices.push(verticesLength);
  24192. indices.push(verticesLength + 2);
  24193. indices.push(verticesLength + 3);
  24194. // Four vertices per face.
  24195. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  24196. positions.push(vertex.x, vertex.y, vertex.z);
  24197. normals.push(normal.x, normal.y, normal.z);
  24198. uvs.push(faceUV[index].z, faceUV[index].w);
  24199. if (faceColors) {
  24200. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  24201. }
  24202. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  24203. positions.push(vertex.x, vertex.y, vertex.z);
  24204. normals.push(normal.x, normal.y, normal.z);
  24205. uvs.push(faceUV[index].x, faceUV[index].w);
  24206. if (faceColors) {
  24207. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  24208. }
  24209. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  24210. positions.push(vertex.x, vertex.y, vertex.z);
  24211. normals.push(normal.x, normal.y, normal.z);
  24212. uvs.push(faceUV[index].x, faceUV[index].y);
  24213. if (faceColors) {
  24214. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  24215. }
  24216. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  24217. positions.push(vertex.x, vertex.y, vertex.z);
  24218. normals.push(normal.x, normal.y, normal.z);
  24219. uvs.push(faceUV[index].z, faceUV[index].y);
  24220. if (faceColors) {
  24221. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  24222. }
  24223. }
  24224. // sides
  24225. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24226. // Result
  24227. var vertexData = new VertexData();
  24228. vertexData.indices = indices;
  24229. vertexData.positions = positions;
  24230. vertexData.normals = normals;
  24231. vertexData.uvs = uvs;
  24232. if (faceColors) {
  24233. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  24234. vertexData.colors = totalColors;
  24235. }
  24236. return vertexData;
  24237. };
  24238. VertexData.CreateSphere = function (options) {
  24239. var segments = options.segments || 32;
  24240. var diameterX = options.diameterX || options.diameter || 1;
  24241. var diameterY = options.diameterY || options.diameter || 1;
  24242. var diameterZ = options.diameterZ || options.diameter || 1;
  24243. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  24244. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  24245. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24246. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  24247. var totalZRotationSteps = 2 + segments;
  24248. var totalYRotationSteps = 2 * totalZRotationSteps;
  24249. var indices = [];
  24250. var positions = [];
  24251. var normals = [];
  24252. var uvs = [];
  24253. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  24254. var normalizedZ = zRotationStep / totalZRotationSteps;
  24255. var angleZ = normalizedZ * Math.PI * slice;
  24256. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  24257. var normalizedY = yRotationStep / totalYRotationSteps;
  24258. var angleY = normalizedY * Math.PI * 2 * arc;
  24259. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  24260. var rotationY = BABYLON.Matrix.RotationY(angleY);
  24261. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  24262. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  24263. var vertex = complete.multiply(radius);
  24264. var normal = complete.divide(radius).normalize();
  24265. positions.push(vertex.x, vertex.y, vertex.z);
  24266. normals.push(normal.x, normal.y, normal.z);
  24267. uvs.push(normalizedY, normalizedZ);
  24268. }
  24269. if (zRotationStep > 0) {
  24270. var verticesCount = positions.length / 3;
  24271. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  24272. indices.push((firstIndex));
  24273. indices.push((firstIndex + 1));
  24274. indices.push(firstIndex + totalYRotationSteps + 1);
  24275. indices.push((firstIndex + totalYRotationSteps + 1));
  24276. indices.push((firstIndex + 1));
  24277. indices.push((firstIndex + totalYRotationSteps + 2));
  24278. }
  24279. }
  24280. }
  24281. // Sides
  24282. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24283. // Result
  24284. var vertexData = new VertexData();
  24285. vertexData.indices = indices;
  24286. vertexData.positions = positions;
  24287. vertexData.normals = normals;
  24288. vertexData.uvs = uvs;
  24289. return vertexData;
  24290. };
  24291. // Cylinder and cone
  24292. VertexData.CreateCylinder = function (options) {
  24293. var height = options.height || 2;
  24294. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  24295. var diameterBottom = options.diameterBottom || options.diameter || 1;
  24296. var tessellation = options.tessellation || 24;
  24297. var subdivisions = options.subdivisions || 1;
  24298. var hasRings = options.hasRings;
  24299. var enclose = options.enclose;
  24300. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  24301. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24302. var faceUV = options.faceUV || new Array(3);
  24303. var faceColors = options.faceColors;
  24304. // default face colors and UV if undefined
  24305. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  24306. var ringNb = (hasRings) ? subdivisions : 1;
  24307. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  24308. var f;
  24309. for (f = 0; f < surfaceNb; f++) {
  24310. if (faceColors && faceColors[f] === undefined) {
  24311. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  24312. }
  24313. }
  24314. for (f = 0; f < surfaceNb; f++) {
  24315. if (faceUV && faceUV[f] === undefined) {
  24316. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  24317. }
  24318. }
  24319. var indices = [];
  24320. var positions = [];
  24321. var normals = [];
  24322. var uvs = [];
  24323. var colors = [];
  24324. var angle_step = Math.PI * 2 * arc / tessellation;
  24325. var angle;
  24326. var h;
  24327. var radius;
  24328. var tan = (diameterBottom - diameterTop) / 2 / height;
  24329. var ringVertex = BABYLON.Vector3.Zero();
  24330. var ringNormal = BABYLON.Vector3.Zero();
  24331. var ringFirstVertex = BABYLON.Vector3.Zero();
  24332. var ringFirstNormal = BABYLON.Vector3.Zero();
  24333. var quadNormal = BABYLON.Vector3.Zero();
  24334. var Y = BABYLON.Axis.Y;
  24335. // positions, normals, uvs
  24336. var i;
  24337. var j;
  24338. var r;
  24339. var ringIdx = 1;
  24340. var s = 1; // surface index
  24341. var cs = 0;
  24342. var v = 0;
  24343. for (i = 0; i <= subdivisions; i++) {
  24344. h = i / subdivisions;
  24345. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  24346. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  24347. for (r = 0; r < ringIdx; r++) {
  24348. if (hasRings) {
  24349. s += r;
  24350. }
  24351. if (enclose) {
  24352. s += 2 * r;
  24353. }
  24354. for (j = 0; j <= tessellation; j++) {
  24355. angle = j * angle_step;
  24356. // position
  24357. ringVertex.x = Math.cos(-angle) * radius;
  24358. ringVertex.y = -height / 2 + h * height;
  24359. ringVertex.z = Math.sin(-angle) * radius;
  24360. // normal
  24361. if (diameterTop === 0 && i === subdivisions) {
  24362. // if no top cap, reuse former normals
  24363. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  24364. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  24365. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  24366. }
  24367. else {
  24368. ringNormal.x = ringVertex.x;
  24369. ringNormal.z = ringVertex.z;
  24370. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  24371. ringNormal.normalize();
  24372. }
  24373. // keep first ring vertex values for enclose
  24374. if (j === 0) {
  24375. ringFirstVertex.copyFrom(ringVertex);
  24376. ringFirstNormal.copyFrom(ringNormal);
  24377. }
  24378. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  24379. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  24380. if (hasRings) {
  24381. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  24382. }
  24383. else {
  24384. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  24385. }
  24386. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  24387. if (faceColors) {
  24388. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  24389. }
  24390. }
  24391. // if enclose, add four vertices and their dedicated normals
  24392. if (arc !== 1 && enclose) {
  24393. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  24394. positions.push(0, ringVertex.y, 0);
  24395. positions.push(0, ringVertex.y, 0);
  24396. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  24397. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  24398. quadNormal.normalize();
  24399. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  24400. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  24401. quadNormal.normalize();
  24402. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  24403. if (hasRings) {
  24404. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  24405. }
  24406. else {
  24407. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  24408. }
  24409. uvs.push(faceUV[s + 1].x, v);
  24410. uvs.push(faceUV[s + 1].z, v);
  24411. if (hasRings) {
  24412. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  24413. }
  24414. else {
  24415. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  24416. }
  24417. uvs.push(faceUV[s + 2].x, v);
  24418. uvs.push(faceUV[s + 2].z, v);
  24419. if (faceColors) {
  24420. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  24421. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  24422. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  24423. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  24424. }
  24425. }
  24426. if (cs !== s) {
  24427. cs = s;
  24428. }
  24429. }
  24430. }
  24431. // indices
  24432. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  24433. var s;
  24434. i = 0;
  24435. for (s = 0; s < subdivisions; s++) {
  24436. for (j = 0; j < tessellation; j++) {
  24437. var i0 = i * (e + 1) + j;
  24438. var i1 = (i + 1) * (e + 1) + j;
  24439. var i2 = i * (e + 1) + (j + 1);
  24440. var i3 = (i + 1) * (e + 1) + (j + 1);
  24441. indices.push(i0, i1, i2);
  24442. indices.push(i3, i2, i1);
  24443. }
  24444. if (arc !== 1 && enclose) {
  24445. indices.push(i0 + 2, i1 + 2, i2 + 2);
  24446. indices.push(i3 + 2, i2 + 2, i1 + 2);
  24447. indices.push(i0 + 4, i1 + 4, i2 + 4);
  24448. indices.push(i3 + 4, i2 + 4, i1 + 4);
  24449. }
  24450. i = (hasRings) ? (i + 2) : (i + 1);
  24451. }
  24452. // Caps
  24453. var createCylinderCap = function (isTop) {
  24454. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  24455. if (radius === 0) {
  24456. return;
  24457. }
  24458. // Cap positions, normals & uvs
  24459. var angle;
  24460. var circleVector;
  24461. var i;
  24462. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  24463. var c;
  24464. if (faceColors) {
  24465. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  24466. }
  24467. // cap center
  24468. var vbase = positions.length / 3;
  24469. var offset = isTop ? height / 2 : -height / 2;
  24470. var center = new BABYLON.Vector3(0, offset, 0);
  24471. positions.push(center.x, center.y, center.z);
  24472. normals.push(0, isTop ? 1 : -1, 0);
  24473. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  24474. if (faceColors) {
  24475. colors.push(c.r, c.g, c.b, c.a);
  24476. }
  24477. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  24478. for (i = 0; i <= tessellation; i++) {
  24479. angle = Math.PI * 2 * i * arc / tessellation;
  24480. var cos = Math.cos(-angle);
  24481. var sin = Math.sin(-angle);
  24482. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  24483. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  24484. positions.push(circleVector.x, circleVector.y, circleVector.z);
  24485. normals.push(0, isTop ? 1 : -1, 0);
  24486. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  24487. if (faceColors) {
  24488. colors.push(c.r, c.g, c.b, c.a);
  24489. }
  24490. }
  24491. // Cap indices
  24492. for (i = 0; i < tessellation; i++) {
  24493. if (!isTop) {
  24494. indices.push(vbase);
  24495. indices.push(vbase + (i + 1));
  24496. indices.push(vbase + (i + 2));
  24497. }
  24498. else {
  24499. indices.push(vbase);
  24500. indices.push(vbase + (i + 2));
  24501. indices.push(vbase + (i + 1));
  24502. }
  24503. }
  24504. };
  24505. // add caps to geometry
  24506. createCylinderCap(false);
  24507. createCylinderCap(true);
  24508. // Sides
  24509. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24510. var vertexData = new VertexData();
  24511. vertexData.indices = indices;
  24512. vertexData.positions = positions;
  24513. vertexData.normals = normals;
  24514. vertexData.uvs = uvs;
  24515. if (faceColors) {
  24516. vertexData.colors = colors;
  24517. }
  24518. return vertexData;
  24519. };
  24520. VertexData.CreateTorus = function (options) {
  24521. var indices = [];
  24522. var positions = [];
  24523. var normals = [];
  24524. var uvs = [];
  24525. var diameter = options.diameter || 1;
  24526. var thickness = options.thickness || 0.5;
  24527. var tessellation = options.tessellation || 16;
  24528. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24529. var stride = tessellation + 1;
  24530. for (var i = 0; i <= tessellation; i++) {
  24531. var u = i / tessellation;
  24532. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  24533. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  24534. for (var j = 0; j <= tessellation; j++) {
  24535. var v = 1 - j / tessellation;
  24536. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  24537. var dx = Math.cos(innerAngle);
  24538. var dy = Math.sin(innerAngle);
  24539. // Create a vertex.
  24540. var normal = new BABYLON.Vector3(dx, dy, 0);
  24541. var position = normal.scale(thickness / 2);
  24542. var textureCoordinate = new BABYLON.Vector2(u, v);
  24543. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  24544. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  24545. positions.push(position.x, position.y, position.z);
  24546. normals.push(normal.x, normal.y, normal.z);
  24547. uvs.push(textureCoordinate.x, textureCoordinate.y);
  24548. // And create indices for two triangles.
  24549. var nextI = (i + 1) % stride;
  24550. var nextJ = (j + 1) % stride;
  24551. indices.push(i * stride + j);
  24552. indices.push(i * stride + nextJ);
  24553. indices.push(nextI * stride + j);
  24554. indices.push(i * stride + nextJ);
  24555. indices.push(nextI * stride + nextJ);
  24556. indices.push(nextI * stride + j);
  24557. }
  24558. }
  24559. // Sides
  24560. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24561. // Result
  24562. var vertexData = new VertexData();
  24563. vertexData.indices = indices;
  24564. vertexData.positions = positions;
  24565. vertexData.normals = normals;
  24566. vertexData.uvs = uvs;
  24567. return vertexData;
  24568. };
  24569. VertexData.CreateLines = function (options) {
  24570. var indices = [];
  24571. var positions = [];
  24572. var points = options.points;
  24573. for (var index = 0; index < points.length; index++) {
  24574. positions.push(points[index].x, points[index].y, points[index].z);
  24575. if (index > 0) {
  24576. indices.push(index - 1);
  24577. indices.push(index);
  24578. }
  24579. }
  24580. // Result
  24581. var vertexData = new VertexData();
  24582. vertexData.indices = indices;
  24583. vertexData.positions = positions;
  24584. return vertexData;
  24585. };
  24586. VertexData.CreateDashedLines = function (options) {
  24587. var dashSize = options.dashSize || 3;
  24588. var gapSize = options.gapSize || 1;
  24589. var dashNb = options.dashNb || 200;
  24590. var points = options.points;
  24591. var positions = new Array();
  24592. var indices = new Array();
  24593. var curvect = BABYLON.Vector3.Zero();
  24594. var lg = 0;
  24595. var nb = 0;
  24596. var shft = 0;
  24597. var dashshft = 0;
  24598. var curshft = 0;
  24599. var idx = 0;
  24600. var i = 0;
  24601. for (i = 0; i < points.length - 1; i++) {
  24602. points[i + 1].subtractToRef(points[i], curvect);
  24603. lg += curvect.length();
  24604. }
  24605. shft = lg / dashNb;
  24606. dashshft = dashSize * shft / (dashSize + gapSize);
  24607. for (i = 0; i < points.length - 1; i++) {
  24608. points[i + 1].subtractToRef(points[i], curvect);
  24609. nb = Math.floor(curvect.length() / shft);
  24610. curvect.normalize();
  24611. for (var j = 0; j < nb; j++) {
  24612. curshft = shft * j;
  24613. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  24614. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  24615. indices.push(idx, idx + 1);
  24616. idx += 2;
  24617. }
  24618. }
  24619. // Result
  24620. var vertexData = new VertexData();
  24621. vertexData.positions = positions;
  24622. vertexData.indices = indices;
  24623. return vertexData;
  24624. };
  24625. VertexData.CreateGround = function (options) {
  24626. var indices = [];
  24627. var positions = [];
  24628. var normals = [];
  24629. var uvs = [];
  24630. var row, col;
  24631. var width = options.width || 1;
  24632. var height = options.height || 1;
  24633. var subdivisions = options.subdivisions || 1;
  24634. for (row = 0; row <= subdivisions; row++) {
  24635. for (col = 0; col <= subdivisions; col++) {
  24636. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  24637. var normal = new BABYLON.Vector3(0, 1.0, 0);
  24638. positions.push(position.x, position.y, position.z);
  24639. normals.push(normal.x, normal.y, normal.z);
  24640. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  24641. }
  24642. }
  24643. for (row = 0; row < subdivisions; row++) {
  24644. for (col = 0; col < subdivisions; col++) {
  24645. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  24646. indices.push(col + 1 + row * (subdivisions + 1));
  24647. indices.push(col + row * (subdivisions + 1));
  24648. indices.push(col + (row + 1) * (subdivisions + 1));
  24649. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  24650. indices.push(col + row * (subdivisions + 1));
  24651. }
  24652. }
  24653. // Result
  24654. var vertexData = new VertexData();
  24655. vertexData.indices = indices;
  24656. vertexData.positions = positions;
  24657. vertexData.normals = normals;
  24658. vertexData.uvs = uvs;
  24659. return vertexData;
  24660. };
  24661. VertexData.CreateTiledGround = function (options) {
  24662. var xmin = options.xmin;
  24663. var zmin = options.zmin;
  24664. var xmax = options.xmax;
  24665. var zmax = options.zmax;
  24666. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  24667. var precision = options.precision || { w: 1, h: 1 };
  24668. var indices = [];
  24669. var positions = [];
  24670. var normals = [];
  24671. var uvs = [];
  24672. var row, col, tileRow, tileCol;
  24673. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  24674. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  24675. precision.w = (precision.w < 1) ? 1 : precision.w;
  24676. precision.h = (precision.h < 1) ? 1 : precision.h;
  24677. var tileSize = {
  24678. 'w': (xmax - xmin) / subdivisions.w,
  24679. 'h': (zmax - zmin) / subdivisions.h
  24680. };
  24681. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  24682. // Indices
  24683. var base = positions.length / 3;
  24684. var rowLength = precision.w + 1;
  24685. for (row = 0; row < precision.h; row++) {
  24686. for (col = 0; col < precision.w; col++) {
  24687. var square = [
  24688. base + col + row * rowLength,
  24689. base + (col + 1) + row * rowLength,
  24690. base + (col + 1) + (row + 1) * rowLength,
  24691. base + col + (row + 1) * rowLength
  24692. ];
  24693. indices.push(square[1]);
  24694. indices.push(square[2]);
  24695. indices.push(square[3]);
  24696. indices.push(square[0]);
  24697. indices.push(square[1]);
  24698. indices.push(square[3]);
  24699. }
  24700. }
  24701. // Position, normals and uvs
  24702. var position = BABYLON.Vector3.Zero();
  24703. var normal = new BABYLON.Vector3(0, 1.0, 0);
  24704. for (row = 0; row <= precision.h; row++) {
  24705. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  24706. for (col = 0; col <= precision.w; col++) {
  24707. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  24708. position.y = 0;
  24709. positions.push(position.x, position.y, position.z);
  24710. normals.push(normal.x, normal.y, normal.z);
  24711. uvs.push(col / precision.w, row / precision.h);
  24712. }
  24713. }
  24714. }
  24715. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  24716. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  24717. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  24718. }
  24719. }
  24720. // Result
  24721. var vertexData = new VertexData();
  24722. vertexData.indices = indices;
  24723. vertexData.positions = positions;
  24724. vertexData.normals = normals;
  24725. vertexData.uvs = uvs;
  24726. return vertexData;
  24727. };
  24728. VertexData.CreateGroundFromHeightMap = function (options) {
  24729. var indices = [];
  24730. var positions = [];
  24731. var normals = [];
  24732. var uvs = [];
  24733. var row, col;
  24734. // Vertices
  24735. for (row = 0; row <= options.subdivisions; row++) {
  24736. for (col = 0; col <= options.subdivisions; col++) {
  24737. 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));
  24738. // Compute height
  24739. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  24740. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  24741. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  24742. var r = options.buffer[pos] / 255.0;
  24743. var g = options.buffer[pos + 1] / 255.0;
  24744. var b = options.buffer[pos + 2] / 255.0;
  24745. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  24746. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  24747. // Add vertex
  24748. positions.push(position.x, position.y, position.z);
  24749. normals.push(0, 0, 0);
  24750. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  24751. }
  24752. }
  24753. // Indices
  24754. for (row = 0; row < options.subdivisions; row++) {
  24755. for (col = 0; col < options.subdivisions; col++) {
  24756. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  24757. indices.push(col + 1 + row * (options.subdivisions + 1));
  24758. indices.push(col + row * (options.subdivisions + 1));
  24759. indices.push(col + (row + 1) * (options.subdivisions + 1));
  24760. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  24761. indices.push(col + row * (options.subdivisions + 1));
  24762. }
  24763. }
  24764. // Normals
  24765. VertexData.ComputeNormals(positions, indices, normals);
  24766. // Result
  24767. var vertexData = new VertexData();
  24768. vertexData.indices = indices;
  24769. vertexData.positions = positions;
  24770. vertexData.normals = normals;
  24771. vertexData.uvs = uvs;
  24772. return vertexData;
  24773. };
  24774. VertexData.CreatePlane = function (options) {
  24775. var indices = [];
  24776. var positions = [];
  24777. var normals = [];
  24778. var uvs = [];
  24779. var width = options.width || options.size || 1;
  24780. var height = options.height || options.size || 1;
  24781. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24782. // Vertices
  24783. var halfWidth = width / 2.0;
  24784. var halfHeight = height / 2.0;
  24785. positions.push(-halfWidth, -halfHeight, 0);
  24786. normals.push(0, 0, -1.0);
  24787. uvs.push(0.0, 0.0);
  24788. positions.push(halfWidth, -halfHeight, 0);
  24789. normals.push(0, 0, -1.0);
  24790. uvs.push(1.0, 0.0);
  24791. positions.push(halfWidth, halfHeight, 0);
  24792. normals.push(0, 0, -1.0);
  24793. uvs.push(1.0, 1.0);
  24794. positions.push(-halfWidth, halfHeight, 0);
  24795. normals.push(0, 0, -1.0);
  24796. uvs.push(0.0, 1.0);
  24797. // Indices
  24798. indices.push(0);
  24799. indices.push(1);
  24800. indices.push(2);
  24801. indices.push(0);
  24802. indices.push(2);
  24803. indices.push(3);
  24804. // Sides
  24805. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24806. // Result
  24807. var vertexData = new VertexData();
  24808. vertexData.indices = indices;
  24809. vertexData.positions = positions;
  24810. vertexData.normals = normals;
  24811. vertexData.uvs = uvs;
  24812. return vertexData;
  24813. };
  24814. VertexData.CreateDisc = function (options) {
  24815. var positions = [];
  24816. var indices = [];
  24817. var normals = [];
  24818. var uvs = [];
  24819. var radius = options.radius || 0.5;
  24820. var tessellation = options.tessellation || 64;
  24821. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  24822. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24823. // positions and uvs
  24824. positions.push(0, 0, 0); // disc center first
  24825. uvs.push(0.5, 0.5);
  24826. var theta = Math.PI * 2 * arc;
  24827. var step = theta / tessellation;
  24828. for (var a = 0; a < theta; a += step) {
  24829. var x = Math.cos(a);
  24830. var y = Math.sin(a);
  24831. var u = (x + 1) / 2;
  24832. var v = (1 - y) / 2;
  24833. positions.push(radius * x, radius * y, 0);
  24834. uvs.push(u, v);
  24835. }
  24836. if (arc === 1) {
  24837. positions.push(positions[3], positions[4], positions[5]); // close the circle
  24838. uvs.push(uvs[2], uvs[3]);
  24839. }
  24840. //indices
  24841. var vertexNb = positions.length / 3;
  24842. for (var i = 1; i < vertexNb - 1; i++) {
  24843. indices.push(i + 1, 0, i);
  24844. }
  24845. // result
  24846. VertexData.ComputeNormals(positions, indices, normals);
  24847. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24848. var vertexData = new VertexData();
  24849. vertexData.indices = indices;
  24850. vertexData.positions = positions;
  24851. vertexData.normals = normals;
  24852. vertexData.uvs = uvs;
  24853. return vertexData;
  24854. };
  24855. VertexData.CreateIcoSphere = function (options) {
  24856. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24857. var radius = options.radius || 1;
  24858. var flat = (options.flat === undefined) ? true : options.flat;
  24859. var subdivisions = options.subdivisions || 4;
  24860. var radiusX = options.radiusX || radius;
  24861. var radiusY = options.radiusY || radius;
  24862. var radiusZ = options.radiusZ || radius;
  24863. var t = (1 + Math.sqrt(5)) / 2;
  24864. // 12 vertex x,y,z
  24865. var ico_vertices = [
  24866. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  24867. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  24868. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  24869. ];
  24870. // index of 3 vertex makes a face of icopshere
  24871. var ico_indices = [
  24872. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  24873. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  24874. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  24875. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  24876. ];
  24877. // vertex for uv have aliased position, not for UV
  24878. var vertices_unalias_id = [
  24879. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  24880. // vertex alias
  24881. 0,
  24882. 2,
  24883. 3,
  24884. 3,
  24885. 3,
  24886. 4,
  24887. 7,
  24888. 8,
  24889. 9,
  24890. 9,
  24891. 10,
  24892. 11 // 23: B + 12
  24893. ];
  24894. // uv as integer step (not pixels !)
  24895. var ico_vertexuv = [
  24896. 5, 1, 3, 1, 6, 4, 0, 0,
  24897. 5, 3, 4, 2, 2, 2, 4, 0,
  24898. 2, 0, 1, 1, 6, 0, 6, 2,
  24899. // vertex alias (for same vertex on different faces)
  24900. 0, 4,
  24901. 3, 3,
  24902. 4, 4,
  24903. 3, 1,
  24904. 4, 2,
  24905. 4, 4,
  24906. 0, 2,
  24907. 1, 1,
  24908. 2, 2,
  24909. 3, 3,
  24910. 1, 3,
  24911. 2, 4 // 23: B + 12
  24912. ];
  24913. // Vertices[0, 1, ...9, A, B] : position on UV plane
  24914. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  24915. // First island of uv mapping
  24916. // v = 4h 3+ 2
  24917. // v = 3h 9+ 4
  24918. // v = 2h 9+ 5 B
  24919. // v = 1h 9 1 0
  24920. // v = 0h 3 8 7 A
  24921. // u = 0 1 2 3 4 5 6 *a
  24922. // Second island of uv mapping
  24923. // v = 4h 0+ B+ 4+
  24924. // v = 3h A+ 2+
  24925. // v = 2h 7+ 6 3+
  24926. // v = 1h 8+ 3+
  24927. // v = 0h
  24928. // u = 0 1 2 3 4 5 6 *a
  24929. // Face layout on texture UV mapping
  24930. // ============
  24931. // \ 4 /\ 16 / ======
  24932. // \ / \ / /\ 11 /
  24933. // \/ 7 \/ / \ /
  24934. // ======= / 10 \/
  24935. // /\ 17 /\ =======
  24936. // / \ / \ \ 15 /\
  24937. // / 8 \/ 12 \ \ / \
  24938. // ============ \/ 6 \
  24939. // \ 18 /\ ============
  24940. // \ / \ \ 5 /\ 0 /
  24941. // \/ 13 \ \ / \ /
  24942. // ======= \/ 1 \/
  24943. // =============
  24944. // /\ 19 /\ 2 /\
  24945. // / \ / \ / \
  24946. // / 14 \/ 9 \/ 3 \
  24947. // ===================
  24948. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  24949. var ustep = 138 / 1024;
  24950. var vstep = 239 / 1024;
  24951. var uoffset = 60 / 1024;
  24952. var voffset = 26 / 1024;
  24953. // Second island should have margin, not to touch the first island
  24954. // avoid any borderline artefact in pixel rounding
  24955. var island_u_offset = -40 / 1024;
  24956. var island_v_offset = +20 / 1024;
  24957. // face is either island 0 or 1 :
  24958. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  24959. var island = [
  24960. 0, 0, 0, 0, 1,
  24961. 0, 0, 1, 1, 0,
  24962. 0, 0, 1, 1, 0,
  24963. 0, 1, 1, 1, 0 // 15 - 19
  24964. ];
  24965. var indices = [];
  24966. var positions = [];
  24967. var normals = [];
  24968. var uvs = [];
  24969. var current_indice = 0;
  24970. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  24971. var face_vertex_pos = new Array(3);
  24972. var face_vertex_uv = new Array(3);
  24973. var v012;
  24974. for (v012 = 0; v012 < 3; v012++) {
  24975. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  24976. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  24977. }
  24978. // create all with normals
  24979. for (var face = 0; face < 20; face++) {
  24980. // 3 vertex per face
  24981. for (v012 = 0; v012 < 3; v012++) {
  24982. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  24983. var v_id = ico_indices[3 * face + v012];
  24984. // vertex have 3D position (x,y,z)
  24985. face_vertex_pos[v012].copyFromFloats(ico_vertices[3 * vertices_unalias_id[v_id]], ico_vertices[3 * vertices_unalias_id[v_id] + 1], ico_vertices[3 * vertices_unalias_id[v_id] + 2]);
  24986. // Normalize to get normal, then scale to radius
  24987. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  24988. // uv Coordinates from vertex ID
  24989. face_vertex_uv[v012].copyFromFloats(ico_vertexuv[2 * v_id] * ustep + uoffset + island[face] * island_u_offset, ico_vertexuv[2 * v_id + 1] * vstep + voffset + island[face] * island_v_offset);
  24990. }
  24991. // Subdivide the face (interpolate pos, norm, uv)
  24992. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  24993. // - norm is linear interpolation of vertex corner normal
  24994. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  24995. // - uv is linear interpolation
  24996. //
  24997. // Topology is as below for sub-divide by 2
  24998. // vertex shown as v0,v1,v2
  24999. // interp index is i1 to progress in range [v0,v1[
  25000. // interp index is i2 to progress in range [v0,v2[
  25001. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  25002. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  25003. //
  25004. //
  25005. // i2 v2
  25006. // ^ ^
  25007. // / / \
  25008. // / / \
  25009. // / / \
  25010. // / / (0,1) \
  25011. // / #---------\
  25012. // / / \ (0,0)'/ \
  25013. // / / \ / \
  25014. // / / \ / \
  25015. // / / (0,0) \ / (1,0) \
  25016. // / #---------#---------\
  25017. // v0 v1
  25018. //
  25019. // --------------------> i1
  25020. //
  25021. // interp of (i1,i2):
  25022. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  25023. // along i1 : lerp(x0,x1, i1/(S-i2))
  25024. //
  25025. // centroid of triangle is needed to get help normal computation
  25026. // (c1,c2) are used for centroid location
  25027. var interp_vertex = function (i1, i2, c1, c2) {
  25028. // vertex is interpolated from
  25029. // - face_vertex_pos[0..2]
  25030. // - face_vertex_uv[0..2]
  25031. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  25032. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  25033. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  25034. pos_interp.normalize();
  25035. var vertex_normal;
  25036. if (flat) {
  25037. // in flat mode, recalculate normal as face centroid normal
  25038. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  25039. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  25040. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  25041. }
  25042. else {
  25043. // in smooth mode, recalculate normal from each single vertex position
  25044. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  25045. }
  25046. // Vertex normal need correction due to X,Y,Z radius scaling
  25047. vertex_normal.x /= radiusX;
  25048. vertex_normal.y /= radiusY;
  25049. vertex_normal.z /= radiusZ;
  25050. vertex_normal.normalize();
  25051. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  25052. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  25053. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  25054. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  25055. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  25056. uvs.push(uv_interp.x, uv_interp.y);
  25057. // push each vertex has member of a face
  25058. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  25059. indices.push(current_indice);
  25060. current_indice++;
  25061. };
  25062. for (var i2 = 0; i2 < subdivisions; i2++) {
  25063. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  25064. // face : (i1,i2) for /\ :
  25065. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  25066. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  25067. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  25068. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  25069. if (i1 + i2 + 1 < subdivisions) {
  25070. // face : (i1,i2)' for \/ :
  25071. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  25072. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  25073. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  25074. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  25075. }
  25076. }
  25077. }
  25078. }
  25079. // Sides
  25080. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25081. // Result
  25082. var vertexData = new VertexData();
  25083. vertexData.indices = indices;
  25084. vertexData.positions = positions;
  25085. vertexData.normals = normals;
  25086. vertexData.uvs = uvs;
  25087. return vertexData;
  25088. };
  25089. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  25090. VertexData.CreatePolyhedron = function (options) {
  25091. // provided polyhedron types :
  25092. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  25093. // 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)
  25094. var polyhedra = [];
  25095. 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]] };
  25096. 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]] };
  25097. polyhedra[2] = {
  25098. 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]],
  25099. 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]]
  25100. };
  25101. polyhedra[3] = {
  25102. 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]],
  25103. 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]]
  25104. };
  25105. polyhedra[4] = {
  25106. 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]],
  25107. 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]]
  25108. };
  25109. 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]] };
  25110. 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]] };
  25111. 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]] };
  25112. 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]] };
  25113. 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]] };
  25114. 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]] };
  25115. 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]] };
  25116. 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]] };
  25117. 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]] };
  25118. polyhedra[14] = {
  25119. 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]],
  25120. 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]]
  25121. };
  25122. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  25123. var size = options.size;
  25124. var sizeX = options.sizeX || size || 1;
  25125. var sizeY = options.sizeY || size || 1;
  25126. var sizeZ = options.sizeZ || size || 1;
  25127. var data = options.custom || polyhedra[type];
  25128. var nbfaces = data.face.length;
  25129. var faceUV = options.faceUV || new Array(nbfaces);
  25130. var faceColors = options.faceColors;
  25131. var flat = (options.flat === undefined) ? true : options.flat;
  25132. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25133. var positions = [];
  25134. var indices = [];
  25135. var normals = [];
  25136. var uvs = [];
  25137. var colors = [];
  25138. var index = 0;
  25139. var faceIdx = 0; // face cursor in the array "indexes"
  25140. var indexes = [];
  25141. var i = 0;
  25142. var f = 0;
  25143. var u, v, ang, x, y, tmp;
  25144. // default face colors and UV if undefined
  25145. if (flat) {
  25146. for (f = 0; f < nbfaces; f++) {
  25147. if (faceColors && faceColors[f] === undefined) {
  25148. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  25149. }
  25150. if (faceUV && faceUV[f] === undefined) {
  25151. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  25152. }
  25153. }
  25154. }
  25155. if (!flat) {
  25156. for (i = 0; i < data.vertex.length; i++) {
  25157. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  25158. uvs.push(0, 0);
  25159. }
  25160. for (f = 0; f < nbfaces; f++) {
  25161. for (i = 0; i < data.face[f].length - 2; i++) {
  25162. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  25163. }
  25164. }
  25165. }
  25166. else {
  25167. for (f = 0; f < nbfaces; f++) {
  25168. var fl = data.face[f].length; // number of vertices of the current face
  25169. ang = 2 * Math.PI / fl;
  25170. x = 0.5 * Math.tan(ang / 2);
  25171. y = 0.5;
  25172. // positions, uvs, colors
  25173. for (i = 0; i < fl; i++) {
  25174. // positions
  25175. 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);
  25176. indexes.push(index);
  25177. index++;
  25178. // uvs
  25179. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  25180. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  25181. uvs.push(u, v);
  25182. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  25183. y = x * Math.sin(ang) + y * Math.cos(ang);
  25184. x = tmp;
  25185. // colors
  25186. if (faceColors) {
  25187. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  25188. }
  25189. }
  25190. // indices from indexes
  25191. for (i = 0; i < fl - 2; i++) {
  25192. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  25193. }
  25194. faceIdx += fl;
  25195. }
  25196. }
  25197. VertexData.ComputeNormals(positions, indices, normals);
  25198. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25199. var vertexData = new VertexData();
  25200. vertexData.positions = positions;
  25201. vertexData.indices = indices;
  25202. vertexData.normals = normals;
  25203. vertexData.uvs = uvs;
  25204. if (faceColors && flat) {
  25205. vertexData.colors = colors;
  25206. }
  25207. return vertexData;
  25208. };
  25209. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  25210. VertexData.CreateTorusKnot = function (options) {
  25211. var indices = [];
  25212. var positions = [];
  25213. var normals = [];
  25214. var uvs = [];
  25215. var radius = options.radius || 2;
  25216. var tube = options.tube || 0.5;
  25217. var radialSegments = options.radialSegments || 32;
  25218. var tubularSegments = options.tubularSegments || 32;
  25219. var p = options.p || 2;
  25220. var q = options.q || 3;
  25221. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25222. // Helper
  25223. var getPos = function (angle) {
  25224. var cu = Math.cos(angle);
  25225. var su = Math.sin(angle);
  25226. var quOverP = q / p * angle;
  25227. var cs = Math.cos(quOverP);
  25228. var tx = radius * (2 + cs) * 0.5 * cu;
  25229. var ty = radius * (2 + cs) * su * 0.5;
  25230. var tz = radius * Math.sin(quOverP) * 0.5;
  25231. return new BABYLON.Vector3(tx, ty, tz);
  25232. };
  25233. // Vertices
  25234. var i;
  25235. var j;
  25236. for (i = 0; i <= radialSegments; i++) {
  25237. var modI = i % radialSegments;
  25238. var u = modI / radialSegments * 2 * p * Math.PI;
  25239. var p1 = getPos(u);
  25240. var p2 = getPos(u + 0.01);
  25241. var tang = p2.subtract(p1);
  25242. var n = p2.add(p1);
  25243. var bitan = BABYLON.Vector3.Cross(tang, n);
  25244. n = BABYLON.Vector3.Cross(bitan, tang);
  25245. bitan.normalize();
  25246. n.normalize();
  25247. for (j = 0; j < tubularSegments; j++) {
  25248. var modJ = j % tubularSegments;
  25249. var v = modJ / tubularSegments * 2 * Math.PI;
  25250. var cx = -tube * Math.cos(v);
  25251. var cy = tube * Math.sin(v);
  25252. positions.push(p1.x + cx * n.x + cy * bitan.x);
  25253. positions.push(p1.y + cx * n.y + cy * bitan.y);
  25254. positions.push(p1.z + cx * n.z + cy * bitan.z);
  25255. uvs.push(i / radialSegments);
  25256. uvs.push(j / tubularSegments);
  25257. }
  25258. }
  25259. for (i = 0; i < radialSegments; i++) {
  25260. for (j = 0; j < tubularSegments; j++) {
  25261. var jNext = (j + 1) % tubularSegments;
  25262. var a = i * tubularSegments + j;
  25263. var b = (i + 1) * tubularSegments + j;
  25264. var c = (i + 1) * tubularSegments + jNext;
  25265. var d = i * tubularSegments + jNext;
  25266. indices.push(d);
  25267. indices.push(b);
  25268. indices.push(a);
  25269. indices.push(d);
  25270. indices.push(c);
  25271. indices.push(b);
  25272. }
  25273. }
  25274. // Normals
  25275. VertexData.ComputeNormals(positions, indices, normals);
  25276. // Sides
  25277. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25278. // Result
  25279. var vertexData = new VertexData();
  25280. vertexData.indices = indices;
  25281. vertexData.positions = positions;
  25282. vertexData.normals = normals;
  25283. vertexData.uvs = uvs;
  25284. return vertexData;
  25285. };
  25286. // Tools
  25287. /**
  25288. * @param {any} - positions (number[] or Float32Array)
  25289. * @param {any} - indices (number[] or Uint16Array)
  25290. * @param {any} - normals (number[] or Float32Array)
  25291. */
  25292. VertexData.ComputeNormals = function (positions, indices, normals) {
  25293. var index = 0;
  25294. var p1p2x = 0.0;
  25295. var p1p2y = 0.0;
  25296. var p1p2z = 0.0;
  25297. var p3p2x = 0.0;
  25298. var p3p2y = 0.0;
  25299. var p3p2z = 0.0;
  25300. var faceNormalx = 0.0;
  25301. var faceNormaly = 0.0;
  25302. var faceNormalz = 0.0;
  25303. var length = 0.0;
  25304. var i1 = 0;
  25305. var i2 = 0;
  25306. var i3 = 0;
  25307. for (index = 0; index < positions.length; index++) {
  25308. normals[index] = 0.0;
  25309. }
  25310. // indice triplet = 1 face
  25311. var nbFaces = indices.length / 3;
  25312. for (index = 0; index < nbFaces; index++) {
  25313. i1 = indices[index * 3]; // get the indexes of each vertex of the face
  25314. i2 = indices[index * 3 + 1];
  25315. i3 = indices[index * 3 + 2];
  25316. p1p2x = positions[i1 * 3] - positions[i2 * 3]; // compute two vectors per face
  25317. p1p2y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  25318. p1p2z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  25319. p3p2x = positions[i3 * 3] - positions[i2 * 3];
  25320. p3p2y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  25321. p3p2z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  25322. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y; // compute the face normal with cross product
  25323. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  25324. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  25325. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  25326. length = (length === 0) ? 1.0 : length;
  25327. faceNormalx /= length; // normalize this normal
  25328. faceNormaly /= length;
  25329. faceNormalz /= length;
  25330. normals[i1 * 3] += faceNormalx; // accumulate all the normals per face
  25331. normals[i1 * 3 + 1] += faceNormaly;
  25332. normals[i1 * 3 + 2] += faceNormalz;
  25333. normals[i2 * 3] += faceNormalx;
  25334. normals[i2 * 3 + 1] += faceNormaly;
  25335. normals[i2 * 3 + 2] += faceNormalz;
  25336. normals[i3 * 3] += faceNormalx;
  25337. normals[i3 * 3 + 1] += faceNormaly;
  25338. normals[i3 * 3 + 2] += faceNormalz;
  25339. }
  25340. // last normalization of each normal
  25341. for (index = 0; index < normals.length / 3; index++) {
  25342. faceNormalx = normals[index * 3];
  25343. faceNormaly = normals[index * 3 + 1];
  25344. faceNormalz = normals[index * 3 + 2];
  25345. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  25346. length = (length === 0) ? 1.0 : length;
  25347. faceNormalx /= length;
  25348. faceNormaly /= length;
  25349. faceNormalz /= length;
  25350. normals[index * 3] = faceNormalx;
  25351. normals[index * 3 + 1] = faceNormaly;
  25352. normals[index * 3 + 2] = faceNormalz;
  25353. }
  25354. };
  25355. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  25356. var li = indices.length;
  25357. var ln = normals.length;
  25358. var i;
  25359. var n;
  25360. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25361. switch (sideOrientation) {
  25362. case BABYLON.Mesh.FRONTSIDE:
  25363. // nothing changed
  25364. break;
  25365. case BABYLON.Mesh.BACKSIDE:
  25366. var tmp;
  25367. // indices
  25368. for (i = 0; i < li; i += 3) {
  25369. tmp = indices[i];
  25370. indices[i] = indices[i + 2];
  25371. indices[i + 2] = tmp;
  25372. }
  25373. // normals
  25374. for (n = 0; n < ln; n++) {
  25375. normals[n] = -normals[n];
  25376. }
  25377. break;
  25378. case BABYLON.Mesh.DOUBLESIDE:
  25379. // positions
  25380. var lp = positions.length;
  25381. var l = lp / 3;
  25382. for (var p = 0; p < lp; p++) {
  25383. positions[lp + p] = positions[p];
  25384. }
  25385. // indices
  25386. for (i = 0; i < li; i += 3) {
  25387. indices[i + li] = indices[i + 2] + l;
  25388. indices[i + 1 + li] = indices[i + 1] + l;
  25389. indices[i + 2 + li] = indices[i] + l;
  25390. }
  25391. // normals
  25392. for (n = 0; n < ln; n++) {
  25393. normals[ln + n] = -normals[n];
  25394. }
  25395. // uvs
  25396. var lu = uvs.length;
  25397. for (var u = 0; u < lu; u++) {
  25398. uvs[u + lu] = uvs[u];
  25399. }
  25400. break;
  25401. }
  25402. };
  25403. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  25404. var vertexData = new VertexData();
  25405. // positions
  25406. var positions = parsedVertexData.positions;
  25407. if (positions) {
  25408. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  25409. }
  25410. // normals
  25411. var normals = parsedVertexData.normals;
  25412. if (normals) {
  25413. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  25414. }
  25415. // uvs
  25416. var uvs = parsedVertexData.uvs;
  25417. if (uvs) {
  25418. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  25419. }
  25420. // uv2s
  25421. var uv2s = parsedVertexData.uv2s;
  25422. if (uv2s) {
  25423. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  25424. }
  25425. // uv3s
  25426. var uv3s = parsedVertexData.uv3s;
  25427. if (uv3s) {
  25428. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  25429. }
  25430. // uv4s
  25431. var uv4s = parsedVertexData.uv4s;
  25432. if (uv4s) {
  25433. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  25434. }
  25435. // uv5s
  25436. var uv5s = parsedVertexData.uv5s;
  25437. if (uv5s) {
  25438. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  25439. }
  25440. // uv6s
  25441. var uv6s = parsedVertexData.uv6s;
  25442. if (uv6s) {
  25443. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  25444. }
  25445. // colors
  25446. var colors = parsedVertexData.colors;
  25447. if (colors) {
  25448. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  25449. }
  25450. // matricesIndices
  25451. var matricesIndices = parsedVertexData.matricesIndices;
  25452. if (matricesIndices) {
  25453. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  25454. }
  25455. // matricesWeights
  25456. var matricesWeights = parsedVertexData.matricesWeights;
  25457. if (matricesWeights) {
  25458. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  25459. }
  25460. // indices
  25461. var indices = parsedVertexData.indices;
  25462. if (indices) {
  25463. vertexData.indices = indices;
  25464. }
  25465. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  25466. };
  25467. return VertexData;
  25468. })();
  25469. BABYLON.VertexData = VertexData;
  25470. })(BABYLON || (BABYLON = {}));
  25471. var BABYLON;
  25472. (function (BABYLON) {
  25473. var Tags = (function () {
  25474. function Tags() {
  25475. }
  25476. Tags.EnableFor = function (obj) {
  25477. obj._tags = obj._tags || {};
  25478. obj.hasTags = function () {
  25479. return Tags.HasTags(obj);
  25480. };
  25481. obj.addTags = function (tagsString) {
  25482. return Tags.AddTagsTo(obj, tagsString);
  25483. };
  25484. obj.removeTags = function (tagsString) {
  25485. return Tags.RemoveTagsFrom(obj, tagsString);
  25486. };
  25487. obj.matchesTagsQuery = function (tagsQuery) {
  25488. return Tags.MatchesQuery(obj, tagsQuery);
  25489. };
  25490. };
  25491. Tags.DisableFor = function (obj) {
  25492. delete obj._tags;
  25493. delete obj.hasTags;
  25494. delete obj.addTags;
  25495. delete obj.removeTags;
  25496. delete obj.matchesTagsQuery;
  25497. };
  25498. Tags.HasTags = function (obj) {
  25499. if (!obj._tags) {
  25500. return false;
  25501. }
  25502. return !BABYLON.Tools.IsEmpty(obj._tags);
  25503. };
  25504. Tags.GetTags = function (obj, asString) {
  25505. if (asString === void 0) { asString = true; }
  25506. if (!obj._tags) {
  25507. return null;
  25508. }
  25509. if (asString) {
  25510. var tagsArray = [];
  25511. for (var tag in obj._tags) {
  25512. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  25513. tagsArray.push(tag);
  25514. }
  25515. }
  25516. return tagsArray.join(" ");
  25517. }
  25518. else {
  25519. return obj._tags;
  25520. }
  25521. };
  25522. // the tags 'true' and 'false' are reserved and cannot be used as tags
  25523. // a tag cannot start with '||', '&&', and '!'
  25524. // it cannot contain whitespaces
  25525. Tags.AddTagsTo = function (obj, tagsString) {
  25526. if (!tagsString) {
  25527. return;
  25528. }
  25529. if (typeof tagsString !== "string") {
  25530. return;
  25531. }
  25532. var tags = tagsString.split(" ");
  25533. for (var t in tags) {
  25534. Tags._AddTagTo(obj, tags[t]);
  25535. }
  25536. };
  25537. Tags._AddTagTo = function (obj, tag) {
  25538. tag = tag.trim();
  25539. if (tag === "" || tag === "true" || tag === "false") {
  25540. return;
  25541. }
  25542. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  25543. return;
  25544. }
  25545. Tags.EnableFor(obj);
  25546. obj._tags[tag] = true;
  25547. };
  25548. Tags.RemoveTagsFrom = function (obj, tagsString) {
  25549. if (!Tags.HasTags(obj)) {
  25550. return;
  25551. }
  25552. var tags = tagsString.split(" ");
  25553. for (var t in tags) {
  25554. Tags._RemoveTagFrom(obj, tags[t]);
  25555. }
  25556. };
  25557. Tags._RemoveTagFrom = function (obj, tag) {
  25558. delete obj._tags[tag];
  25559. };
  25560. Tags.MatchesQuery = function (obj, tagsQuery) {
  25561. if (tagsQuery === undefined) {
  25562. return true;
  25563. }
  25564. if (tagsQuery === "") {
  25565. return Tags.HasTags(obj);
  25566. }
  25567. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  25568. };
  25569. return Tags;
  25570. })();
  25571. BABYLON.Tags = Tags;
  25572. })(BABYLON || (BABYLON = {}));
  25573. var BABYLON;
  25574. (function (BABYLON) {
  25575. var Internals;
  25576. (function (Internals) {
  25577. var AndOrNotEvaluator = (function () {
  25578. function AndOrNotEvaluator() {
  25579. }
  25580. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  25581. if (!query.match(/\([^\(\)]*\)/g)) {
  25582. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  25583. }
  25584. else {
  25585. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  25586. // remove parenthesis
  25587. r = r.slice(1, r.length - 1);
  25588. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  25589. });
  25590. }
  25591. if (query === "true") {
  25592. return true;
  25593. }
  25594. if (query === "false") {
  25595. return false;
  25596. }
  25597. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  25598. };
  25599. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  25600. evaluateCallback = evaluateCallback || (function (r) {
  25601. return r === "true" ? true : false;
  25602. });
  25603. var result;
  25604. var or = parenthesisContent.split("||");
  25605. for (var i in or) {
  25606. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  25607. var and = ori.split("&&");
  25608. if (and.length > 1) {
  25609. for (var j = 0; j < and.length; ++j) {
  25610. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  25611. if (andj !== "true" && andj !== "false") {
  25612. if (andj[0] === "!") {
  25613. result = !evaluateCallback(andj.substring(1));
  25614. }
  25615. else {
  25616. result = evaluateCallback(andj);
  25617. }
  25618. }
  25619. else {
  25620. result = andj === "true" ? true : false;
  25621. }
  25622. if (!result) {
  25623. ori = "false";
  25624. break;
  25625. }
  25626. }
  25627. }
  25628. if (result || ori === "true") {
  25629. result = true;
  25630. break;
  25631. }
  25632. // result equals false (or undefined)
  25633. if (ori !== "true" && ori !== "false") {
  25634. if (ori[0] === "!") {
  25635. result = !evaluateCallback(ori.substring(1));
  25636. }
  25637. else {
  25638. result = evaluateCallback(ori);
  25639. }
  25640. }
  25641. else {
  25642. result = ori === "true" ? true : false;
  25643. }
  25644. }
  25645. // the whole parenthesis scope is replaced by 'true' or 'false'
  25646. return result ? "true" : "false";
  25647. };
  25648. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  25649. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  25650. // remove whitespaces
  25651. r = r.replace(/[\s]/g, function () { return ""; });
  25652. return r.length % 2 ? "!" : "";
  25653. });
  25654. booleanString = booleanString.trim();
  25655. if (booleanString === "!true") {
  25656. booleanString = "false";
  25657. }
  25658. else if (booleanString === "!false") {
  25659. booleanString = "true";
  25660. }
  25661. return booleanString;
  25662. };
  25663. return AndOrNotEvaluator;
  25664. })();
  25665. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  25666. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  25667. })(BABYLON || (BABYLON = {}));
  25668. var BABYLON;
  25669. (function (BABYLON) {
  25670. var PostProcessRenderPass = (function () {
  25671. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  25672. this._enabled = true;
  25673. this._refCount = 0;
  25674. this._name = name;
  25675. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  25676. this.setRenderList(renderList);
  25677. this._renderTexture.onBeforeRender = beforeRender;
  25678. this._renderTexture.onAfterRender = afterRender;
  25679. this._scene = scene;
  25680. this._renderList = renderList;
  25681. }
  25682. // private
  25683. PostProcessRenderPass.prototype._incRefCount = function () {
  25684. if (this._refCount === 0) {
  25685. this._scene.customRenderTargets.push(this._renderTexture);
  25686. }
  25687. return ++this._refCount;
  25688. };
  25689. PostProcessRenderPass.prototype._decRefCount = function () {
  25690. this._refCount--;
  25691. if (this._refCount <= 0) {
  25692. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  25693. }
  25694. return this._refCount;
  25695. };
  25696. PostProcessRenderPass.prototype._update = function () {
  25697. this.setRenderList(this._renderList);
  25698. };
  25699. // public
  25700. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  25701. this._renderTexture.renderList = renderList;
  25702. };
  25703. PostProcessRenderPass.prototype.getRenderTexture = function () {
  25704. return this._renderTexture;
  25705. };
  25706. return PostProcessRenderPass;
  25707. })();
  25708. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  25709. })(BABYLON || (BABYLON = {}));
  25710. var BABYLON;
  25711. (function (BABYLON) {
  25712. var PostProcessRenderEffect = (function () {
  25713. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  25714. this._engine = engine;
  25715. this._name = name;
  25716. this._singleInstance = singleInstance || true;
  25717. this._getPostProcess = getPostProcess;
  25718. this._cameras = [];
  25719. this._indicesForCamera = [];
  25720. this._postProcesses = {};
  25721. this._renderPasses = {};
  25722. this._renderEffectAsPasses = {};
  25723. }
  25724. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  25725. get: function () {
  25726. for (var index in this._postProcesses) {
  25727. if (!this._postProcesses[index].isSupported) {
  25728. return false;
  25729. }
  25730. }
  25731. return true;
  25732. },
  25733. enumerable: true,
  25734. configurable: true
  25735. });
  25736. PostProcessRenderEffect.prototype._update = function () {
  25737. for (var renderPassName in this._renderPasses) {
  25738. this._renderPasses[renderPassName]._update();
  25739. }
  25740. };
  25741. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  25742. this._renderPasses[renderPass._name] = renderPass;
  25743. this._linkParameters();
  25744. };
  25745. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  25746. delete this._renderPasses[renderPass._name];
  25747. this._linkParameters();
  25748. };
  25749. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  25750. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  25751. this._linkParameters();
  25752. };
  25753. PostProcessRenderEffect.prototype.getPass = function (passName) {
  25754. for (var renderPassName in this._renderPasses) {
  25755. if (renderPassName === passName) {
  25756. return this._renderPasses[passName];
  25757. }
  25758. }
  25759. };
  25760. PostProcessRenderEffect.prototype.emptyPasses = function () {
  25761. this._renderPasses = {};
  25762. this._linkParameters();
  25763. };
  25764. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  25765. var cameraKey;
  25766. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25767. for (var i = 0; i < _cam.length; i++) {
  25768. var camera = _cam[i];
  25769. var cameraName = camera.name;
  25770. if (this._singleInstance) {
  25771. cameraKey = 0;
  25772. }
  25773. else {
  25774. cameraKey = cameraName;
  25775. }
  25776. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  25777. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  25778. if (!this._indicesForCamera[cameraName]) {
  25779. this._indicesForCamera[cameraName] = [];
  25780. }
  25781. this._indicesForCamera[cameraName].push(index);
  25782. if (this._cameras.indexOf(camera) === -1) {
  25783. this._cameras[cameraName] = camera;
  25784. }
  25785. for (var passName in this._renderPasses) {
  25786. this._renderPasses[passName]._incRefCount();
  25787. }
  25788. }
  25789. this._linkParameters();
  25790. };
  25791. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  25792. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25793. for (var i = 0; i < _cam.length; i++) {
  25794. var camera = _cam[i];
  25795. var cameraName = camera.name;
  25796. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  25797. var index = this._cameras.indexOf(cameraName);
  25798. this._indicesForCamera.splice(index, 1);
  25799. this._cameras.splice(index, 1);
  25800. for (var passName in this._renderPasses) {
  25801. this._renderPasses[passName]._decRefCount();
  25802. }
  25803. }
  25804. };
  25805. PostProcessRenderEffect.prototype._enable = function (cameras) {
  25806. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25807. for (var i = 0; i < _cam.length; i++) {
  25808. var camera = _cam[i];
  25809. var cameraName = camera.name;
  25810. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  25811. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  25812. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  25813. }
  25814. }
  25815. for (var passName in this._renderPasses) {
  25816. this._renderPasses[passName]._incRefCount();
  25817. }
  25818. }
  25819. };
  25820. PostProcessRenderEffect.prototype._disable = function (cameras) {
  25821. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25822. for (var i = 0; i < _cam.length; i++) {
  25823. var camera = _cam[i];
  25824. var cameraName = camera.Name;
  25825. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  25826. for (var passName in this._renderPasses) {
  25827. this._renderPasses[passName]._decRefCount();
  25828. }
  25829. }
  25830. };
  25831. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  25832. if (this._singleInstance) {
  25833. return this._postProcesses[0];
  25834. }
  25835. else {
  25836. return this._postProcesses[camera.name];
  25837. }
  25838. };
  25839. PostProcessRenderEffect.prototype._linkParameters = function () {
  25840. var _this = this;
  25841. for (var index in this._postProcesses) {
  25842. if (this.applyParameters) {
  25843. this.applyParameters(this._postProcesses[index]);
  25844. }
  25845. this._postProcesses[index].onBeforeRender = function (effect) {
  25846. _this._linkTextures(effect);
  25847. };
  25848. }
  25849. };
  25850. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  25851. for (var renderPassName in this._renderPasses) {
  25852. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  25853. }
  25854. for (var renderEffectName in this._renderEffectAsPasses) {
  25855. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  25856. }
  25857. };
  25858. return PostProcessRenderEffect;
  25859. })();
  25860. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  25861. })(BABYLON || (BABYLON = {}));
  25862. var BABYLON;
  25863. (function (BABYLON) {
  25864. var PostProcessRenderPipeline = (function () {
  25865. function PostProcessRenderPipeline(engine, name) {
  25866. this._engine = engine;
  25867. this._name = name;
  25868. this._renderEffects = {};
  25869. this._renderEffectsForIsolatedPass = {};
  25870. this._cameras = [];
  25871. }
  25872. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  25873. get: function () {
  25874. for (var renderEffectName in this._renderEffects) {
  25875. if (!this._renderEffects[renderEffectName].isSupported) {
  25876. return false;
  25877. }
  25878. }
  25879. return true;
  25880. },
  25881. enumerable: true,
  25882. configurable: true
  25883. });
  25884. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  25885. this._renderEffects[renderEffect._name] = renderEffect;
  25886. };
  25887. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  25888. var renderEffects = this._renderEffects[renderEffectName];
  25889. if (!renderEffects) {
  25890. return;
  25891. }
  25892. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  25893. };
  25894. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  25895. var renderEffects = this._renderEffects[renderEffectName];
  25896. if (!renderEffects) {
  25897. return;
  25898. }
  25899. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  25900. };
  25901. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  25902. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25903. var indicesToDelete = [];
  25904. var i;
  25905. for (i = 0; i < _cam.length; i++) {
  25906. var camera = _cam[i];
  25907. var cameraName = camera.name;
  25908. if (this._cameras.indexOf(camera) === -1) {
  25909. this._cameras[cameraName] = camera;
  25910. }
  25911. else if (unique) {
  25912. indicesToDelete.push(i);
  25913. }
  25914. }
  25915. for (i = 0; i < indicesToDelete.length; i++) {
  25916. cameras.splice(indicesToDelete[i], 1);
  25917. }
  25918. for (var renderEffectName in this._renderEffects) {
  25919. this._renderEffects[renderEffectName]._attachCameras(_cam);
  25920. }
  25921. };
  25922. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  25923. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25924. for (var renderEffectName in this._renderEffects) {
  25925. this._renderEffects[renderEffectName]._detachCameras(_cam);
  25926. }
  25927. for (var i = 0; i < _cam.length; i++) {
  25928. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  25929. }
  25930. };
  25931. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  25932. var _this = this;
  25933. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25934. var pass = null;
  25935. var renderEffectName;
  25936. for (renderEffectName in this._renderEffects) {
  25937. pass = this._renderEffects[renderEffectName].getPass(passName);
  25938. if (pass != null) {
  25939. break;
  25940. }
  25941. }
  25942. if (pass === null) {
  25943. return;
  25944. }
  25945. for (renderEffectName in this._renderEffects) {
  25946. this._renderEffects[renderEffectName]._disable(_cam);
  25947. }
  25948. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  25949. for (var i = 0; i < _cam.length; i++) {
  25950. var camera = _cam[i];
  25951. var cameraName = camera.name;
  25952. 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); });
  25953. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  25954. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  25955. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  25956. }
  25957. };
  25958. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  25959. var _this = this;
  25960. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25961. for (var i = 0; i < _cam.length; i++) {
  25962. var camera = _cam[i];
  25963. var cameraName = camera.name;
  25964. 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); });
  25965. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  25966. }
  25967. for (var renderEffectName in this._renderEffects) {
  25968. this._renderEffects[renderEffectName]._enable(_cam);
  25969. }
  25970. };
  25971. PostProcessRenderPipeline.prototype._update = function () {
  25972. for (var renderEffectName in this._renderEffects) {
  25973. this._renderEffects[renderEffectName]._update();
  25974. }
  25975. for (var i = 0; i < this._cameras.length; i++) {
  25976. var cameraName = this._cameras[i].name;
  25977. if (this._renderEffectsForIsolatedPass[cameraName]) {
  25978. this._renderEffectsForIsolatedPass[cameraName]._update();
  25979. }
  25980. }
  25981. };
  25982. PostProcessRenderPipeline.prototype.dispose = function () {
  25983. // Must be implemented by children
  25984. };
  25985. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  25986. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  25987. return PostProcessRenderPipeline;
  25988. })();
  25989. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  25990. })(BABYLON || (BABYLON = {}));
  25991. var BABYLON;
  25992. (function (BABYLON) {
  25993. var PostProcessRenderPipelineManager = (function () {
  25994. function PostProcessRenderPipelineManager() {
  25995. this._renderPipelines = {};
  25996. }
  25997. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  25998. this._renderPipelines[renderPipeline._name] = renderPipeline;
  25999. };
  26000. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  26001. var renderPipeline = this._renderPipelines[renderPipelineName];
  26002. if (!renderPipeline) {
  26003. return;
  26004. }
  26005. renderPipeline._attachCameras(cameras, unique);
  26006. };
  26007. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  26008. var renderPipeline = this._renderPipelines[renderPipelineName];
  26009. if (!renderPipeline) {
  26010. return;
  26011. }
  26012. renderPipeline._detachCameras(cameras);
  26013. };
  26014. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  26015. var renderPipeline = this._renderPipelines[renderPipelineName];
  26016. if (!renderPipeline) {
  26017. return;
  26018. }
  26019. renderPipeline._enableEffect(renderEffectName, cameras);
  26020. };
  26021. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  26022. var renderPipeline = this._renderPipelines[renderPipelineName];
  26023. if (!renderPipeline) {
  26024. return;
  26025. }
  26026. renderPipeline._disableEffect(renderEffectName, cameras);
  26027. };
  26028. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  26029. var renderPipeline = this._renderPipelines[renderPipelineName];
  26030. if (!renderPipeline) {
  26031. return;
  26032. }
  26033. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  26034. };
  26035. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  26036. var renderPipeline = this._renderPipelines[renderPipelineName];
  26037. if (!renderPipeline) {
  26038. return;
  26039. }
  26040. renderPipeline._disableDisplayOnlyPass(cameras);
  26041. };
  26042. PostProcessRenderPipelineManager.prototype.update = function () {
  26043. for (var renderPipelineName in this._renderPipelines) {
  26044. var pipeline = this._renderPipelines[renderPipelineName];
  26045. if (!pipeline.isSupported) {
  26046. pipeline.dispose();
  26047. delete this._renderPipelines[renderPipelineName];
  26048. }
  26049. else {
  26050. pipeline._update();
  26051. }
  26052. }
  26053. };
  26054. return PostProcessRenderPipelineManager;
  26055. })();
  26056. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  26057. })(BABYLON || (BABYLON = {}));
  26058. var BABYLON;
  26059. (function (BABYLON) {
  26060. var BoundingBoxRenderer = (function () {
  26061. function BoundingBoxRenderer(scene) {
  26062. this.frontColor = new BABYLON.Color3(1, 1, 1);
  26063. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  26064. this.showBackLines = true;
  26065. this.renderList = new BABYLON.SmartArray(32);
  26066. this._scene = scene;
  26067. }
  26068. BoundingBoxRenderer.prototype._prepareRessources = function () {
  26069. if (this._colorShader) {
  26070. return;
  26071. }
  26072. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  26073. attributes: ["position"],
  26074. uniforms: ["worldViewProjection", "color"]
  26075. });
  26076. var engine = this._scene.getEngine();
  26077. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  26078. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  26079. 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]);
  26080. };
  26081. BoundingBoxRenderer.prototype.reset = function () {
  26082. this.renderList.reset();
  26083. };
  26084. BoundingBoxRenderer.prototype.render = function () {
  26085. if (this.renderList.length === 0) {
  26086. return;
  26087. }
  26088. this._prepareRessources();
  26089. if (!this._colorShader.isReady()) {
  26090. return;
  26091. }
  26092. var engine = this._scene.getEngine();
  26093. engine.setDepthWrite(false);
  26094. this._colorShader._preBind();
  26095. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  26096. var boundingBox = this.renderList.data[boundingBoxIndex];
  26097. var min = boundingBox.minimum;
  26098. var max = boundingBox.maximum;
  26099. var diff = max.subtract(min);
  26100. var median = min.add(diff.scale(0.5));
  26101. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  26102. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  26103. .multiply(boundingBox.getWorldMatrix());
  26104. // VBOs
  26105. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  26106. if (this.showBackLines) {
  26107. // Back
  26108. engine.setDepthFunctionToGreaterOrEqual();
  26109. this._scene.resetCachedMaterial();
  26110. this._colorShader.setColor4("color", this.backColor.toColor4());
  26111. this._colorShader.bind(worldMatrix);
  26112. // Draw order
  26113. engine.draw(false, 0, 24);
  26114. }
  26115. // Front
  26116. engine.setDepthFunctionToLess();
  26117. this._scene.resetCachedMaterial();
  26118. this._colorShader.setColor4("color", this.frontColor.toColor4());
  26119. this._colorShader.bind(worldMatrix);
  26120. // Draw order
  26121. engine.draw(false, 0, 24);
  26122. }
  26123. this._colorShader.unbind();
  26124. engine.setDepthFunctionToLessOrEqual();
  26125. engine.setDepthWrite(true);
  26126. };
  26127. BoundingBoxRenderer.prototype.dispose = function () {
  26128. if (!this._colorShader) {
  26129. return;
  26130. }
  26131. this._colorShader.dispose();
  26132. this._vb.dispose();
  26133. this._scene.getEngine()._releaseBuffer(this._ib);
  26134. };
  26135. return BoundingBoxRenderer;
  26136. })();
  26137. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  26138. })(BABYLON || (BABYLON = {}));
  26139. var BABYLON;
  26140. (function (BABYLON) {
  26141. var Condition = (function () {
  26142. function Condition(actionManager) {
  26143. this._actionManager = actionManager;
  26144. }
  26145. Condition.prototype.isValid = function () {
  26146. return true;
  26147. };
  26148. Condition.prototype._getProperty = function (propertyPath) {
  26149. return this._actionManager._getProperty(propertyPath);
  26150. };
  26151. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  26152. return this._actionManager._getEffectiveTarget(target, propertyPath);
  26153. };
  26154. return Condition;
  26155. })();
  26156. BABYLON.Condition = Condition;
  26157. var ValueCondition = (function (_super) {
  26158. __extends(ValueCondition, _super);
  26159. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  26160. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  26161. _super.call(this, actionManager);
  26162. this.propertyPath = propertyPath;
  26163. this.value = value;
  26164. this.operator = operator;
  26165. this._target = this._getEffectiveTarget(target, this.propertyPath);
  26166. this._property = this._getProperty(this.propertyPath);
  26167. }
  26168. Object.defineProperty(ValueCondition, "IsEqual", {
  26169. get: function () {
  26170. return ValueCondition._IsEqual;
  26171. },
  26172. enumerable: true,
  26173. configurable: true
  26174. });
  26175. Object.defineProperty(ValueCondition, "IsDifferent", {
  26176. get: function () {
  26177. return ValueCondition._IsDifferent;
  26178. },
  26179. enumerable: true,
  26180. configurable: true
  26181. });
  26182. Object.defineProperty(ValueCondition, "IsGreater", {
  26183. get: function () {
  26184. return ValueCondition._IsGreater;
  26185. },
  26186. enumerable: true,
  26187. configurable: true
  26188. });
  26189. Object.defineProperty(ValueCondition, "IsLesser", {
  26190. get: function () {
  26191. return ValueCondition._IsLesser;
  26192. },
  26193. enumerable: true,
  26194. configurable: true
  26195. });
  26196. // Methods
  26197. ValueCondition.prototype.isValid = function () {
  26198. switch (this.operator) {
  26199. case ValueCondition.IsGreater:
  26200. return this._target[this._property] > this.value;
  26201. case ValueCondition.IsLesser:
  26202. return this._target[this._property] < this.value;
  26203. case ValueCondition.IsEqual:
  26204. case ValueCondition.IsDifferent:
  26205. var check;
  26206. if (this.value.equals) {
  26207. check = this.value.equals(this._target[this._property]);
  26208. }
  26209. else {
  26210. check = this.value === this._target[this._property];
  26211. }
  26212. return this.operator === ValueCondition.IsEqual ? check : !check;
  26213. }
  26214. return false;
  26215. };
  26216. // Statics
  26217. ValueCondition._IsEqual = 0;
  26218. ValueCondition._IsDifferent = 1;
  26219. ValueCondition._IsGreater = 2;
  26220. ValueCondition._IsLesser = 3;
  26221. return ValueCondition;
  26222. })(Condition);
  26223. BABYLON.ValueCondition = ValueCondition;
  26224. var PredicateCondition = (function (_super) {
  26225. __extends(PredicateCondition, _super);
  26226. function PredicateCondition(actionManager, predicate) {
  26227. _super.call(this, actionManager);
  26228. this.predicate = predicate;
  26229. }
  26230. PredicateCondition.prototype.isValid = function () {
  26231. return this.predicate();
  26232. };
  26233. return PredicateCondition;
  26234. })(Condition);
  26235. BABYLON.PredicateCondition = PredicateCondition;
  26236. var StateCondition = (function (_super) {
  26237. __extends(StateCondition, _super);
  26238. function StateCondition(actionManager, target, value) {
  26239. _super.call(this, actionManager);
  26240. this.value = value;
  26241. this._target = target;
  26242. }
  26243. // Methods
  26244. StateCondition.prototype.isValid = function () {
  26245. return this._target.state === this.value;
  26246. };
  26247. return StateCondition;
  26248. })(Condition);
  26249. BABYLON.StateCondition = StateCondition;
  26250. })(BABYLON || (BABYLON = {}));
  26251. var BABYLON;
  26252. (function (BABYLON) {
  26253. var Action = (function () {
  26254. function Action(triggerOptions, condition) {
  26255. this.triggerOptions = triggerOptions;
  26256. if (triggerOptions.parameter) {
  26257. this.trigger = triggerOptions.trigger;
  26258. this._triggerParameter = triggerOptions.parameter;
  26259. }
  26260. else {
  26261. this.trigger = triggerOptions;
  26262. }
  26263. this._nextActiveAction = this;
  26264. this._condition = condition;
  26265. }
  26266. // Methods
  26267. Action.prototype._prepare = function () {
  26268. };
  26269. Action.prototype.getTriggerParameter = function () {
  26270. return this._triggerParameter;
  26271. };
  26272. Action.prototype._executeCurrent = function (evt) {
  26273. if (this._nextActiveAction._condition) {
  26274. var condition = this._nextActiveAction._condition;
  26275. var currentRenderId = this._actionManager.getScene().getRenderId();
  26276. // We cache the current evaluation for the current frame
  26277. if (condition._evaluationId === currentRenderId) {
  26278. if (!condition._currentResult) {
  26279. return;
  26280. }
  26281. }
  26282. else {
  26283. condition._evaluationId = currentRenderId;
  26284. if (!condition.isValid()) {
  26285. condition._currentResult = false;
  26286. return;
  26287. }
  26288. condition._currentResult = true;
  26289. }
  26290. }
  26291. this._nextActiveAction.execute(evt);
  26292. this.skipToNextActiveAction();
  26293. };
  26294. Action.prototype.execute = function (evt) {
  26295. };
  26296. Action.prototype.skipToNextActiveAction = function () {
  26297. if (this._nextActiveAction._child) {
  26298. if (!this._nextActiveAction._child._actionManager) {
  26299. this._nextActiveAction._child._actionManager = this._actionManager;
  26300. }
  26301. this._nextActiveAction = this._nextActiveAction._child;
  26302. }
  26303. else {
  26304. this._nextActiveAction = this;
  26305. }
  26306. };
  26307. Action.prototype.then = function (action) {
  26308. this._child = action;
  26309. action._actionManager = this._actionManager;
  26310. action._prepare();
  26311. return action;
  26312. };
  26313. Action.prototype._getProperty = function (propertyPath) {
  26314. return this._actionManager._getProperty(propertyPath);
  26315. };
  26316. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  26317. return this._actionManager._getEffectiveTarget(target, propertyPath);
  26318. };
  26319. return Action;
  26320. })();
  26321. BABYLON.Action = Action;
  26322. })(BABYLON || (BABYLON = {}));
  26323. var BABYLON;
  26324. (function (BABYLON) {
  26325. /**
  26326. * ActionEvent is the event beint sent when an action is triggered.
  26327. */
  26328. var ActionEvent = (function () {
  26329. /**
  26330. * @constructor
  26331. * @param source The mesh or sprite that triggered the action.
  26332. * @param pointerX The X mouse cursor position at the time of the event
  26333. * @param pointerY The Y mouse cursor position at the time of the event
  26334. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  26335. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  26336. */
  26337. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  26338. this.source = source;
  26339. this.pointerX = pointerX;
  26340. this.pointerY = pointerY;
  26341. this.meshUnderPointer = meshUnderPointer;
  26342. this.sourceEvent = sourceEvent;
  26343. this.additionalData = additionalData;
  26344. }
  26345. /**
  26346. * Helper function to auto-create an ActionEvent from a source mesh.
  26347. * @param source The source mesh that triggered the event
  26348. * @param evt {Event} The original (browser) event
  26349. */
  26350. ActionEvent.CreateNew = function (source, evt, additionalData) {
  26351. var scene = source.getScene();
  26352. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  26353. };
  26354. /**
  26355. * Helper function to auto-create an ActionEvent from a source mesh.
  26356. * @param source The source sprite that triggered the event
  26357. * @param scene Scene associated with the sprite
  26358. * @param evt {Event} The original (browser) event
  26359. */
  26360. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  26361. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  26362. };
  26363. /**
  26364. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  26365. * @param scene the scene where the event occurred
  26366. * @param evt {Event} The original (browser) event
  26367. */
  26368. ActionEvent.CreateNewFromScene = function (scene, evt) {
  26369. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  26370. };
  26371. return ActionEvent;
  26372. })();
  26373. BABYLON.ActionEvent = ActionEvent;
  26374. /**
  26375. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  26376. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  26377. */
  26378. var ActionManager = (function () {
  26379. function ActionManager(scene) {
  26380. // Members
  26381. this.actions = new Array();
  26382. this._scene = scene;
  26383. scene._actionManagers.push(this);
  26384. }
  26385. Object.defineProperty(ActionManager, "NothingTrigger", {
  26386. get: function () {
  26387. return ActionManager._NothingTrigger;
  26388. },
  26389. enumerable: true,
  26390. configurable: true
  26391. });
  26392. Object.defineProperty(ActionManager, "OnPickTrigger", {
  26393. get: function () {
  26394. return ActionManager._OnPickTrigger;
  26395. },
  26396. enumerable: true,
  26397. configurable: true
  26398. });
  26399. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  26400. get: function () {
  26401. return ActionManager._OnLeftPickTrigger;
  26402. },
  26403. enumerable: true,
  26404. configurable: true
  26405. });
  26406. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  26407. get: function () {
  26408. return ActionManager._OnRightPickTrigger;
  26409. },
  26410. enumerable: true,
  26411. configurable: true
  26412. });
  26413. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  26414. get: function () {
  26415. return ActionManager._OnCenterPickTrigger;
  26416. },
  26417. enumerable: true,
  26418. configurable: true
  26419. });
  26420. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  26421. get: function () {
  26422. return ActionManager._OnPickDownTrigger;
  26423. },
  26424. enumerable: true,
  26425. configurable: true
  26426. });
  26427. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  26428. get: function () {
  26429. return ActionManager._OnPickUpTrigger;
  26430. },
  26431. enumerable: true,
  26432. configurable: true
  26433. });
  26434. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  26435. /// This trigger will only be raised if you also declared a OnPickDown
  26436. get: function () {
  26437. return ActionManager._OnPickOutTrigger;
  26438. },
  26439. enumerable: true,
  26440. configurable: true
  26441. });
  26442. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  26443. get: function () {
  26444. return ActionManager._OnLongPressTrigger;
  26445. },
  26446. enumerable: true,
  26447. configurable: true
  26448. });
  26449. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  26450. get: function () {
  26451. return ActionManager._OnPointerOverTrigger;
  26452. },
  26453. enumerable: true,
  26454. configurable: true
  26455. });
  26456. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  26457. get: function () {
  26458. return ActionManager._OnPointerOutTrigger;
  26459. },
  26460. enumerable: true,
  26461. configurable: true
  26462. });
  26463. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  26464. get: function () {
  26465. return ActionManager._OnEveryFrameTrigger;
  26466. },
  26467. enumerable: true,
  26468. configurable: true
  26469. });
  26470. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  26471. get: function () {
  26472. return ActionManager._OnIntersectionEnterTrigger;
  26473. },
  26474. enumerable: true,
  26475. configurable: true
  26476. });
  26477. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  26478. get: function () {
  26479. return ActionManager._OnIntersectionExitTrigger;
  26480. },
  26481. enumerable: true,
  26482. configurable: true
  26483. });
  26484. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  26485. get: function () {
  26486. return ActionManager._OnKeyDownTrigger;
  26487. },
  26488. enumerable: true,
  26489. configurable: true
  26490. });
  26491. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  26492. get: function () {
  26493. return ActionManager._OnKeyUpTrigger;
  26494. },
  26495. enumerable: true,
  26496. configurable: true
  26497. });
  26498. // Methods
  26499. ActionManager.prototype.dispose = function () {
  26500. var index = this._scene._actionManagers.indexOf(this);
  26501. if (index > -1) {
  26502. this._scene._actionManagers.splice(index, 1);
  26503. }
  26504. };
  26505. ActionManager.prototype.getScene = function () {
  26506. return this._scene;
  26507. };
  26508. /**
  26509. * Does this action manager handles actions of any of the given triggers
  26510. * @param {number[]} triggers - the triggers to be tested
  26511. * @return {boolean} whether one (or more) of the triggers is handeled
  26512. */
  26513. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  26514. for (var index = 0; index < this.actions.length; index++) {
  26515. var action = this.actions[index];
  26516. if (triggers.indexOf(action.trigger) > -1) {
  26517. return true;
  26518. }
  26519. }
  26520. return false;
  26521. };
  26522. /**
  26523. * Does this action manager handles actions of a given trigger
  26524. * @param {number} trigger - the trigger to be tested
  26525. * @return {boolean} whether the trigger is handeled
  26526. */
  26527. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  26528. for (var index = 0; index < this.actions.length; index++) {
  26529. var action = this.actions[index];
  26530. if (action.trigger === trigger) {
  26531. return true;
  26532. }
  26533. }
  26534. return false;
  26535. };
  26536. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  26537. /**
  26538. * Does this action manager has pointer triggers
  26539. * @return {boolean} whether or not it has pointer triggers
  26540. */
  26541. get: function () {
  26542. for (var index = 0; index < this.actions.length; index++) {
  26543. var action = this.actions[index];
  26544. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  26545. return true;
  26546. }
  26547. }
  26548. return false;
  26549. },
  26550. enumerable: true,
  26551. configurable: true
  26552. });
  26553. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  26554. /**
  26555. * Does this action manager has pick triggers
  26556. * @return {boolean} whether or not it has pick triggers
  26557. */
  26558. get: function () {
  26559. for (var index = 0; index < this.actions.length; index++) {
  26560. var action = this.actions[index];
  26561. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  26562. return true;
  26563. }
  26564. }
  26565. return false;
  26566. },
  26567. enumerable: true,
  26568. configurable: true
  26569. });
  26570. /**
  26571. * Registers an action to this action manager
  26572. * @param {BABYLON.Action} action - the action to be registered
  26573. * @return {BABYLON.Action} the action amended (prepared) after registration
  26574. */
  26575. ActionManager.prototype.registerAction = function (action) {
  26576. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  26577. if (this.getScene().actionManager !== this) {
  26578. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  26579. return null;
  26580. }
  26581. }
  26582. this.actions.push(action);
  26583. action._actionManager = this;
  26584. action._prepare();
  26585. return action;
  26586. };
  26587. /**
  26588. * Process a specific trigger
  26589. * @param {number} trigger - the trigger to process
  26590. * @param evt {BABYLON.ActionEvent} the event details to be processed
  26591. */
  26592. ActionManager.prototype.processTrigger = function (trigger, evt) {
  26593. for (var index = 0; index < this.actions.length; index++) {
  26594. var action = this.actions[index];
  26595. if (action.trigger === trigger) {
  26596. if (trigger === ActionManager.OnKeyUpTrigger
  26597. || trigger === ActionManager.OnKeyDownTrigger) {
  26598. var parameter = action.getTriggerParameter();
  26599. if (parameter) {
  26600. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  26601. var actualkey = String.fromCharCode(unicode).toLowerCase();
  26602. if (actualkey !== parameter.toLowerCase()) {
  26603. continue;
  26604. }
  26605. }
  26606. }
  26607. action._executeCurrent(evt);
  26608. }
  26609. }
  26610. };
  26611. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  26612. var properties = propertyPath.split(".");
  26613. for (var index = 0; index < properties.length - 1; index++) {
  26614. target = target[properties[index]];
  26615. }
  26616. return target;
  26617. };
  26618. ActionManager.prototype._getProperty = function (propertyPath) {
  26619. var properties = propertyPath.split(".");
  26620. return properties[properties.length - 1];
  26621. };
  26622. ActionManager.Parse = function (parsedActions, object, scene) {
  26623. var actionManager = new BABYLON.ActionManager(scene);
  26624. if (object === null)
  26625. scene.actionManager = actionManager;
  26626. else
  26627. object.actionManager = actionManager;
  26628. // instanciate a new object
  26629. var instanciate = function (name, params) {
  26630. var newInstance = Object.create(BABYLON[name].prototype);
  26631. newInstance.constructor.apply(newInstance, params);
  26632. return newInstance;
  26633. };
  26634. var parseParameter = function (name, value, target, propertyPath) {
  26635. if (propertyPath === null) {
  26636. // String, boolean or float
  26637. var floatValue = parseFloat(value);
  26638. if (value === "true" || value === "false")
  26639. return value === "true";
  26640. else
  26641. return isNaN(floatValue) ? value : floatValue;
  26642. }
  26643. var effectiveTarget = propertyPath.split(".");
  26644. var values = value.split(",");
  26645. // Get effective Target
  26646. for (var i = 0; i < effectiveTarget.length; i++) {
  26647. target = target[effectiveTarget[i]];
  26648. }
  26649. // Return appropriate value with its type
  26650. if (typeof (target) === "boolean")
  26651. return values[0] === "true";
  26652. if (typeof (target) === "string")
  26653. return values[0];
  26654. // Parameters with multiple values such as Vector3 etc.
  26655. var split = new Array();
  26656. for (var i = 0; i < values.length; i++)
  26657. split.push(parseFloat(values[i]));
  26658. if (target instanceof BABYLON.Vector3)
  26659. return BABYLON.Vector3.FromArray(split);
  26660. if (target instanceof BABYLON.Vector4)
  26661. return BABYLON.Vector4.FromArray(split);
  26662. if (target instanceof BABYLON.Color3)
  26663. return BABYLON.Color3.FromArray(split);
  26664. if (target instanceof BABYLON.Color4)
  26665. return BABYLON.Color4.FromArray(split);
  26666. return parseFloat(values[0]);
  26667. };
  26668. // traverse graph per trigger
  26669. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  26670. if (combineArray === void 0) { combineArray = null; }
  26671. if (parsedAction.detached)
  26672. return;
  26673. var parameters = new Array();
  26674. var target = null;
  26675. var propertyPath = null;
  26676. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  26677. // Parameters
  26678. if (parsedAction.type === 2)
  26679. parameters.push(actionManager);
  26680. else
  26681. parameters.push(trigger);
  26682. if (combine) {
  26683. var actions = new Array();
  26684. for (var j = 0; j < parsedAction.combine.length; j++) {
  26685. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  26686. }
  26687. parameters.push(actions);
  26688. }
  26689. else {
  26690. for (var i = 0; i < parsedAction.properties.length; i++) {
  26691. var value = parsedAction.properties[i].value;
  26692. var name = parsedAction.properties[i].name;
  26693. var targetType = parsedAction.properties[i].targetType;
  26694. if (name === "target")
  26695. if (targetType !== null && targetType === "SceneProperties")
  26696. value = target = scene;
  26697. else
  26698. value = target = scene.getNodeByName(value);
  26699. else if (name === "parent")
  26700. value = scene.getNodeByName(value);
  26701. else if (name === "sound")
  26702. value = scene.getSoundByName(value);
  26703. else if (name !== "propertyPath") {
  26704. if (parsedAction.type === 2 && name === "operator")
  26705. value = BABYLON.ValueCondition[value];
  26706. else
  26707. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  26708. }
  26709. else {
  26710. propertyPath = value;
  26711. }
  26712. parameters.push(value);
  26713. }
  26714. }
  26715. if (combineArray === null) {
  26716. parameters.push(condition);
  26717. }
  26718. else {
  26719. parameters.push(null);
  26720. }
  26721. // If interpolate value action
  26722. if (parsedAction.name === "InterpolateValueAction") {
  26723. var param = parameters[parameters.length - 2];
  26724. parameters[parameters.length - 1] = param;
  26725. parameters[parameters.length - 2] = condition;
  26726. }
  26727. // Action or condition(s) and not CombineAction
  26728. var newAction = instanciate(parsedAction.name, parameters);
  26729. if (newAction instanceof BABYLON.Condition && condition !== null) {
  26730. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  26731. if (action)
  26732. action.then(nothing);
  26733. else
  26734. actionManager.registerAction(nothing);
  26735. action = nothing;
  26736. }
  26737. if (combineArray === null) {
  26738. if (newAction instanceof BABYLON.Condition) {
  26739. condition = newAction;
  26740. newAction = action;
  26741. }
  26742. else {
  26743. condition = null;
  26744. if (action)
  26745. action.then(newAction);
  26746. else
  26747. actionManager.registerAction(newAction);
  26748. }
  26749. }
  26750. else {
  26751. combineArray.push(newAction);
  26752. }
  26753. for (var i = 0; i < parsedAction.children.length; i++)
  26754. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  26755. };
  26756. // triggers
  26757. for (var i = 0; i < parsedActions.children.length; i++) {
  26758. var triggerParams;
  26759. var trigger = parsedActions.children[i];
  26760. if (trigger.properties.length > 0) {
  26761. var param = trigger.properties[0].value;
  26762. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  26763. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  26764. }
  26765. else
  26766. triggerParams = BABYLON.ActionManager[trigger.name];
  26767. for (var j = 0; j < trigger.children.length; j++) {
  26768. if (!trigger.detached)
  26769. traverse(trigger.children[j], triggerParams, null, null);
  26770. }
  26771. }
  26772. };
  26773. // Statics
  26774. ActionManager._NothingTrigger = 0;
  26775. ActionManager._OnPickTrigger = 1;
  26776. ActionManager._OnLeftPickTrigger = 2;
  26777. ActionManager._OnRightPickTrigger = 3;
  26778. ActionManager._OnCenterPickTrigger = 4;
  26779. ActionManager._OnPickDownTrigger = 5;
  26780. ActionManager._OnPickUpTrigger = 6;
  26781. ActionManager._OnLongPressTrigger = 7;
  26782. ActionManager._OnPointerOverTrigger = 8;
  26783. ActionManager._OnPointerOutTrigger = 9;
  26784. ActionManager._OnEveryFrameTrigger = 10;
  26785. ActionManager._OnIntersectionEnterTrigger = 11;
  26786. ActionManager._OnIntersectionExitTrigger = 12;
  26787. ActionManager._OnKeyDownTrigger = 13;
  26788. ActionManager._OnKeyUpTrigger = 14;
  26789. ActionManager._OnPickOutTrigger = 15;
  26790. ActionManager.DragMovementThreshold = 10; // in pixels
  26791. ActionManager.LongPressDelay = 500; // in milliseconds
  26792. return ActionManager;
  26793. })();
  26794. BABYLON.ActionManager = ActionManager;
  26795. })(BABYLON || (BABYLON = {}));
  26796. var BABYLON;
  26797. (function (BABYLON) {
  26798. var InterpolateValueAction = (function (_super) {
  26799. __extends(InterpolateValueAction, _super);
  26800. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  26801. if (duration === void 0) { duration = 1000; }
  26802. _super.call(this, triggerOptions, condition);
  26803. this.propertyPath = propertyPath;
  26804. this.value = value;
  26805. this.duration = duration;
  26806. this.stopOtherAnimations = stopOtherAnimations;
  26807. this.onInterpolationDone = onInterpolationDone;
  26808. this._target = target;
  26809. }
  26810. InterpolateValueAction.prototype._prepare = function () {
  26811. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  26812. this._property = this._getProperty(this.propertyPath);
  26813. };
  26814. InterpolateValueAction.prototype.execute = function () {
  26815. var scene = this._actionManager.getScene();
  26816. var keys = [
  26817. {
  26818. frame: 0,
  26819. value: this._target[this._property]
  26820. }, {
  26821. frame: 100,
  26822. value: this.value
  26823. }
  26824. ];
  26825. var dataType;
  26826. if (typeof this.value === "number") {
  26827. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  26828. }
  26829. else if (this.value instanceof BABYLON.Color3) {
  26830. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  26831. }
  26832. else if (this.value instanceof BABYLON.Vector3) {
  26833. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  26834. }
  26835. else if (this.value instanceof BABYLON.Matrix) {
  26836. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  26837. }
  26838. else if (this.value instanceof BABYLON.Quaternion) {
  26839. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  26840. }
  26841. else {
  26842. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  26843. return;
  26844. }
  26845. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  26846. animation.setKeys(keys);
  26847. if (this.stopOtherAnimations) {
  26848. scene.stopAnimation(this._target);
  26849. }
  26850. scene.beginDirectAnimation(this._target, [animation], 0, 100, false, 1, this.onInterpolationDone);
  26851. };
  26852. return InterpolateValueAction;
  26853. })(BABYLON.Action);
  26854. BABYLON.InterpolateValueAction = InterpolateValueAction;
  26855. })(BABYLON || (BABYLON = {}));
  26856. var BABYLON;
  26857. (function (BABYLON) {
  26858. var SwitchBooleanAction = (function (_super) {
  26859. __extends(SwitchBooleanAction, _super);
  26860. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  26861. _super.call(this, triggerOptions, condition);
  26862. this.propertyPath = propertyPath;
  26863. this._target = target;
  26864. }
  26865. SwitchBooleanAction.prototype._prepare = function () {
  26866. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  26867. this._property = this._getProperty(this.propertyPath);
  26868. };
  26869. SwitchBooleanAction.prototype.execute = function () {
  26870. this._target[this._property] = !this._target[this._property];
  26871. };
  26872. return SwitchBooleanAction;
  26873. })(BABYLON.Action);
  26874. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  26875. var SetStateAction = (function (_super) {
  26876. __extends(SetStateAction, _super);
  26877. function SetStateAction(triggerOptions, target, value, condition) {
  26878. _super.call(this, triggerOptions, condition);
  26879. this.value = value;
  26880. this._target = target;
  26881. }
  26882. SetStateAction.prototype.execute = function () {
  26883. this._target.state = this.value;
  26884. };
  26885. return SetStateAction;
  26886. })(BABYLON.Action);
  26887. BABYLON.SetStateAction = SetStateAction;
  26888. var SetValueAction = (function (_super) {
  26889. __extends(SetValueAction, _super);
  26890. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  26891. _super.call(this, triggerOptions, condition);
  26892. this.propertyPath = propertyPath;
  26893. this.value = value;
  26894. this._target = target;
  26895. }
  26896. SetValueAction.prototype._prepare = function () {
  26897. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  26898. this._property = this._getProperty(this.propertyPath);
  26899. };
  26900. SetValueAction.prototype.execute = function () {
  26901. this._target[this._property] = this.value;
  26902. };
  26903. return SetValueAction;
  26904. })(BABYLON.Action);
  26905. BABYLON.SetValueAction = SetValueAction;
  26906. var IncrementValueAction = (function (_super) {
  26907. __extends(IncrementValueAction, _super);
  26908. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  26909. _super.call(this, triggerOptions, condition);
  26910. this.propertyPath = propertyPath;
  26911. this.value = value;
  26912. this._target = target;
  26913. }
  26914. IncrementValueAction.prototype._prepare = function () {
  26915. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  26916. this._property = this._getProperty(this.propertyPath);
  26917. if (typeof this._target[this._property] !== "number") {
  26918. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  26919. }
  26920. };
  26921. IncrementValueAction.prototype.execute = function () {
  26922. this._target[this._property] += this.value;
  26923. };
  26924. return IncrementValueAction;
  26925. })(BABYLON.Action);
  26926. BABYLON.IncrementValueAction = IncrementValueAction;
  26927. var PlayAnimationAction = (function (_super) {
  26928. __extends(PlayAnimationAction, _super);
  26929. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  26930. _super.call(this, triggerOptions, condition);
  26931. this.from = from;
  26932. this.to = to;
  26933. this.loop = loop;
  26934. this._target = target;
  26935. }
  26936. PlayAnimationAction.prototype._prepare = function () {
  26937. };
  26938. PlayAnimationAction.prototype.execute = function () {
  26939. var scene = this._actionManager.getScene();
  26940. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  26941. };
  26942. return PlayAnimationAction;
  26943. })(BABYLON.Action);
  26944. BABYLON.PlayAnimationAction = PlayAnimationAction;
  26945. var StopAnimationAction = (function (_super) {
  26946. __extends(StopAnimationAction, _super);
  26947. function StopAnimationAction(triggerOptions, target, condition) {
  26948. _super.call(this, triggerOptions, condition);
  26949. this._target = target;
  26950. }
  26951. StopAnimationAction.prototype._prepare = function () {
  26952. };
  26953. StopAnimationAction.prototype.execute = function () {
  26954. var scene = this._actionManager.getScene();
  26955. scene.stopAnimation(this._target);
  26956. };
  26957. return StopAnimationAction;
  26958. })(BABYLON.Action);
  26959. BABYLON.StopAnimationAction = StopAnimationAction;
  26960. var DoNothingAction = (function (_super) {
  26961. __extends(DoNothingAction, _super);
  26962. function DoNothingAction(triggerOptions, condition) {
  26963. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  26964. _super.call(this, triggerOptions, condition);
  26965. }
  26966. DoNothingAction.prototype.execute = function () {
  26967. };
  26968. return DoNothingAction;
  26969. })(BABYLON.Action);
  26970. BABYLON.DoNothingAction = DoNothingAction;
  26971. var CombineAction = (function (_super) {
  26972. __extends(CombineAction, _super);
  26973. function CombineAction(triggerOptions, children, condition) {
  26974. _super.call(this, triggerOptions, condition);
  26975. this.children = children;
  26976. }
  26977. CombineAction.prototype._prepare = function () {
  26978. for (var index = 0; index < this.children.length; index++) {
  26979. this.children[index]._actionManager = this._actionManager;
  26980. this.children[index]._prepare();
  26981. }
  26982. };
  26983. CombineAction.prototype.execute = function (evt) {
  26984. for (var index = 0; index < this.children.length; index++) {
  26985. this.children[index].execute(evt);
  26986. }
  26987. };
  26988. return CombineAction;
  26989. })(BABYLON.Action);
  26990. BABYLON.CombineAction = CombineAction;
  26991. var ExecuteCodeAction = (function (_super) {
  26992. __extends(ExecuteCodeAction, _super);
  26993. function ExecuteCodeAction(triggerOptions, func, condition) {
  26994. _super.call(this, triggerOptions, condition);
  26995. this.func = func;
  26996. }
  26997. ExecuteCodeAction.prototype.execute = function (evt) {
  26998. this.func(evt);
  26999. };
  27000. return ExecuteCodeAction;
  27001. })(BABYLON.Action);
  27002. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  27003. var SetParentAction = (function (_super) {
  27004. __extends(SetParentAction, _super);
  27005. function SetParentAction(triggerOptions, target, parent, condition) {
  27006. _super.call(this, triggerOptions, condition);
  27007. this._target = target;
  27008. this._parent = parent;
  27009. }
  27010. SetParentAction.prototype._prepare = function () {
  27011. };
  27012. SetParentAction.prototype.execute = function () {
  27013. if (this._target.parent === this._parent) {
  27014. return;
  27015. }
  27016. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  27017. invertParentWorldMatrix.invert();
  27018. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  27019. this._target.parent = this._parent;
  27020. };
  27021. return SetParentAction;
  27022. })(BABYLON.Action);
  27023. BABYLON.SetParentAction = SetParentAction;
  27024. var PlaySoundAction = (function (_super) {
  27025. __extends(PlaySoundAction, _super);
  27026. function PlaySoundAction(triggerOptions, sound, condition) {
  27027. _super.call(this, triggerOptions, condition);
  27028. this._sound = sound;
  27029. }
  27030. PlaySoundAction.prototype._prepare = function () {
  27031. };
  27032. PlaySoundAction.prototype.execute = function () {
  27033. if (this._sound !== undefined)
  27034. this._sound.play();
  27035. };
  27036. return PlaySoundAction;
  27037. })(BABYLON.Action);
  27038. BABYLON.PlaySoundAction = PlaySoundAction;
  27039. var StopSoundAction = (function (_super) {
  27040. __extends(StopSoundAction, _super);
  27041. function StopSoundAction(triggerOptions, sound, condition) {
  27042. _super.call(this, triggerOptions, condition);
  27043. this._sound = sound;
  27044. }
  27045. StopSoundAction.prototype._prepare = function () {
  27046. };
  27047. StopSoundAction.prototype.execute = function () {
  27048. if (this._sound !== undefined)
  27049. this._sound.stop();
  27050. };
  27051. return StopSoundAction;
  27052. })(BABYLON.Action);
  27053. BABYLON.StopSoundAction = StopSoundAction;
  27054. })(BABYLON || (BABYLON = {}));
  27055. var BABYLON;
  27056. (function (BABYLON) {
  27057. var Geometry = (function () {
  27058. function Geometry(id, scene, vertexData, updatable, mesh) {
  27059. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27060. this._totalVertices = 0;
  27061. this._isDisposed = false;
  27062. this.id = id;
  27063. this._engine = scene.getEngine();
  27064. this._meshes = [];
  27065. this._scene = scene;
  27066. //Init vertex buffer cache
  27067. this._vertexBuffers = {};
  27068. this._indices = [];
  27069. // vertexData
  27070. if (vertexData) {
  27071. this.setAllVerticesData(vertexData, updatable);
  27072. }
  27073. else {
  27074. this._totalVertices = 0;
  27075. this._indices = [];
  27076. }
  27077. // applyToMesh
  27078. if (mesh) {
  27079. this.applyToMesh(mesh);
  27080. mesh.computeWorldMatrix(true);
  27081. }
  27082. }
  27083. Object.defineProperty(Geometry.prototype, "extend", {
  27084. get: function () {
  27085. return this._extend;
  27086. },
  27087. enumerable: true,
  27088. configurable: true
  27089. });
  27090. Geometry.prototype.getScene = function () {
  27091. return this._scene;
  27092. };
  27093. Geometry.prototype.getEngine = function () {
  27094. return this._engine;
  27095. };
  27096. Geometry.prototype.isReady = function () {
  27097. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  27098. };
  27099. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  27100. vertexData.applyToGeometry(this, updatable);
  27101. this.notifyUpdate();
  27102. };
  27103. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  27104. if (this._vertexBuffers[kind]) {
  27105. this._vertexBuffers[kind].dispose();
  27106. }
  27107. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  27108. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27109. stride = this._vertexBuffers[kind].getStrideSize();
  27110. this._totalVertices = data.length / stride;
  27111. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  27112. var meshes = this._meshes;
  27113. var numOfMeshes = meshes.length;
  27114. for (var index = 0; index < numOfMeshes; index++) {
  27115. var mesh = meshes[index];
  27116. mesh._resetPointsArrayCache();
  27117. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27118. mesh._createGlobalSubMesh();
  27119. mesh.computeWorldMatrix(true);
  27120. }
  27121. }
  27122. this.notifyUpdate(kind);
  27123. };
  27124. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  27125. var vertexBuffer = this.getVertexBuffer(kind);
  27126. if (!vertexBuffer) {
  27127. return;
  27128. }
  27129. vertexBuffer.updateDirectly(data, offset);
  27130. this.notifyUpdate(kind);
  27131. };
  27132. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  27133. var vertexBuffer = this.getVertexBuffer(kind);
  27134. if (!vertexBuffer) {
  27135. return;
  27136. }
  27137. vertexBuffer.update(data);
  27138. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27139. var stride = vertexBuffer.getStrideSize();
  27140. this._totalVertices = data.length / stride;
  27141. if (updateExtends) {
  27142. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  27143. }
  27144. var meshes = this._meshes;
  27145. var numOfMeshes = meshes.length;
  27146. for (var index = 0; index < numOfMeshes; index++) {
  27147. var mesh = meshes[index];
  27148. mesh._resetPointsArrayCache();
  27149. if (updateExtends) {
  27150. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27151. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  27152. var subMesh = mesh.subMeshes[subIndex];
  27153. subMesh.refreshBoundingInfo();
  27154. }
  27155. }
  27156. }
  27157. }
  27158. this.notifyUpdate(kind);
  27159. };
  27160. Geometry.prototype.getTotalVertices = function () {
  27161. if (!this.isReady()) {
  27162. return 0;
  27163. }
  27164. return this._totalVertices;
  27165. };
  27166. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  27167. var vertexBuffer = this.getVertexBuffer(kind);
  27168. if (!vertexBuffer) {
  27169. return null;
  27170. }
  27171. var orig = vertexBuffer.getData();
  27172. if (!copyWhenShared || this._meshes.length === 1) {
  27173. return orig;
  27174. }
  27175. else {
  27176. var len = orig.length;
  27177. var copy = [];
  27178. for (var i = 0; i < len; i++) {
  27179. copy.push(orig[i]);
  27180. }
  27181. return copy;
  27182. }
  27183. };
  27184. Geometry.prototype.getVertexBuffer = function (kind) {
  27185. if (!this.isReady()) {
  27186. return null;
  27187. }
  27188. return this._vertexBuffers[kind];
  27189. };
  27190. Geometry.prototype.getVertexBuffers = function () {
  27191. if (!this.isReady()) {
  27192. return null;
  27193. }
  27194. return this._vertexBuffers;
  27195. };
  27196. Geometry.prototype.isVerticesDataPresent = function (kind) {
  27197. if (!this._vertexBuffers) {
  27198. if (this._delayInfo) {
  27199. return this._delayInfo.indexOf(kind) !== -1;
  27200. }
  27201. return false;
  27202. }
  27203. return this._vertexBuffers[kind] !== undefined;
  27204. };
  27205. Geometry.prototype.getVerticesDataKinds = function () {
  27206. var result = [];
  27207. var kind;
  27208. if (!this._vertexBuffers && this._delayInfo) {
  27209. for (kind in this._delayInfo) {
  27210. result.push(kind);
  27211. }
  27212. }
  27213. else {
  27214. for (kind in this._vertexBuffers) {
  27215. result.push(kind);
  27216. }
  27217. }
  27218. return result;
  27219. };
  27220. Geometry.prototype.setIndices = function (indices, totalVertices) {
  27221. if (this._indexBuffer) {
  27222. this._engine._releaseBuffer(this._indexBuffer);
  27223. }
  27224. this._indices = indices;
  27225. if (this._meshes.length !== 0 && this._indices) {
  27226. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  27227. }
  27228. if (totalVertices !== undefined) {
  27229. this._totalVertices = totalVertices;
  27230. }
  27231. var meshes = this._meshes;
  27232. var numOfMeshes = meshes.length;
  27233. for (var index = 0; index < numOfMeshes; index++) {
  27234. meshes[index]._createGlobalSubMesh();
  27235. }
  27236. this.notifyUpdate();
  27237. };
  27238. Geometry.prototype.getTotalIndices = function () {
  27239. if (!this.isReady()) {
  27240. return 0;
  27241. }
  27242. return this._indices.length;
  27243. };
  27244. Geometry.prototype.getIndices = function (copyWhenShared) {
  27245. if (!this.isReady()) {
  27246. return null;
  27247. }
  27248. var orig = this._indices;
  27249. if (!copyWhenShared || this._meshes.length === 1) {
  27250. return orig;
  27251. }
  27252. else {
  27253. var len = orig.length;
  27254. var copy = [];
  27255. for (var i = 0; i < len; i++) {
  27256. copy.push(orig[i]);
  27257. }
  27258. return copy;
  27259. }
  27260. };
  27261. Geometry.prototype.getIndexBuffer = function () {
  27262. if (!this.isReady()) {
  27263. return null;
  27264. }
  27265. return this._indexBuffer;
  27266. };
  27267. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  27268. var meshes = this._meshes;
  27269. var index = meshes.indexOf(mesh);
  27270. if (index === -1) {
  27271. return;
  27272. }
  27273. for (var kind in this._vertexBuffers) {
  27274. this._vertexBuffers[kind].dispose();
  27275. }
  27276. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  27277. this._indexBuffer = null;
  27278. }
  27279. meshes.splice(index, 1);
  27280. mesh._geometry = null;
  27281. if (meshes.length === 0 && shouldDispose) {
  27282. this.dispose();
  27283. }
  27284. };
  27285. Geometry.prototype.applyToMesh = function (mesh) {
  27286. if (mesh._geometry === this) {
  27287. return;
  27288. }
  27289. var previousGeometry = mesh._geometry;
  27290. if (previousGeometry) {
  27291. previousGeometry.releaseForMesh(mesh);
  27292. }
  27293. var meshes = this._meshes;
  27294. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  27295. mesh._geometry = this;
  27296. this._scene.pushGeometry(this);
  27297. meshes.push(mesh);
  27298. if (this.isReady()) {
  27299. this._applyToMesh(mesh);
  27300. }
  27301. else {
  27302. mesh._boundingInfo = this._boundingInfo;
  27303. }
  27304. };
  27305. Geometry.prototype._applyToMesh = function (mesh) {
  27306. var numOfMeshes = this._meshes.length;
  27307. // vertexBuffers
  27308. for (var kind in this._vertexBuffers) {
  27309. if (numOfMeshes === 1) {
  27310. this._vertexBuffers[kind].create();
  27311. }
  27312. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  27313. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27314. mesh._resetPointsArrayCache();
  27315. if (!this._extend) {
  27316. this._extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  27317. }
  27318. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27319. mesh._createGlobalSubMesh();
  27320. //bounding info was just created again, world matrix should be applied again.
  27321. mesh._updateBoundingInfo();
  27322. }
  27323. }
  27324. // indexBuffer
  27325. if (numOfMeshes === 1 && this._indices) {
  27326. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  27327. }
  27328. if (this._indexBuffer) {
  27329. this._indexBuffer.references = numOfMeshes;
  27330. }
  27331. };
  27332. Geometry.prototype.notifyUpdate = function (kind) {
  27333. if (this.onGeometryUpdated) {
  27334. this.onGeometryUpdated(this, kind);
  27335. }
  27336. };
  27337. Geometry.prototype.load = function (scene, onLoaded) {
  27338. var _this = this;
  27339. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27340. return;
  27341. }
  27342. if (this.isReady()) {
  27343. if (onLoaded) {
  27344. onLoaded();
  27345. }
  27346. return;
  27347. }
  27348. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  27349. scene._addPendingData(this);
  27350. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  27351. _this._delayLoadingFunction(JSON.parse(data), _this);
  27352. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  27353. _this._delayInfo = [];
  27354. scene._removePendingData(_this);
  27355. var meshes = _this._meshes;
  27356. var numOfMeshes = meshes.length;
  27357. for (var index = 0; index < numOfMeshes; index++) {
  27358. _this._applyToMesh(meshes[index]);
  27359. }
  27360. if (onLoaded) {
  27361. onLoaded();
  27362. }
  27363. }, function () { }, scene.database);
  27364. };
  27365. Geometry.prototype.isDisposed = function () {
  27366. return this._isDisposed;
  27367. };
  27368. Geometry.prototype.dispose = function () {
  27369. var meshes = this._meshes;
  27370. var numOfMeshes = meshes.length;
  27371. var index;
  27372. for (index = 0; index < numOfMeshes; index++) {
  27373. this.releaseForMesh(meshes[index]);
  27374. }
  27375. this._meshes = [];
  27376. for (var kind in this._vertexBuffers) {
  27377. this._vertexBuffers[kind].dispose();
  27378. }
  27379. this._vertexBuffers = [];
  27380. this._totalVertices = 0;
  27381. if (this._indexBuffer) {
  27382. this._engine._releaseBuffer(this._indexBuffer);
  27383. }
  27384. this._indexBuffer = null;
  27385. this._indices = [];
  27386. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27387. this.delayLoadingFile = null;
  27388. this._delayLoadingFunction = null;
  27389. this._delayInfo = [];
  27390. this._boundingInfo = null;
  27391. this._scene.removeGeometry(this);
  27392. this._isDisposed = true;
  27393. };
  27394. Geometry.prototype.copy = function (id) {
  27395. var vertexData = new BABYLON.VertexData();
  27396. vertexData.indices = [];
  27397. var indices = this.getIndices();
  27398. for (var index = 0; index < indices.length; index++) {
  27399. vertexData.indices.push(indices[index]);
  27400. }
  27401. var updatable = false;
  27402. var stopChecking = false;
  27403. var kind;
  27404. for (kind in this._vertexBuffers) {
  27405. // using slice() to make a copy of the array and not just reference it
  27406. var data = this.getVerticesData(kind);
  27407. if (data instanceof Float32Array) {
  27408. vertexData.set(new Float32Array(data), kind);
  27409. }
  27410. else {
  27411. vertexData.set(data.slice(0), kind);
  27412. }
  27413. if (!stopChecking) {
  27414. updatable = this.getVertexBuffer(kind).isUpdatable();
  27415. stopChecking = !updatable;
  27416. }
  27417. }
  27418. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  27419. geometry.delayLoadState = this.delayLoadState;
  27420. geometry.delayLoadingFile = this.delayLoadingFile;
  27421. geometry._delayLoadingFunction = this._delayLoadingFunction;
  27422. for (kind in this._delayInfo) {
  27423. geometry._delayInfo = geometry._delayInfo || [];
  27424. geometry._delayInfo.push(kind);
  27425. }
  27426. // Bounding info
  27427. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27428. return geometry;
  27429. };
  27430. Geometry.prototype.serialize = function () {
  27431. var serializationObject = {};
  27432. serializationObject.id = this.id;
  27433. if (BABYLON.Tags.HasTags(this)) {
  27434. serializationObject.tags = BABYLON.Tags.GetTags(this);
  27435. }
  27436. return serializationObject;
  27437. };
  27438. Geometry.prototype.serializeVerticeData = function () {
  27439. var serializationObject = this.serialize();
  27440. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  27441. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27442. }
  27443. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  27444. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27445. }
  27446. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27447. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  27448. }
  27449. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  27450. serializationObject.uvs2 = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  27451. }
  27452. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  27453. serializationObject.uvs3 = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  27454. }
  27455. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  27456. serializationObject.uvs4 = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  27457. }
  27458. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  27459. serializationObject.uvs5 = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  27460. }
  27461. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  27462. serializationObject.uvs6 = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  27463. }
  27464. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  27465. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  27466. }
  27467. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  27468. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  27469. serializationObject.matricesIndices._isExpanded = true;
  27470. }
  27471. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  27472. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  27473. }
  27474. serializationObject.indices = this.getIndices();
  27475. return serializationObject;
  27476. };
  27477. // Statics
  27478. Geometry.ExtractFromMesh = function (mesh, id) {
  27479. var geometry = mesh._geometry;
  27480. if (!geometry) {
  27481. return null;
  27482. }
  27483. return geometry.copy(id);
  27484. };
  27485. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  27486. // be aware Math.random() could cause collisions
  27487. Geometry.RandomId = function () {
  27488. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  27489. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  27490. return v.toString(16);
  27491. });
  27492. };
  27493. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  27494. var scene = mesh.getScene();
  27495. // Geometry
  27496. var geometryId = parsedGeometry.geometryId;
  27497. if (geometryId) {
  27498. var geometry = scene.getGeometryByID(geometryId);
  27499. if (geometry) {
  27500. geometry.applyToMesh(mesh);
  27501. }
  27502. }
  27503. else if (parsedGeometry instanceof ArrayBuffer) {
  27504. var binaryInfo = mesh._binaryInfo;
  27505. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  27506. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  27507. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  27508. }
  27509. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  27510. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  27511. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  27512. }
  27513. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  27514. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  27515. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  27516. }
  27517. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  27518. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  27519. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  27520. }
  27521. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  27522. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  27523. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  27524. }
  27525. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  27526. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  27527. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  27528. }
  27529. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  27530. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  27531. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  27532. }
  27533. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  27534. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  27535. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  27536. }
  27537. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  27538. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  27539. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  27540. }
  27541. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  27542. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  27543. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  27544. }
  27545. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  27546. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  27547. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  27548. }
  27549. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  27550. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  27551. mesh.setIndices(indicesData);
  27552. }
  27553. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  27554. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  27555. mesh.subMeshes = [];
  27556. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  27557. var materialIndex = subMeshesData[(i * 5) + 0];
  27558. var verticesStart = subMeshesData[(i * 5) + 1];
  27559. var verticesCount = subMeshesData[(i * 5) + 2];
  27560. var indexStart = subMeshesData[(i * 5) + 3];
  27561. var indexCount = subMeshesData[(i * 5) + 4];
  27562. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  27563. }
  27564. }
  27565. }
  27566. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  27567. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  27568. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  27569. if (parsedGeometry.uvs) {
  27570. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  27571. }
  27572. if (parsedGeometry.uvs2) {
  27573. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  27574. }
  27575. if (parsedGeometry.uvs3) {
  27576. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  27577. }
  27578. if (parsedGeometry.uvs4) {
  27579. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  27580. }
  27581. if (parsedGeometry.uvs5) {
  27582. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  27583. }
  27584. if (parsedGeometry.uvs6) {
  27585. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  27586. }
  27587. if (parsedGeometry.colors) {
  27588. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  27589. }
  27590. if (parsedGeometry.matricesIndices) {
  27591. if (!parsedGeometry.matricesIndices._isExpanded) {
  27592. var floatIndices = [];
  27593. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  27594. var matricesIndex = parsedGeometry.matricesIndices[i];
  27595. floatIndices.push(matricesIndex & 0x000000FF);
  27596. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  27597. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  27598. floatIndices.push(matricesIndex >> 24);
  27599. }
  27600. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  27601. }
  27602. else {
  27603. delete parsedGeometry.matricesIndices._isExpanded;
  27604. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  27605. }
  27606. }
  27607. if (parsedGeometry.matricesIndicesExtra) {
  27608. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  27609. var floatIndices = [];
  27610. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  27611. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  27612. floatIndices.push(matricesIndex & 0x000000FF);
  27613. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  27614. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  27615. floatIndices.push(matricesIndex >> 24);
  27616. }
  27617. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, false);
  27618. }
  27619. else {
  27620. delete parsedGeometry.matricesIndices._isExpanded;
  27621. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, false);
  27622. }
  27623. }
  27624. if (parsedGeometry.matricesWeights) {
  27625. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  27626. }
  27627. if (parsedGeometry.matricesWeightsExtra) {
  27628. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, false);
  27629. }
  27630. mesh.setIndices(parsedGeometry.indices);
  27631. }
  27632. // SubMeshes
  27633. if (parsedGeometry.subMeshes) {
  27634. mesh.subMeshes = [];
  27635. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  27636. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  27637. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  27638. }
  27639. }
  27640. // Flat shading
  27641. if (mesh._shouldGenerateFlatShading) {
  27642. mesh.convertToFlatShadedMesh();
  27643. delete mesh._shouldGenerateFlatShading;
  27644. }
  27645. // Update
  27646. mesh.computeWorldMatrix(true);
  27647. // Octree
  27648. if (scene['_selectionOctree']) {
  27649. scene['_selectionOctree'].addMesh(mesh);
  27650. }
  27651. };
  27652. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  27653. if (scene.getGeometryByID(parsedVertexData.id)) {
  27654. return null; // null since geometry could be something else than a box...
  27655. }
  27656. var geometry = new Geometry(parsedVertexData.id, scene);
  27657. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  27658. if (parsedVertexData.delayLoadingFile) {
  27659. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27660. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  27661. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  27662. geometry._delayInfo = [];
  27663. if (parsedVertexData.hasUVs) {
  27664. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  27665. }
  27666. if (parsedVertexData.hasUVs2) {
  27667. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  27668. }
  27669. if (parsedVertexData.hasUVs3) {
  27670. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  27671. }
  27672. if (parsedVertexData.hasUVs4) {
  27673. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  27674. }
  27675. if (parsedVertexData.hasUVs5) {
  27676. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  27677. }
  27678. if (parsedVertexData.hasUVs6) {
  27679. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  27680. }
  27681. if (parsedVertexData.hasColors) {
  27682. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  27683. }
  27684. if (parsedVertexData.hasMatricesIndices) {
  27685. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  27686. }
  27687. if (parsedVertexData.hasMatricesWeights) {
  27688. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  27689. }
  27690. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  27691. }
  27692. else {
  27693. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  27694. }
  27695. scene.pushGeometry(geometry, true);
  27696. return geometry;
  27697. };
  27698. return Geometry;
  27699. })();
  27700. BABYLON.Geometry = Geometry;
  27701. /////// Primitives //////////////////////////////////////////////
  27702. var Geometry;
  27703. (function (Geometry) {
  27704. var Primitives;
  27705. (function (Primitives) {
  27706. /// Abstract class
  27707. var _Primitive = (function (_super) {
  27708. __extends(_Primitive, _super);
  27709. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  27710. this._beingRegenerated = true;
  27711. this._canBeRegenerated = canBeRegenerated;
  27712. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  27713. this._beingRegenerated = false;
  27714. }
  27715. _Primitive.prototype.canBeRegenerated = function () {
  27716. return this._canBeRegenerated;
  27717. };
  27718. _Primitive.prototype.regenerate = function () {
  27719. if (!this._canBeRegenerated) {
  27720. return;
  27721. }
  27722. this._beingRegenerated = true;
  27723. this.setAllVerticesData(this._regenerateVertexData(), false);
  27724. this._beingRegenerated = false;
  27725. };
  27726. _Primitive.prototype.asNewGeometry = function (id) {
  27727. return _super.prototype.copy.call(this, id);
  27728. };
  27729. // overrides
  27730. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  27731. if (!this._beingRegenerated) {
  27732. return;
  27733. }
  27734. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  27735. };
  27736. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  27737. if (!this._beingRegenerated) {
  27738. return;
  27739. }
  27740. _super.prototype.setVerticesData.call(this, kind, data, false);
  27741. };
  27742. // to override
  27743. // protected
  27744. _Primitive.prototype._regenerateVertexData = function () {
  27745. throw new Error("Abstract method");
  27746. };
  27747. _Primitive.prototype.copy = function (id) {
  27748. throw new Error("Must be overriden in sub-classes.");
  27749. };
  27750. _Primitive.prototype.serialize = function () {
  27751. var serializationObject = _super.prototype.serialize.call(this);
  27752. serializationObject.canBeRegenerated = this.canBeRegenerated();
  27753. return serializationObject;
  27754. };
  27755. return _Primitive;
  27756. })(Geometry);
  27757. Primitives._Primitive = _Primitive;
  27758. var Ribbon = (function (_super) {
  27759. __extends(Ribbon, _super);
  27760. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  27761. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27762. this.pathArray = pathArray;
  27763. this.closeArray = closeArray;
  27764. this.closePath = closePath;
  27765. this.offset = offset;
  27766. this.side = side;
  27767. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27768. }
  27769. Ribbon.prototype._regenerateVertexData = function () {
  27770. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  27771. };
  27772. Ribbon.prototype.copy = function (id) {
  27773. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  27774. };
  27775. return Ribbon;
  27776. })(_Primitive);
  27777. Primitives.Ribbon = Ribbon;
  27778. var Box = (function (_super) {
  27779. __extends(Box, _super);
  27780. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  27781. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27782. this.size = size;
  27783. this.side = side;
  27784. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27785. }
  27786. Box.prototype._regenerateVertexData = function () {
  27787. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  27788. };
  27789. Box.prototype.copy = function (id) {
  27790. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  27791. };
  27792. Box.prototype.serialize = function () {
  27793. var serializationObject = _super.prototype.serialize.call(this);
  27794. serializationObject.size = this.size;
  27795. return serializationObject;
  27796. };
  27797. Box.Parse = function (parsedBox, scene) {
  27798. if (scene.getGeometryByID(parsedBox.id)) {
  27799. return null; // null since geometry could be something else than a box...
  27800. }
  27801. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  27802. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  27803. scene.pushGeometry(box, true);
  27804. return box;
  27805. };
  27806. return Box;
  27807. })(_Primitive);
  27808. Primitives.Box = Box;
  27809. var Sphere = (function (_super) {
  27810. __extends(Sphere, _super);
  27811. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  27812. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27813. this.segments = segments;
  27814. this.diameter = diameter;
  27815. this.side = side;
  27816. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27817. }
  27818. Sphere.prototype._regenerateVertexData = function () {
  27819. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  27820. };
  27821. Sphere.prototype.copy = function (id) {
  27822. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  27823. };
  27824. Sphere.prototype.serialize = function () {
  27825. var serializationObject = _super.prototype.serialize.call(this);
  27826. serializationObject.segments = this.segments;
  27827. serializationObject.diameter = this.diameter;
  27828. return serializationObject;
  27829. };
  27830. Sphere.Parse = function (parsedSphere, scene) {
  27831. if (scene.getGeometryByID(parsedSphere.id)) {
  27832. return null; // null since geometry could be something else than a sphere...
  27833. }
  27834. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  27835. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  27836. scene.pushGeometry(sphere, true);
  27837. return sphere;
  27838. };
  27839. return Sphere;
  27840. })(_Primitive);
  27841. Primitives.Sphere = Sphere;
  27842. var Disc = (function (_super) {
  27843. __extends(Disc, _super);
  27844. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  27845. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27846. this.radius = radius;
  27847. this.tessellation = tessellation;
  27848. this.side = side;
  27849. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27850. }
  27851. Disc.prototype._regenerateVertexData = function () {
  27852. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  27853. };
  27854. Disc.prototype.copy = function (id) {
  27855. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  27856. };
  27857. return Disc;
  27858. })(_Primitive);
  27859. Primitives.Disc = Disc;
  27860. var Cylinder = (function (_super) {
  27861. __extends(Cylinder, _super);
  27862. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  27863. if (subdivisions === void 0) { subdivisions = 1; }
  27864. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27865. this.height = height;
  27866. this.diameterTop = diameterTop;
  27867. this.diameterBottom = diameterBottom;
  27868. this.tessellation = tessellation;
  27869. this.subdivisions = subdivisions;
  27870. this.side = side;
  27871. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27872. }
  27873. Cylinder.prototype._regenerateVertexData = function () {
  27874. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  27875. };
  27876. Cylinder.prototype.copy = function (id) {
  27877. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  27878. };
  27879. Cylinder.prototype.serialize = function () {
  27880. var serializationObject = _super.prototype.serialize.call(this);
  27881. serializationObject.height = this.height;
  27882. serializationObject.diameterTop = this.diameterTop;
  27883. serializationObject.diameterBottom = this.diameterBottom;
  27884. serializationObject.tessellation = this.tessellation;
  27885. return serializationObject;
  27886. };
  27887. Cylinder.Parse = function (parsedCylinder, scene) {
  27888. if (scene.getGeometryByID(parsedCylinder.id)) {
  27889. return null; // null since geometry could be something else than a cylinder...
  27890. }
  27891. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  27892. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  27893. scene.pushGeometry(cylinder, true);
  27894. return cylinder;
  27895. };
  27896. return Cylinder;
  27897. })(_Primitive);
  27898. Primitives.Cylinder = Cylinder;
  27899. var Torus = (function (_super) {
  27900. __extends(Torus, _super);
  27901. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  27902. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27903. this.diameter = diameter;
  27904. this.thickness = thickness;
  27905. this.tessellation = tessellation;
  27906. this.side = side;
  27907. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27908. }
  27909. Torus.prototype._regenerateVertexData = function () {
  27910. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  27911. };
  27912. Torus.prototype.copy = function (id) {
  27913. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  27914. };
  27915. Torus.prototype.serialize = function () {
  27916. var serializationObject = _super.prototype.serialize.call(this);
  27917. serializationObject.diameter = this.diameter;
  27918. serializationObject.thickness = this.thickness;
  27919. serializationObject.tessellation = this.tessellation;
  27920. return serializationObject;
  27921. };
  27922. Torus.Parse = function (parsedTorus, scene) {
  27923. if (scene.getGeometryByID(parsedTorus.id)) {
  27924. return null; // null since geometry could be something else than a torus...
  27925. }
  27926. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  27927. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  27928. scene.pushGeometry(torus, true);
  27929. return torus;
  27930. };
  27931. return Torus;
  27932. })(_Primitive);
  27933. Primitives.Torus = Torus;
  27934. var Ground = (function (_super) {
  27935. __extends(Ground, _super);
  27936. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  27937. this.width = width;
  27938. this.height = height;
  27939. this.subdivisions = subdivisions;
  27940. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27941. }
  27942. Ground.prototype._regenerateVertexData = function () {
  27943. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  27944. };
  27945. Ground.prototype.copy = function (id) {
  27946. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  27947. };
  27948. Ground.prototype.serialize = function () {
  27949. var serializationObject = _super.prototype.serialize.call(this);
  27950. serializationObject.width = this.width;
  27951. serializationObject.height = this.height;
  27952. serializationObject.subdivisions = this.subdivisions;
  27953. return serializationObject;
  27954. };
  27955. Ground.Parse = function (parsedGround, scene) {
  27956. if (scene.getGeometryByID(parsedGround.id)) {
  27957. return null; // null since geometry could be something else than a ground...
  27958. }
  27959. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  27960. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  27961. scene.pushGeometry(ground, true);
  27962. return ground;
  27963. };
  27964. return Ground;
  27965. })(_Primitive);
  27966. Primitives.Ground = Ground;
  27967. var TiledGround = (function (_super) {
  27968. __extends(TiledGround, _super);
  27969. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  27970. this.xmin = xmin;
  27971. this.zmin = zmin;
  27972. this.xmax = xmax;
  27973. this.zmax = zmax;
  27974. this.subdivisions = subdivisions;
  27975. this.precision = precision;
  27976. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27977. }
  27978. TiledGround.prototype._regenerateVertexData = function () {
  27979. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  27980. };
  27981. TiledGround.prototype.copy = function (id) {
  27982. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  27983. };
  27984. return TiledGround;
  27985. })(_Primitive);
  27986. Primitives.TiledGround = TiledGround;
  27987. var Plane = (function (_super) {
  27988. __extends(Plane, _super);
  27989. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  27990. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27991. this.size = size;
  27992. this.side = side;
  27993. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27994. }
  27995. Plane.prototype._regenerateVertexData = function () {
  27996. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  27997. };
  27998. Plane.prototype.copy = function (id) {
  27999. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  28000. };
  28001. Plane.prototype.serialize = function () {
  28002. var serializationObject = _super.prototype.serialize.call(this);
  28003. serializationObject.size = this.size;
  28004. return serializationObject;
  28005. };
  28006. Plane.Parse = function (parsedPlane, scene) {
  28007. if (scene.getGeometryByID(parsedPlane.id)) {
  28008. return null; // null since geometry could be something else than a ground...
  28009. }
  28010. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  28011. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  28012. scene.pushGeometry(plane, true);
  28013. return plane;
  28014. };
  28015. return Plane;
  28016. })(_Primitive);
  28017. Primitives.Plane = Plane;
  28018. var TorusKnot = (function (_super) {
  28019. __extends(TorusKnot, _super);
  28020. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  28021. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28022. this.radius = radius;
  28023. this.tube = tube;
  28024. this.radialSegments = radialSegments;
  28025. this.tubularSegments = tubularSegments;
  28026. this.p = p;
  28027. this.q = q;
  28028. this.side = side;
  28029. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  28030. }
  28031. TorusKnot.prototype._regenerateVertexData = function () {
  28032. 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 });
  28033. };
  28034. TorusKnot.prototype.copy = function (id) {
  28035. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  28036. };
  28037. TorusKnot.prototype.serialize = function () {
  28038. var serializationObject = _super.prototype.serialize.call(this);
  28039. serializationObject.radius = this.radius;
  28040. serializationObject.tube = this.tube;
  28041. serializationObject.radialSegments = this.radialSegments;
  28042. serializationObject.tubularSegments = this.tubularSegments;
  28043. serializationObject.p = this.p;
  28044. serializationObject.q = this.q;
  28045. return serializationObject;
  28046. };
  28047. ;
  28048. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  28049. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  28050. return null; // null since geometry could be something else than a ground...
  28051. }
  28052. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  28053. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  28054. scene.pushGeometry(torusKnot, true);
  28055. return torusKnot;
  28056. };
  28057. return TorusKnot;
  28058. })(_Primitive);
  28059. Primitives.TorusKnot = TorusKnot;
  28060. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  28061. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  28062. })(BABYLON || (BABYLON = {}));
  28063. var BABYLON;
  28064. (function (BABYLON) {
  28065. var GroundMesh = (function (_super) {
  28066. __extends(GroundMesh, _super);
  28067. function GroundMesh(name, scene) {
  28068. _super.call(this, name, scene);
  28069. this.generateOctree = false;
  28070. this._worldInverse = new BABYLON.Matrix();
  28071. }
  28072. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  28073. get: function () {
  28074. return this._subdivisions;
  28075. },
  28076. enumerable: true,
  28077. configurable: true
  28078. });
  28079. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  28080. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  28081. this._subdivisions = chunksCount;
  28082. this.subdivide(this._subdivisions);
  28083. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  28084. };
  28085. /**
  28086. * Returns a height (y) value in the Worl system :
  28087. * the ground altitude at the coordinates (x, z) expressed in the World system.
  28088. * Returns the ground y position if (x, z) are outside the ground surface.
  28089. * Not pertinent if the ground is rotated.
  28090. */
  28091. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  28092. // express x and y in the ground local system
  28093. x -= this.position.x;
  28094. z -= this.position.z;
  28095. x /= this.scaling.x;
  28096. z /= this.scaling.z;
  28097. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  28098. return this.position.y;
  28099. }
  28100. if (!this._heightQuads || this._heightQuads.length == 0) {
  28101. this._computeHeightQuads();
  28102. }
  28103. var facet = this._getFacetAt(x, z);
  28104. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  28105. // return y in the World system
  28106. return y * this.scaling.y + this.position.y;
  28107. };
  28108. /**
  28109. * Returns a normalized vector (Vector3) orthogonal to the ground
  28110. * at the ground coordinates (x, z) expressed in the World system.
  28111. * Returns Vector3(0, 1, 0) if (x, z) are outside the ground surface.
  28112. * Not pertinent if the ground is rotated.
  28113. */
  28114. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  28115. var normal = new BABYLON.Vector3(0, 1, 0);
  28116. this.getNormalAtCoordinatesToRef(x, z, normal);
  28117. return normal;
  28118. };
  28119. /**
  28120. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  28121. * at the ground coordinates (x, z) expressed in the World system.
  28122. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  28123. * Not pertinent if the ground is rotated.
  28124. */
  28125. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  28126. // express x and y in the ground local system
  28127. x -= this.position.x;
  28128. z -= this.position.z;
  28129. x /= this.scaling.x;
  28130. z /= this.scaling.z;
  28131. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  28132. return;
  28133. }
  28134. if (!this._heightQuads || this._heightQuads.length == 0) {
  28135. this._computeHeightQuads();
  28136. }
  28137. var facet = this._getFacetAt(x, z);
  28138. ref.x = facet.x;
  28139. ref.y = facet.y;
  28140. ref.z = facet.z;
  28141. };
  28142. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  28143. GroundMesh.prototype._getFacetAt = function (x, z) {
  28144. // retrieve col and row from x, z coordinates in the ground local system
  28145. var col = Math.floor((x + this._maxX) * this._subdivisions / this._width);
  28146. var row = Math.floor(-(z + this._maxZ) * this._subdivisions / this._height + this._subdivisions);
  28147. var quad = this._heightQuads[row * this._subdivisions + col];
  28148. var facet;
  28149. if (z < quad.slope.x * x + quad.slope.y) {
  28150. facet = quad.facet1;
  28151. }
  28152. else {
  28153. facet = quad.facet2;
  28154. }
  28155. return facet;
  28156. };
  28157. // Populates the heightMap array with "facet" elements :
  28158. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  28159. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  28160. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  28161. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  28162. GroundMesh.prototype._computeHeightQuads = function () {
  28163. this._heightQuads = new Array();
  28164. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28165. var v1 = BABYLON.Vector3.Zero();
  28166. var v2 = BABYLON.Vector3.Zero();
  28167. var v3 = BABYLON.Vector3.Zero();
  28168. var v4 = BABYLON.Vector3.Zero();
  28169. var v1v2 = BABYLON.Vector3.Zero();
  28170. var v1v3 = BABYLON.Vector3.Zero();
  28171. var v1v4 = BABYLON.Vector3.Zero();
  28172. var norm1 = BABYLON.Vector3.Zero();
  28173. var norm2 = BABYLON.Vector3.Zero();
  28174. var i = 0;
  28175. var j = 0;
  28176. var k = 0;
  28177. var cd = 0; // 2D slope coefficient : z = cd * x + h
  28178. var h = 0;
  28179. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  28180. var d2 = 0;
  28181. for (var row = 0; row < this._subdivisions; row++) {
  28182. for (var col = 0; col < this._subdivisions; col++) {
  28183. i = col * 3;
  28184. j = row * (this._subdivisions + 1) * 3;
  28185. k = (row + 1) * (this._subdivisions + 1) * 3;
  28186. v1.x = positions[j + i];
  28187. v1.y = positions[j + i + 1];
  28188. v1.z = positions[j + i + 2];
  28189. v2.x = positions[j + i + 3];
  28190. v2.y = positions[j + i + 4];
  28191. v2.z = positions[j + i + 5];
  28192. v3.x = positions[k + i];
  28193. v3.y = positions[k + i + 1];
  28194. v3.z = positions[k + i + 2];
  28195. v4.x = positions[k + i + 3];
  28196. v4.y = positions[k + i + 4];
  28197. v4.z = positions[k + i + 5];
  28198. // 2D slope V1V4
  28199. cd = (v4.z - v1.z) / (v4.x - v1.x);
  28200. h = v1.z - cd * v1.x; // v1 belongs to the slope
  28201. var slope = new BABYLON.Vector2(cd, h);
  28202. // facet equations :
  28203. // we compute each facet normal vector
  28204. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  28205. // we compute the value d by applying the equation to v1 which belongs to the plane
  28206. // then we store the facet equation in a Vector4
  28207. v2.subtractToRef(v1, v1v2);
  28208. v3.subtractToRef(v1, v1v3);
  28209. v4.subtractToRef(v1, v1v4);
  28210. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1);
  28211. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  28212. norm1.normalize();
  28213. norm2.normalize();
  28214. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  28215. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  28216. var facet1 = new BABYLON.Vector4(norm1.x, norm1.y, norm1.z, d1);
  28217. var facet2 = new BABYLON.Vector4(norm2.x, norm2.y, norm2.z, d2);
  28218. var quad = { slope: slope, facet1: facet1, facet2: facet2 };
  28219. this._heightQuads.push(quad);
  28220. }
  28221. }
  28222. };
  28223. return GroundMesh;
  28224. })(BABYLON.Mesh);
  28225. BABYLON.GroundMesh = GroundMesh;
  28226. })(BABYLON || (BABYLON = {}));
  28227. var BABYLON;
  28228. (function (BABYLON) {
  28229. var LinesMesh = (function (_super) {
  28230. __extends(LinesMesh, _super);
  28231. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  28232. if (parent === void 0) { parent = null; }
  28233. _super.call(this, name, scene, parent, source, doNotCloneChildren);
  28234. this.color = new BABYLON.Color3(1, 1, 1);
  28235. this.alpha = 1;
  28236. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  28237. attributes: ["position"],
  28238. uniforms: ["worldViewProjection", "color"],
  28239. needAlphaBlending: true
  28240. });
  28241. }
  28242. Object.defineProperty(LinesMesh.prototype, "material", {
  28243. get: function () {
  28244. return this._colorShader;
  28245. },
  28246. enumerable: true,
  28247. configurable: true
  28248. });
  28249. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  28250. get: function () {
  28251. return false;
  28252. },
  28253. enumerable: true,
  28254. configurable: true
  28255. });
  28256. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  28257. get: function () {
  28258. return false;
  28259. },
  28260. enumerable: true,
  28261. configurable: true
  28262. });
  28263. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  28264. var engine = this.getScene().getEngine();
  28265. var indexToBind = this._geometry.getIndexBuffer();
  28266. // VBOs
  28267. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  28268. // Color
  28269. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  28270. };
  28271. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  28272. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28273. return;
  28274. }
  28275. var engine = this.getScene().getEngine();
  28276. // Draw order
  28277. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  28278. };
  28279. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  28280. return null;
  28281. };
  28282. LinesMesh.prototype.dispose = function (doNotRecurse) {
  28283. this._colorShader.dispose();
  28284. _super.prototype.dispose.call(this, doNotRecurse);
  28285. };
  28286. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  28287. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  28288. };
  28289. return LinesMesh;
  28290. })(BABYLON.Mesh);
  28291. BABYLON.LinesMesh = LinesMesh;
  28292. })(BABYLON || (BABYLON = {}));
  28293. var BABYLON;
  28294. (function (BABYLON) {
  28295. var DebugLayer = (function () {
  28296. function DebugLayer(scene) {
  28297. var _this = this;
  28298. this._transformationMatrix = BABYLON.Matrix.Identity();
  28299. this._enabled = false;
  28300. this._labelsEnabled = false;
  28301. this._displayStatistics = true;
  28302. this._displayTree = false;
  28303. this._displayLogs = false;
  28304. this._identityMatrix = BABYLON.Matrix.Identity();
  28305. this.axisRatio = 0.02;
  28306. this.accentColor = "orange";
  28307. this._scene = scene;
  28308. this._syncPositions = function () {
  28309. var engine = _this._scene.getEngine();
  28310. var canvasRect = engine.getRenderingCanvasClientRect();
  28311. if (_this._showUI) {
  28312. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  28313. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  28314. _this._statsDiv.style.width = "400px";
  28315. _this._statsDiv.style.height = "auto";
  28316. _this._statsSubsetDiv.style.maxHeight = "240px";
  28317. _this._optionsDiv.style.left = "0px";
  28318. _this._optionsDiv.style.top = "10px";
  28319. _this._optionsDiv.style.width = "200px";
  28320. _this._optionsDiv.style.height = "auto";
  28321. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  28322. _this._logDiv.style.left = "0px";
  28323. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  28324. _this._logDiv.style.width = "600px";
  28325. _this._logDiv.style.height = "160px";
  28326. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  28327. _this._treeDiv.style.top = "10px";
  28328. _this._treeDiv.style.width = "300px";
  28329. _this._treeDiv.style.height = "auto";
  28330. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  28331. }
  28332. _this._globalDiv.style.left = canvasRect.left + "px";
  28333. _this._globalDiv.style.top = canvasRect.top + "px";
  28334. _this._drawingCanvas.style.left = "0px";
  28335. _this._drawingCanvas.style.top = "0px";
  28336. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  28337. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  28338. var devicePixelRatio = window.devicePixelRatio || 1;
  28339. var context = _this._drawingContext;
  28340. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  28341. context.mozBackingStorePixelRatio ||
  28342. context.msBackingStorePixelRatio ||
  28343. context.oBackingStorePixelRatio ||
  28344. context.backingStorePixelRatio || 1;
  28345. _this._ratio = devicePixelRatio / backingStoreRatio;
  28346. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  28347. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  28348. };
  28349. this._onCanvasClick = function (evt) {
  28350. _this._clickPosition = {
  28351. x: evt.clientX * _this._ratio,
  28352. y: evt.clientY * _this._ratio
  28353. };
  28354. };
  28355. this._syncUI = function () {
  28356. if (_this._showUI) {
  28357. if (_this._displayStatistics) {
  28358. _this._displayStats();
  28359. _this._statsDiv.style.display = "";
  28360. }
  28361. else {
  28362. _this._statsDiv.style.display = "none";
  28363. }
  28364. if (_this._displayLogs) {
  28365. _this._logDiv.style.display = "";
  28366. }
  28367. else {
  28368. _this._logDiv.style.display = "none";
  28369. }
  28370. if (_this._displayTree) {
  28371. _this._treeDiv.style.display = "";
  28372. if (_this._needToRefreshMeshesTree) {
  28373. _this._needToRefreshMeshesTree = false;
  28374. _this._refreshMeshesTreeContent();
  28375. }
  28376. }
  28377. else {
  28378. _this._treeDiv.style.display = "none";
  28379. }
  28380. }
  28381. };
  28382. this._syncData = function () {
  28383. if (_this._labelsEnabled || !_this._showUI) {
  28384. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  28385. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  28386. var engine = _this._scene.getEngine();
  28387. var viewport = _this._camera.viewport;
  28388. var globalViewport = viewport.toGlobal(engine);
  28389. // Meshes
  28390. var meshes = _this._camera.getActiveMeshes();
  28391. var index;
  28392. var projectedPosition;
  28393. for (index = 0; index < meshes.length; index++) {
  28394. var mesh = meshes.data[index];
  28395. var position = mesh.getBoundingInfo().boundingSphere.center;
  28396. projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  28397. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  28398. _this._renderAxis(projectedPosition, mesh, globalViewport);
  28399. }
  28400. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  28401. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  28402. }
  28403. }
  28404. // Cameras
  28405. var cameras = _this._scene.cameras;
  28406. for (index = 0; index < cameras.length; index++) {
  28407. var camera = cameras[index];
  28408. if (camera === _this._camera) {
  28409. continue;
  28410. }
  28411. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  28412. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  28413. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  28414. _this._camera.detachControl(engine.getRenderingCanvas());
  28415. _this._camera = camera;
  28416. _this._camera.attachControl(engine.getRenderingCanvas());
  28417. }, function () { return "purple"; });
  28418. }
  28419. }
  28420. // Lights
  28421. var lights = _this._scene.lights;
  28422. for (index = 0; index < lights.length; index++) {
  28423. var light = lights[index];
  28424. if (light.position) {
  28425. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  28426. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  28427. _this._renderLabel(light.name, projectedPosition, -20, function () {
  28428. light.setEnabled(!light.isEnabled());
  28429. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  28430. }
  28431. }
  28432. }
  28433. }
  28434. _this._clickPosition = undefined;
  28435. };
  28436. }
  28437. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  28438. while (this._treeSubsetDiv.hasChildNodes()) {
  28439. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  28440. }
  28441. // Add meshes
  28442. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  28443. sortedArray.sort(function (a, b) {
  28444. if (a.name === b.name) {
  28445. return 0;
  28446. }
  28447. return (a.name > b.name) ? 1 : -1;
  28448. });
  28449. for (var index = 0; index < sortedArray.length; index++) {
  28450. var mesh = sortedArray[index];
  28451. if (!mesh.isEnabled()) {
  28452. continue;
  28453. }
  28454. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  28455. m.isVisible = element.checked;
  28456. }, mesh);
  28457. }
  28458. };
  28459. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  28460. this._drawingContext.beginPath();
  28461. this._drawingContext.moveTo(zero.x, zero.y);
  28462. this._drawingContext.lineTo(unit.x, unit.y);
  28463. this._drawingContext.strokeStyle = color;
  28464. this._drawingContext.lineWidth = 4;
  28465. this._drawingContext.stroke();
  28466. this._drawingContext.font = "normal 14px Segoe UI";
  28467. this._drawingContext.fillStyle = color;
  28468. this._drawingContext.fillText(label, unitText.x, unitText.y);
  28469. };
  28470. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  28471. var position = mesh.getBoundingInfo().boundingSphere.center;
  28472. var worldMatrix = mesh.getWorldMatrix();
  28473. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  28474. var unit = (unprojectedVector.subtract(position)).length();
  28475. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  28476. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  28477. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  28478. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  28479. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  28480. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  28481. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  28482. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  28483. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  28484. };
  28485. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  28486. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  28487. this._drawingContext.font = "normal 12px Segoe UI";
  28488. var textMetrics = this._drawingContext.measureText(text);
  28489. var centerX = projectedPosition.x - textMetrics.width / 2;
  28490. var centerY = projectedPosition.y;
  28491. var clientRect = this._drawingCanvas.getBoundingClientRect();
  28492. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  28493. onClick();
  28494. }
  28495. this._drawingContext.beginPath();
  28496. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  28497. this._drawingContext.fillStyle = getFillStyle();
  28498. this._drawingContext.globalAlpha = 0.5;
  28499. this._drawingContext.fill();
  28500. this._drawingContext.globalAlpha = 1.0;
  28501. this._drawingContext.strokeStyle = '#FFFFFF';
  28502. this._drawingContext.lineWidth = 1;
  28503. this._drawingContext.stroke();
  28504. this._drawingContext.fillStyle = "#FFFFFF";
  28505. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  28506. this._drawingContext.beginPath();
  28507. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  28508. this._drawingContext.fill();
  28509. }
  28510. };
  28511. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  28512. if (!this._clickPosition) {
  28513. return false;
  28514. }
  28515. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  28516. return false;
  28517. }
  28518. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  28519. return false;
  28520. }
  28521. return true;
  28522. };
  28523. DebugLayer.prototype.isVisible = function () {
  28524. return this._enabled;
  28525. };
  28526. DebugLayer.prototype.hide = function () {
  28527. if (!this._enabled) {
  28528. return;
  28529. }
  28530. this._enabled = false;
  28531. var engine = this._scene.getEngine();
  28532. this._scene.unregisterBeforeRender(this._syncData);
  28533. this._scene.unregisterAfterRender(this._syncUI);
  28534. this._rootElement.removeChild(this._globalDiv);
  28535. this._scene.forceShowBoundingBoxes = false;
  28536. this._scene.forceWireframe = false;
  28537. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  28538. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  28539. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  28540. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  28541. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  28542. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  28543. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  28544. BABYLON.StandardMaterial.LightmapTextureEnabled = true;
  28545. BABYLON.StandardMaterial.RefractionTextureEnabled = true;
  28546. this._scene.shadowsEnabled = true;
  28547. this._scene.particlesEnabled = true;
  28548. this._scene.postProcessesEnabled = true;
  28549. this._scene.collisionsEnabled = true;
  28550. this._scene.lightsEnabled = true;
  28551. this._scene.texturesEnabled = true;
  28552. this._scene.lensFlaresEnabled = true;
  28553. this._scene.proceduralTexturesEnabled = true;
  28554. this._scene.renderTargetsEnabled = true;
  28555. this._scene.probesEnabled = true;
  28556. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  28557. };
  28558. DebugLayer.prototype.show = function (showUI, camera, rootElement) {
  28559. if (showUI === void 0) { showUI = true; }
  28560. if (camera === void 0) { camera = null; }
  28561. if (rootElement === void 0) { rootElement = null; }
  28562. if (this._enabled) {
  28563. return;
  28564. }
  28565. this._enabled = true;
  28566. if (camera) {
  28567. this._camera = camera;
  28568. }
  28569. else {
  28570. this._camera = this._scene.activeCamera;
  28571. }
  28572. this._showUI = showUI;
  28573. var engine = this._scene.getEngine();
  28574. this._globalDiv = document.createElement("div");
  28575. this._rootElement = rootElement || document.body;
  28576. this._rootElement.appendChild(this._globalDiv);
  28577. this._generateDOMelements();
  28578. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  28579. this._syncPositions();
  28580. this._scene.registerBeforeRender(this._syncData);
  28581. this._scene.registerAfterRender(this._syncUI);
  28582. };
  28583. DebugLayer.prototype._clearLabels = function () {
  28584. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  28585. for (var index = 0; index < this._scene.meshes.length; index++) {
  28586. var mesh = this._scene.meshes[index];
  28587. mesh.renderOverlay = false;
  28588. }
  28589. };
  28590. DebugLayer.prototype._generateheader = function (root, text) {
  28591. var header = document.createElement("div");
  28592. header.innerHTML = text + "&nbsp;";
  28593. header.style.textAlign = "right";
  28594. header.style.width = "100%";
  28595. header.style.color = "white";
  28596. header.style.backgroundColor = "Black";
  28597. header.style.padding = "5px 5px 4px 0px";
  28598. header.style.marginLeft = "-5px";
  28599. header.style.fontWeight = "bold";
  28600. root.appendChild(header);
  28601. };
  28602. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  28603. var label = document.createElement("label");
  28604. label.innerHTML = title;
  28605. label.style.color = color;
  28606. root.appendChild(label);
  28607. root.appendChild(document.createElement("br"));
  28608. };
  28609. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  28610. if (tag === void 0) { tag = null; }
  28611. var label = document.createElement("label");
  28612. var boundingBoxesCheckbox = document.createElement("input");
  28613. boundingBoxesCheckbox.type = "checkbox";
  28614. boundingBoxesCheckbox.checked = initialState;
  28615. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  28616. task(evt.target, tag);
  28617. });
  28618. label.appendChild(boundingBoxesCheckbox);
  28619. var container = document.createElement("span");
  28620. var leftPart = document.createElement("span");
  28621. var rightPart = document.createElement("span");
  28622. rightPart.style.cssFloat = "right";
  28623. leftPart.innerHTML = leftTitle;
  28624. rightPart.innerHTML = rightTitle;
  28625. rightPart.style.fontSize = "12px";
  28626. rightPart.style.maxWidth = "200px";
  28627. container.appendChild(leftPart);
  28628. container.appendChild(rightPart);
  28629. label.appendChild(container);
  28630. root.appendChild(label);
  28631. root.appendChild(document.createElement("br"));
  28632. };
  28633. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  28634. if (tag === void 0) { tag = null; }
  28635. var label = document.createElement("label");
  28636. var checkBox = document.createElement("input");
  28637. checkBox.type = "checkbox";
  28638. checkBox.checked = initialState;
  28639. checkBox.addEventListener("change", function (evt) {
  28640. task(evt.target, tag);
  28641. });
  28642. label.appendChild(checkBox);
  28643. label.appendChild(document.createTextNode(title));
  28644. root.appendChild(label);
  28645. root.appendChild(document.createElement("br"));
  28646. };
  28647. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  28648. if (tag === void 0) { tag = null; }
  28649. var button = document.createElement("button");
  28650. button.innerHTML = title;
  28651. button.style.height = "24px";
  28652. button.style.width = "150px";
  28653. button.style.marginBottom = "5px";
  28654. button.style.color = "#444444";
  28655. button.style.border = "1px solid white";
  28656. button.className = "debugLayerButton";
  28657. button.addEventListener("click", function (evt) {
  28658. task(evt.target, tag);
  28659. });
  28660. root.appendChild(button);
  28661. root.appendChild(document.createElement("br"));
  28662. };
  28663. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  28664. if (tag === void 0) { tag = null; }
  28665. var label = document.createElement("label");
  28666. var boundingBoxesRadio = document.createElement("input");
  28667. boundingBoxesRadio.type = "radio";
  28668. boundingBoxesRadio.name = name;
  28669. boundingBoxesRadio.checked = initialState;
  28670. boundingBoxesRadio.addEventListener("change", function (evt) {
  28671. task(evt.target, tag);
  28672. });
  28673. label.appendChild(boundingBoxesRadio);
  28674. label.appendChild(document.createTextNode(title));
  28675. root.appendChild(label);
  28676. root.appendChild(document.createElement("br"));
  28677. };
  28678. DebugLayer.prototype._generateDOMelements = function () {
  28679. var _this = this;
  28680. this._globalDiv.id = "DebugLayer";
  28681. this._globalDiv.style.position = "absolute";
  28682. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  28683. this._globalDiv.style.fontSize = "14px";
  28684. this._globalDiv.style.color = "white";
  28685. // Drawing canvas
  28686. this._drawingCanvas = document.createElement("canvas");
  28687. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  28688. this._drawingCanvas.style.position = "absolute";
  28689. this._drawingCanvas.style.pointerEvents = "none";
  28690. this._drawingCanvas.style.backgroundColor = "transparent";
  28691. this._drawingContext = this._drawingCanvas.getContext("2d");
  28692. this._globalDiv.appendChild(this._drawingCanvas);
  28693. if (this._showUI) {
  28694. var background = "rgba(128, 128, 128, 0.4)";
  28695. var border = "rgb(180, 180, 180) solid 1px";
  28696. // Stats
  28697. this._statsDiv = document.createElement("div");
  28698. this._statsDiv.id = "DebugLayerStats";
  28699. this._statsDiv.style.border = border;
  28700. this._statsDiv.style.position = "absolute";
  28701. this._statsDiv.style.background = background;
  28702. this._statsDiv.style.padding = "0px 0px 0px 5px";
  28703. this._generateheader(this._statsDiv, "STATISTICS");
  28704. this._statsSubsetDiv = document.createElement("div");
  28705. this._statsSubsetDiv.style.paddingTop = "5px";
  28706. this._statsSubsetDiv.style.paddingBottom = "5px";
  28707. this._statsSubsetDiv.style.overflowY = "auto";
  28708. this._statsDiv.appendChild(this._statsSubsetDiv);
  28709. // Tree
  28710. this._treeDiv = document.createElement("div");
  28711. this._treeDiv.id = "DebugLayerTree";
  28712. this._treeDiv.style.border = border;
  28713. this._treeDiv.style.position = "absolute";
  28714. this._treeDiv.style.background = background;
  28715. this._treeDiv.style.padding = "0px 0px 0px 5px";
  28716. this._treeDiv.style.display = "none";
  28717. this._generateheader(this._treeDiv, "MESHES TREE");
  28718. this._treeSubsetDiv = document.createElement("div");
  28719. this._treeSubsetDiv.style.paddingTop = "5px";
  28720. this._treeSubsetDiv.style.paddingRight = "5px";
  28721. this._treeSubsetDiv.style.overflowY = "auto";
  28722. this._treeSubsetDiv.style.maxHeight = "300px";
  28723. this._treeDiv.appendChild(this._treeSubsetDiv);
  28724. this._needToRefreshMeshesTree = true;
  28725. // Logs
  28726. this._logDiv = document.createElement("div");
  28727. this._logDiv.style.border = border;
  28728. this._logDiv.id = "DebugLayerLogs";
  28729. this._logDiv.style.position = "absolute";
  28730. this._logDiv.style.background = background;
  28731. this._logDiv.style.padding = "0px 0px 0px 5px";
  28732. this._logDiv.style.display = "none";
  28733. this._generateheader(this._logDiv, "LOGS");
  28734. this._logSubsetDiv = document.createElement("div");
  28735. this._logSubsetDiv.style.height = "127px";
  28736. this._logSubsetDiv.style.paddingTop = "5px";
  28737. this._logSubsetDiv.style.overflowY = "auto";
  28738. this._logSubsetDiv.style.fontSize = "12px";
  28739. this._logSubsetDiv.style.fontFamily = "consolas";
  28740. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  28741. this._logDiv.appendChild(this._logSubsetDiv);
  28742. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  28743. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  28744. };
  28745. // Options
  28746. this._optionsDiv = document.createElement("div");
  28747. this._optionsDiv.id = "DebugLayerOptions";
  28748. this._optionsDiv.style.border = border;
  28749. this._optionsDiv.style.position = "absolute";
  28750. this._optionsDiv.style.background = background;
  28751. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  28752. this._optionsDiv.style.overflowY = "auto";
  28753. this._generateheader(this._optionsDiv, "OPTIONS");
  28754. this._optionsSubsetDiv = document.createElement("div");
  28755. this._optionsSubsetDiv.style.paddingTop = "5px";
  28756. this._optionsSubsetDiv.style.paddingBottom = "5px";
  28757. this._optionsSubsetDiv.style.overflowY = "auto";
  28758. this._optionsSubsetDiv.style.maxHeight = "200px";
  28759. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  28760. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  28761. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  28762. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  28763. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  28764. _this._displayTree = element.checked;
  28765. _this._needToRefreshMeshesTree = true;
  28766. });
  28767. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28768. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  28769. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  28770. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  28771. _this._labelsEnabled = element.checked;
  28772. if (!_this._labelsEnabled) {
  28773. _this._clearLabels();
  28774. }
  28775. });
  28776. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  28777. if (element.checked) {
  28778. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  28779. }
  28780. else {
  28781. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  28782. }
  28783. });
  28784. ;
  28785. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28786. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  28787. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  28788. if (element.checked) {
  28789. _this._scene.forceWireframe = false;
  28790. _this._scene.forcePointsCloud = false;
  28791. }
  28792. });
  28793. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  28794. if (element.checked) {
  28795. _this._scene.forceWireframe = true;
  28796. _this._scene.forcePointsCloud = false;
  28797. }
  28798. });
  28799. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  28800. if (element.checked) {
  28801. _this._scene.forceWireframe = false;
  28802. _this._scene.forcePointsCloud = true;
  28803. }
  28804. });
  28805. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28806. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  28807. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  28808. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  28809. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  28810. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  28811. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  28812. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  28813. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  28814. this._generateCheckBox(this._optionsSubsetDiv, "Refraction", BABYLON.StandardMaterial.RefractionTextureEnabled, function (element) { BABYLON.StandardMaterial.RefractionTextureEnabled = element.checked; });
  28815. this._generateCheckBox(this._optionsSubsetDiv, "Lightmap", BABYLON.StandardMaterial.LightmapTextureEnabled, function (element) { BABYLON.StandardMaterial.LightmapTextureEnabled = element.checked; });
  28816. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  28817. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28818. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  28819. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  28820. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  28821. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  28822. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  28823. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  28824. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  28825. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  28826. this._generateCheckBox(this._optionsSubsetDiv, "Probes", this._scene.probesEnabled, function (element) { _this._scene.probesEnabled = element.checked; });
  28827. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  28828. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  28829. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  28830. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  28831. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  28832. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  28833. if (BABYLON.AudioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  28834. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28835. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  28836. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  28837. if (element.checked) {
  28838. _this._scene.headphone = true;
  28839. }
  28840. });
  28841. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  28842. if (element.checked) {
  28843. _this._scene.headphone = false;
  28844. }
  28845. });
  28846. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  28847. _this._scene.audioEnabled = !element.checked;
  28848. });
  28849. }
  28850. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28851. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  28852. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  28853. this._generateButton(this._optionsSubsetDiv, "Run SceneOptimizer", function (element) { BABYLON.SceneOptimizer.OptimizeAsync(_this._scene); });
  28854. this._generateButton(this._optionsSubsetDiv, "Log camera object", function (element) {
  28855. if (_this._camera) {
  28856. console.log(_this._camera);
  28857. }
  28858. else {
  28859. console.warn("No camera defined, or debug layer created before camera creation!");
  28860. }
  28861. });
  28862. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28863. this._globalDiv.appendChild(this._statsDiv);
  28864. this._globalDiv.appendChild(this._logDiv);
  28865. this._globalDiv.appendChild(this._optionsDiv);
  28866. this._globalDiv.appendChild(this._treeDiv);
  28867. }
  28868. };
  28869. DebugLayer.prototype._displayStats = function () {
  28870. var scene = this._scene;
  28871. var engine = scene.getEngine();
  28872. var glInfo = engine.getGlInfo();
  28873. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  28874. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  28875. + "<b>Count</b><br>"
  28876. + "Total meshes: " + scene.meshes.length + "<br>"
  28877. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  28878. + "Total materials: " + scene.materials.length + "<br>"
  28879. + "Total textures: " + scene.textures.length + "<br>"
  28880. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  28881. + "Active indices: " + scene.getActiveIndices() + "<br>"
  28882. + "Active bones: " + scene.getActiveBones() + "<br>"
  28883. + "Active particles: " + scene.getActiveParticles() + "<br>"
  28884. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br><br>"
  28885. + "<b>Duration</b><br>"
  28886. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  28887. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  28888. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  28889. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  28890. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  28891. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  28892. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br>"
  28893. + "Resolution: " + engine.getRenderWidth() + "x" + engine.getRenderHeight() + "<br>"
  28894. + "</div>"
  28895. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  28896. + "<b>Extensions</b><br>"
  28897. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  28898. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  28899. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  28900. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br><br>"
  28901. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  28902. + "Fragment depth: " + (engine.getCaps().fragmentDepthSupported ? "Yes" : "No") + "<br>"
  28903. + "High precision shaders: " + (engine.getCaps().highPrecisionShaderSupported ? "Yes" : "No") + "<br>"
  28904. + "Draw buffers: " + (engine.getCaps().drawBuffersExtension ? "Yes" : "No") + "<br>"
  28905. + "</div><br>"
  28906. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  28907. + "<b>Caps.</b><br>"
  28908. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  28909. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  28910. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br>"
  28911. + "<b>Info</b><br>"
  28912. + "WebGL feature level: " + engine.webGLVersion + "<br>"
  28913. + glInfo.version + "<br>"
  28914. + "</div><br>"
  28915. + glInfo.renderer + "<br>";
  28916. if (this.customStatsFunction) {
  28917. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  28918. }
  28919. };
  28920. return DebugLayer;
  28921. })();
  28922. BABYLON.DebugLayer = DebugLayer;
  28923. })(BABYLON || (BABYLON = {}));
  28924. var BABYLON;
  28925. (function (BABYLON) {
  28926. var DefaultLoadingScreen = (function () {
  28927. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  28928. var _this = this;
  28929. if (_loadingText === void 0) { _loadingText = ""; }
  28930. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  28931. this._renderingCanvas = _renderingCanvas;
  28932. this._loadingText = _loadingText;
  28933. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  28934. // Resize
  28935. this._resizeLoadingUI = function () {
  28936. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  28937. _this._loadingDiv.style.position = "absolute";
  28938. _this._loadingDiv.style.left = canvasRect.left + "px";
  28939. _this._loadingDiv.style.top = canvasRect.top + "px";
  28940. _this._loadingDiv.style.width = canvasRect.width + "px";
  28941. _this._loadingDiv.style.height = canvasRect.height + "px";
  28942. };
  28943. }
  28944. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  28945. var _this = this;
  28946. if (this._loadingDiv) {
  28947. // Do not add a loading screen if there is already one
  28948. return;
  28949. }
  28950. this._loadingDiv = document.createElement("div");
  28951. this._loadingDiv.id = "babylonjsLoadingDiv";
  28952. this._loadingDiv.style.opacity = "0";
  28953. this._loadingDiv.style.transition = "opacity 1.5s ease";
  28954. // Loading text
  28955. this._loadingTextDiv = document.createElement("div");
  28956. this._loadingTextDiv.style.position = "absolute";
  28957. this._loadingTextDiv.style.left = "0";
  28958. this._loadingTextDiv.style.top = "50%";
  28959. this._loadingTextDiv.style.marginTop = "80px";
  28960. this._loadingTextDiv.style.width = "100%";
  28961. this._loadingTextDiv.style.height = "20px";
  28962. this._loadingTextDiv.style.fontFamily = "Arial";
  28963. this._loadingTextDiv.style.fontSize = "14px";
  28964. this._loadingTextDiv.style.color = "white";
  28965. this._loadingTextDiv.style.textAlign = "center";
  28966. this._loadingTextDiv.innerHTML = "Loading";
  28967. this._loadingDiv.appendChild(this._loadingTextDiv);
  28968. //set the predefined text
  28969. this._loadingTextDiv.innerHTML = this._loadingText;
  28970. // Loading img
  28971. var imgBack = new Image();
  28972. 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==";
  28973. imgBack.style.position = "absolute";
  28974. imgBack.style.left = "50%";
  28975. imgBack.style.top = "50%";
  28976. imgBack.style.marginLeft = "-50px";
  28977. imgBack.style.marginTop = "-50px";
  28978. imgBack.style.transition = "transform 1.0s ease";
  28979. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  28980. var deg = 360;
  28981. var onTransitionEnd = function () {
  28982. deg += 360;
  28983. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  28984. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  28985. };
  28986. imgBack.addEventListener("transitionend", onTransitionEnd);
  28987. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  28988. this._loadingDiv.appendChild(imgBack);
  28989. // front image
  28990. var imgFront = new Image();
  28991. 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=";
  28992. imgFront.style.position = "absolute";
  28993. imgFront.style.left = "50%";
  28994. imgFront.style.top = "50%";
  28995. imgFront.style.marginLeft = "-50px";
  28996. imgFront.style.marginTop = "-50px";
  28997. this._loadingDiv.appendChild(imgFront);
  28998. this._resizeLoadingUI();
  28999. window.addEventListener("resize", this._resizeLoadingUI);
  29000. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  29001. document.body.appendChild(this._loadingDiv);
  29002. setTimeout(function () {
  29003. _this._loadingDiv.style.opacity = "1";
  29004. imgBack.style.transform = "rotateZ(360deg)";
  29005. imgBack.style.webkitTransform = "rotateZ(360deg)";
  29006. }, 0);
  29007. };
  29008. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  29009. var _this = this;
  29010. if (!this._loadingDiv) {
  29011. return;
  29012. }
  29013. var onTransitionEnd = function () {
  29014. if (!_this._loadingDiv) {
  29015. return;
  29016. }
  29017. document.body.removeChild(_this._loadingDiv);
  29018. window.removeEventListener("resize", _this._resizeLoadingUI);
  29019. _this._loadingDiv = null;
  29020. };
  29021. this._loadingDiv.style.opacity = "0";
  29022. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  29023. };
  29024. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  29025. set: function (text) {
  29026. this._loadingText = text;
  29027. if (this._loadingTextDiv) {
  29028. this._loadingTextDiv.innerHTML = this._loadingText;
  29029. }
  29030. },
  29031. enumerable: true,
  29032. configurable: true
  29033. });
  29034. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  29035. get: function () {
  29036. return this._loadingDivBackgroundColor;
  29037. },
  29038. set: function (color) {
  29039. this._loadingDivBackgroundColor = color;
  29040. if (!this._loadingDiv) {
  29041. return;
  29042. }
  29043. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  29044. },
  29045. enumerable: true,
  29046. configurable: true
  29047. });
  29048. return DefaultLoadingScreen;
  29049. })();
  29050. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  29051. })(BABYLON || (BABYLON = {}));
  29052. var BABYLON;
  29053. (function (BABYLON) {
  29054. var SIMDVector3 = (function () {
  29055. function SIMDVector3() {
  29056. }
  29057. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  29058. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  29059. var m0 = SIMD.float32x4.load(transformation.m, 0);
  29060. var m1 = SIMD.float32x4.load(transformation.m, 4);
  29061. var m2 = SIMD.float32x4.load(transformation.m, 8);
  29062. var m3 = SIMD.float32x4.load(transformation.m, 12);
  29063. 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));
  29064. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  29065. SIMD.float32x4.storeXYZ(result._data, 0, r);
  29066. };
  29067. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  29068. var v0 = SIMD.float32x4.splat(x);
  29069. var v1 = SIMD.float32x4.splat(y);
  29070. var v2 = SIMD.float32x4.splat(z);
  29071. var m0 = SIMD.float32x4.load(transformation.m, 0);
  29072. var m1 = SIMD.float32x4.load(transformation.m, 4);
  29073. var m2 = SIMD.float32x4.load(transformation.m, 8);
  29074. var m3 = SIMD.float32x4.load(transformation.m, 12);
  29075. 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));
  29076. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  29077. SIMD.float32x4.storeXYZ(result._data, 0, r);
  29078. };
  29079. return SIMDVector3;
  29080. })();
  29081. BABYLON.SIMDVector3 = SIMDVector3;
  29082. var SIMDMatrix = (function () {
  29083. function SIMDMatrix() {
  29084. }
  29085. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  29086. if (offset === void 0) { offset = 0; }
  29087. var tm = this.m;
  29088. var om = other.m;
  29089. var om0 = SIMD.float32x4.load(om, 0);
  29090. var om1 = SIMD.float32x4.load(om, 4);
  29091. var om2 = SIMD.float32x4.load(om, 8);
  29092. var om3 = SIMD.float32x4.load(om, 12);
  29093. var tm0 = SIMD.float32x4.load(tm, 0);
  29094. 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)))));
  29095. var tm1 = SIMD.float32x4.load(tm, 4);
  29096. 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)))));
  29097. var tm2 = SIMD.float32x4.load(tm, 8);
  29098. 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)))));
  29099. var tm3 = SIMD.float32x4.load(tm, 12);
  29100. 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)))));
  29101. };
  29102. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  29103. var src = this.m;
  29104. var dest = other.m;
  29105. var row0, row1, row2, row3;
  29106. var tmp1;
  29107. var minor0, minor1, minor2, minor3;
  29108. var det;
  29109. // Load the 4 rows
  29110. var src0 = SIMD.float32x4.load(src, 0);
  29111. var src1 = SIMD.float32x4.load(src, 4);
  29112. var src2 = SIMD.float32x4.load(src, 8);
  29113. var src3 = SIMD.float32x4.load(src, 12);
  29114. // Transpose the source matrix. Sort of. Not a true transpose operation
  29115. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  29116. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  29117. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  29118. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  29119. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  29120. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  29121. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  29122. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  29123. // This is a true transposition, but it will lead to an incorrect result
  29124. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  29125. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  29126. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  29127. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  29128. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  29129. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  29130. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  29131. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  29132. // ----
  29133. tmp1 = SIMD.float32x4.mul(row2, row3);
  29134. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  29135. minor0 = SIMD.float32x4.mul(row1, tmp1);
  29136. minor1 = SIMD.float32x4.mul(row0, tmp1);
  29137. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  29138. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  29139. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  29140. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  29141. // ----
  29142. tmp1 = SIMD.float32x4.mul(row1, row2);
  29143. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  29144. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  29145. minor3 = SIMD.float32x4.mul(row0, tmp1);
  29146. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  29147. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  29148. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  29149. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  29150. // ----
  29151. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  29152. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  29153. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  29154. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  29155. minor2 = SIMD.float32x4.mul(row0, tmp1);
  29156. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  29157. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  29158. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  29159. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  29160. // ----
  29161. tmp1 = SIMD.float32x4.mul(row0, row1);
  29162. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  29163. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  29164. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  29165. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  29166. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  29167. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  29168. // ----
  29169. tmp1 = SIMD.float32x4.mul(row0, row3);
  29170. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  29171. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  29172. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  29173. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  29174. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  29175. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  29176. // ----
  29177. tmp1 = SIMD.float32x4.mul(row0, row2);
  29178. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  29179. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  29180. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  29181. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  29182. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  29183. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  29184. // Compute determinant
  29185. det = SIMD.float32x4.mul(row0, minor0);
  29186. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  29187. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  29188. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  29189. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  29190. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  29191. // These shuffles aren't necessary if the faulty transposition is done
  29192. // up at the top of this function.
  29193. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  29194. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  29195. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  29196. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  29197. // Compute final values by multiplying with 1/det
  29198. minor0 = SIMD.float32x4.mul(det, minor0);
  29199. minor1 = SIMD.float32x4.mul(det, minor1);
  29200. minor2 = SIMD.float32x4.mul(det, minor2);
  29201. minor3 = SIMD.float32x4.mul(det, minor3);
  29202. SIMD.float32x4.store(dest, 0, minor0);
  29203. SIMD.float32x4.store(dest, 4, minor1);
  29204. SIMD.float32x4.store(dest, 8, minor2);
  29205. SIMD.float32x4.store(dest, 12, minor3);
  29206. return this;
  29207. };
  29208. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  29209. var out = result.m;
  29210. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  29211. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  29212. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  29213. // cc.kmVec3Subtract(f, pCenter, pEye);
  29214. var f = SIMD.float32x4.sub(center, eye);
  29215. // cc.kmVec3Normalize(f, f);
  29216. var tmp = SIMD.float32x4.mul(f, f);
  29217. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  29218. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  29219. // cc.kmVec3Assign(up, pUp);
  29220. // cc.kmVec3Normalize(up, up);
  29221. tmp = SIMD.float32x4.mul(up, up);
  29222. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  29223. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  29224. // cc.kmVec3Cross(s, f, up);
  29225. 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)));
  29226. // cc.kmVec3Normalize(s, s);
  29227. tmp = SIMD.float32x4.mul(s, s);
  29228. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  29229. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  29230. // cc.kmVec3Cross(u, s, f);
  29231. 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)));
  29232. // cc.kmVec3Normalize(s, s);
  29233. tmp = SIMD.float32x4.mul(s, s);
  29234. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  29235. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  29236. var zero = SIMD.float32x4.splat(0.0);
  29237. s = SIMD.float32x4.neg(s);
  29238. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  29239. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  29240. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  29241. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  29242. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  29243. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  29244. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  29245. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  29246. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  29247. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  29248. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  29249. var b3 = SIMD.float32x4.neg(eye);
  29250. b3 = SIMD.float32x4.withW(b3, 1.0);
  29251. 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)))));
  29252. 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)))));
  29253. 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)))));
  29254. 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)))));
  29255. };
  29256. return SIMDMatrix;
  29257. })();
  29258. BABYLON.SIMDMatrix = SIMDMatrix;
  29259. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  29260. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  29261. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  29262. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  29263. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  29264. var SIMDHelper = (function () {
  29265. function SIMDHelper() {
  29266. }
  29267. Object.defineProperty(SIMDHelper, "IsEnabled", {
  29268. get: function () {
  29269. return SIMDHelper._isEnabled;
  29270. },
  29271. enumerable: true,
  29272. configurable: true
  29273. });
  29274. SIMDHelper.DisableSIMD = function () {
  29275. // Replace functions
  29276. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  29277. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  29278. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  29279. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  29280. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  29281. SIMDHelper._isEnabled = false;
  29282. };
  29283. SIMDHelper.EnableSIMD = function () {
  29284. if (window.SIMD === undefined) {
  29285. return;
  29286. }
  29287. // Replace functions
  29288. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  29289. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  29290. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  29291. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  29292. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  29293. Object.defineProperty(BABYLON.Vector3.prototype, "x", {
  29294. get: function () { return this._data[0]; },
  29295. set: function (value) {
  29296. if (!this._data) {
  29297. this._data = new Float32Array(3);
  29298. }
  29299. this._data[0] = value;
  29300. }
  29301. });
  29302. Object.defineProperty(BABYLON.Vector3.prototype, "y", {
  29303. get: function () { return this._data[1]; },
  29304. set: function (value) {
  29305. this._data[1] = value;
  29306. }
  29307. });
  29308. Object.defineProperty(BABYLON.Vector3.prototype, "z", {
  29309. get: function () { return this._data[2]; },
  29310. set: function (value) {
  29311. this._data[2] = value;
  29312. }
  29313. });
  29314. SIMDHelper._isEnabled = true;
  29315. };
  29316. SIMDHelper._isEnabled = false;
  29317. return SIMDHelper;
  29318. })();
  29319. BABYLON.SIMDHelper = SIMDHelper;
  29320. })(BABYLON || (BABYLON = {}));
  29321. var BABYLON;
  29322. (function (BABYLON) {
  29323. var ShaderMaterial = (function (_super) {
  29324. __extends(ShaderMaterial, _super);
  29325. function ShaderMaterial(name, scene, shaderPath, options) {
  29326. _super.call(this, name, scene);
  29327. this._textures = {};
  29328. this._floats = {};
  29329. this._floatsArrays = {};
  29330. this._colors3 = {};
  29331. this._colors4 = {};
  29332. this._vectors2 = {};
  29333. this._vectors3 = {};
  29334. this._vectors4 = {};
  29335. this._matrices = {};
  29336. this._matrices3x3 = {};
  29337. this._matrices2x2 = {};
  29338. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  29339. this._shaderPath = shaderPath;
  29340. options.needAlphaBlending = options.needAlphaBlending || false;
  29341. options.needAlphaTesting = options.needAlphaTesting || false;
  29342. options.attributes = options.attributes || ["position", "normal", "uv"];
  29343. options.uniforms = options.uniforms || ["worldViewProjection"];
  29344. options.samplers = options.samplers || [];
  29345. options.defines = options.defines || [];
  29346. this._options = options;
  29347. }
  29348. ShaderMaterial.prototype.needAlphaBlending = function () {
  29349. return this._options.needAlphaBlending;
  29350. };
  29351. ShaderMaterial.prototype.needAlphaTesting = function () {
  29352. return this._options.needAlphaTesting;
  29353. };
  29354. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  29355. if (this._options.uniforms.indexOf(uniformName) === -1) {
  29356. this._options.uniforms.push(uniformName);
  29357. }
  29358. };
  29359. ShaderMaterial.prototype.setTexture = function (name, texture) {
  29360. if (this._options.samplers.indexOf(name) === -1) {
  29361. this._options.samplers.push(name);
  29362. }
  29363. this._textures[name] = texture;
  29364. return this;
  29365. };
  29366. ShaderMaterial.prototype.setFloat = function (name, value) {
  29367. this._checkUniform(name);
  29368. this._floats[name] = value;
  29369. return this;
  29370. };
  29371. ShaderMaterial.prototype.setFloats = function (name, value) {
  29372. this._checkUniform(name);
  29373. this._floatsArrays[name] = value;
  29374. return this;
  29375. };
  29376. ShaderMaterial.prototype.setColor3 = function (name, value) {
  29377. this._checkUniform(name);
  29378. this._colors3[name] = value;
  29379. return this;
  29380. };
  29381. ShaderMaterial.prototype.setColor4 = function (name, value) {
  29382. this._checkUniform(name);
  29383. this._colors4[name] = value;
  29384. return this;
  29385. };
  29386. ShaderMaterial.prototype.setVector2 = function (name, value) {
  29387. this._checkUniform(name);
  29388. this._vectors2[name] = value;
  29389. return this;
  29390. };
  29391. ShaderMaterial.prototype.setVector3 = function (name, value) {
  29392. this._checkUniform(name);
  29393. this._vectors3[name] = value;
  29394. return this;
  29395. };
  29396. ShaderMaterial.prototype.setVector4 = function (name, value) {
  29397. this._checkUniform(name);
  29398. this._vectors4[name] = value;
  29399. return this;
  29400. };
  29401. ShaderMaterial.prototype.setMatrix = function (name, value) {
  29402. this._checkUniform(name);
  29403. this._matrices[name] = value;
  29404. return this;
  29405. };
  29406. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  29407. this._checkUniform(name);
  29408. this._matrices3x3[name] = value;
  29409. return this;
  29410. };
  29411. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  29412. this._checkUniform(name);
  29413. this._matrices2x2[name] = value;
  29414. return this;
  29415. };
  29416. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  29417. var scene = this.getScene();
  29418. var engine = scene.getEngine();
  29419. if (!this.checkReadyOnEveryCall) {
  29420. if (this._renderId === scene.getRenderId()) {
  29421. return true;
  29422. }
  29423. }
  29424. // Instances
  29425. var defines = [];
  29426. var fallbacks = new BABYLON.EffectFallbacks();
  29427. if (useInstances) {
  29428. defines.push("#define INSTANCES");
  29429. }
  29430. for (var index = 0; index < this._options.defines.length; index++) {
  29431. defines.push(this._options.defines[index]);
  29432. }
  29433. // Bones
  29434. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  29435. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  29436. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  29437. fallbacks.addCPUSkinningFallback(0, mesh);
  29438. }
  29439. // Alpha test
  29440. if (engine.getAlphaTesting()) {
  29441. defines.push("#define ALPHATEST");
  29442. }
  29443. var previousEffect = this._effect;
  29444. var join = defines.join("\n");
  29445. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  29446. if (!this._effect.isReady()) {
  29447. return false;
  29448. }
  29449. if (previousEffect !== this._effect) {
  29450. scene.resetCachedMaterial();
  29451. }
  29452. this._renderId = scene.getRenderId();
  29453. return true;
  29454. };
  29455. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  29456. var scene = this.getScene();
  29457. if (this._options.uniforms.indexOf("world") !== -1) {
  29458. this._effect.setMatrix("world", world);
  29459. }
  29460. if (this._options.uniforms.indexOf("worldView") !== -1) {
  29461. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  29462. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  29463. }
  29464. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  29465. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  29466. }
  29467. };
  29468. ShaderMaterial.prototype.bind = function (world, mesh) {
  29469. // Std values
  29470. this.bindOnlyWorldMatrix(world);
  29471. if (this.getScene().getCachedMaterial() !== this) {
  29472. if (this._options.uniforms.indexOf("view") !== -1) {
  29473. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  29474. }
  29475. if (this._options.uniforms.indexOf("projection") !== -1) {
  29476. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  29477. }
  29478. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  29479. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  29480. }
  29481. // Bones
  29482. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  29483. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  29484. }
  29485. // Texture
  29486. for (var name in this._textures) {
  29487. this._effect.setTexture(name, this._textures[name]);
  29488. }
  29489. // Float
  29490. for (name in this._floats) {
  29491. this._effect.setFloat(name, this._floats[name]);
  29492. }
  29493. // Float s
  29494. for (name in this._floatsArrays) {
  29495. this._effect.setArray(name, this._floatsArrays[name]);
  29496. }
  29497. // Color3
  29498. for (name in this._colors3) {
  29499. this._effect.setColor3(name, this._colors3[name]);
  29500. }
  29501. // Color4
  29502. for (name in this._colors4) {
  29503. var color = this._colors4[name];
  29504. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  29505. }
  29506. // Vector2
  29507. for (name in this._vectors2) {
  29508. this._effect.setVector2(name, this._vectors2[name]);
  29509. }
  29510. // Vector3
  29511. for (name in this._vectors3) {
  29512. this._effect.setVector3(name, this._vectors3[name]);
  29513. }
  29514. // Vector4
  29515. for (name in this._vectors4) {
  29516. this._effect.setVector4(name, this._vectors4[name]);
  29517. }
  29518. // Matrix
  29519. for (name in this._matrices) {
  29520. this._effect.setMatrix(name, this._matrices[name]);
  29521. }
  29522. // Matrix 3x3
  29523. for (name in this._matrices3x3) {
  29524. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  29525. }
  29526. // Matrix 2x2
  29527. for (name in this._matrices2x2) {
  29528. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  29529. }
  29530. }
  29531. _super.prototype.bind.call(this, world, mesh);
  29532. };
  29533. ShaderMaterial.prototype.clone = function (name) {
  29534. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  29535. return newShaderMaterial;
  29536. };
  29537. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  29538. for (var name in this._textures) {
  29539. this._textures[name].dispose();
  29540. }
  29541. this._textures = {};
  29542. _super.prototype.dispose.call(this, forceDisposeEffect);
  29543. };
  29544. ShaderMaterial.prototype.serialize = function () {
  29545. var serializationObject = _super.prototype.serialize.call(this);
  29546. serializationObject.options = this._options;
  29547. serializationObject.shaderPath = this._shaderPath;
  29548. serializationObject.customType = "BABYLON.ShaderMaterial";
  29549. // Texture
  29550. serializationObject.textures = {};
  29551. for (var name in this._textures) {
  29552. serializationObject.textures[name] = this._textures[name].serialize();
  29553. }
  29554. // Float
  29555. serializationObject.floats = {};
  29556. for (name in this._floats) {
  29557. serializationObject.floats[name] = this._floats[name];
  29558. }
  29559. // Float s
  29560. serializationObject.floatArrays = {};
  29561. for (name in this._floatsArrays) {
  29562. serializationObject.floatArrays[name] = this._floatsArrays[name];
  29563. }
  29564. // Color3
  29565. serializationObject.colors3 = {};
  29566. for (name in this._colors3) {
  29567. serializationObject.colors3[name] = this._colors3[name].asArray();
  29568. }
  29569. // Color4
  29570. serializationObject.colors4 = {};
  29571. for (name in this._colors4) {
  29572. serializationObject.colors4[name] = this._colors4[name].asArray();
  29573. }
  29574. // Vector2
  29575. serializationObject.vectors2 = {};
  29576. for (name in this._vectors2) {
  29577. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  29578. }
  29579. // Vector3
  29580. serializationObject.vectors3 = {};
  29581. for (name in this._vectors3) {
  29582. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  29583. }
  29584. // Vector4
  29585. serializationObject.vectors4 = {};
  29586. for (name in this._vectors4) {
  29587. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  29588. }
  29589. // Matrix
  29590. serializationObject.matrices = {};
  29591. for (name in this._matrices) {
  29592. serializationObject.matrices[name] = this._matrices[name].asArray();
  29593. }
  29594. // Matrix 3x3
  29595. serializationObject.matrices3x3 = {};
  29596. for (name in this._matrices3x3) {
  29597. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  29598. }
  29599. // Matrix 2x2
  29600. serializationObject.matrices2x2 = {};
  29601. for (name in this._matrices2x2) {
  29602. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  29603. }
  29604. return serializationObject;
  29605. };
  29606. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  29607. var material = new ShaderMaterial(source.name, scene, source.shaderPath, source.options);
  29608. // Texture
  29609. for (var name in source.textures) {
  29610. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  29611. }
  29612. // Float
  29613. for (name in source.floats) {
  29614. material.setFloat(name, source.floats[name]);
  29615. }
  29616. // Float s
  29617. for (name in source.floatsArrays) {
  29618. material.setFloats(name, source.floatsArrays[name]);
  29619. }
  29620. // Color3
  29621. for (name in source.colors3) {
  29622. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  29623. }
  29624. // Color4
  29625. for (name in source.colors4) {
  29626. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  29627. }
  29628. // Vector2
  29629. for (name in source.vectors2) {
  29630. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  29631. }
  29632. // Vector3
  29633. for (name in source.vectors3) {
  29634. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  29635. }
  29636. // Vector4
  29637. for (name in source.vectors4) {
  29638. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  29639. }
  29640. // Matrix
  29641. for (name in source.matrices) {
  29642. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  29643. }
  29644. // Matrix 3x3
  29645. for (name in source.matrices3x3) {
  29646. material.setMatrix3x3(name, source.matrices3x3[name]);
  29647. }
  29648. // Matrix 2x2
  29649. for (name in source.matrices2x2) {
  29650. material.setMatrix2x2(name, source.matrices2x2[name]);
  29651. }
  29652. return material;
  29653. };
  29654. return ShaderMaterial;
  29655. })(BABYLON.Material);
  29656. BABYLON.ShaderMaterial = ShaderMaterial;
  29657. })(BABYLON || (BABYLON = {}));
  29658. var BABYLON;
  29659. (function (BABYLON) {
  29660. var Internals;
  29661. (function (Internals) {
  29662. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  29663. // All values and structures referenced from:
  29664. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  29665. var DDS_MAGIC = 0x20534444;
  29666. 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;
  29667. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  29668. 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;
  29669. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  29670. function FourCCToInt32(value) {
  29671. return value.charCodeAt(0) +
  29672. (value.charCodeAt(1) << 8) +
  29673. (value.charCodeAt(2) << 16) +
  29674. (value.charCodeAt(3) << 24);
  29675. }
  29676. function Int32ToFourCC(value) {
  29677. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  29678. }
  29679. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  29680. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  29681. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  29682. var headerLengthInt = 31; // The header length in 32 bit ints
  29683. // Offsets into the header array
  29684. var off_magic = 0;
  29685. var off_size = 1;
  29686. var off_flags = 2;
  29687. var off_height = 3;
  29688. var off_width = 4;
  29689. var off_mipmapCount = 7;
  29690. var off_pfFlags = 20;
  29691. var off_pfFourCC = 21;
  29692. var off_RGBbpp = 22;
  29693. var off_RMask = 23;
  29694. var off_GMask = 24;
  29695. var off_BMask = 25;
  29696. var off_AMask = 26;
  29697. var off_caps1 = 27;
  29698. var off_caps2 = 28;
  29699. ;
  29700. var DDSTools = (function () {
  29701. function DDSTools() {
  29702. }
  29703. DDSTools.GetDDSInfo = function (arrayBuffer) {
  29704. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  29705. var mipmapCount = 1;
  29706. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  29707. mipmapCount = Math.max(1, header[off_mipmapCount]);
  29708. }
  29709. return {
  29710. width: header[off_width],
  29711. height: header[off_height],
  29712. mipmapCount: mipmapCount,
  29713. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  29714. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  29715. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  29716. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  29717. };
  29718. };
  29719. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  29720. var byteArray = new Uint8Array(dataLength);
  29721. var srcData = new Uint8Array(arrayBuffer);
  29722. var index = 0;
  29723. for (var y = height - 1; y >= 0; y--) {
  29724. for (var x = 0; x < width; x++) {
  29725. var srcPos = dataOffset + (x + y * width) * 4;
  29726. byteArray[index + 2] = srcData[srcPos];
  29727. byteArray[index + 1] = srcData[srcPos + 1];
  29728. byteArray[index] = srcData[srcPos + 2];
  29729. byteArray[index + 3] = srcData[srcPos + 3];
  29730. index += 4;
  29731. }
  29732. }
  29733. return byteArray;
  29734. };
  29735. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  29736. var byteArray = new Uint8Array(dataLength);
  29737. var srcData = new Uint8Array(arrayBuffer);
  29738. var index = 0;
  29739. for (var y = height - 1; y >= 0; y--) {
  29740. for (var x = 0; x < width; x++) {
  29741. var srcPos = dataOffset + (x + y * width) * 3;
  29742. byteArray[index + 2] = srcData[srcPos];
  29743. byteArray[index + 1] = srcData[srcPos + 1];
  29744. byteArray[index] = srcData[srcPos + 2];
  29745. index += 3;
  29746. }
  29747. }
  29748. return byteArray;
  29749. };
  29750. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  29751. var byteArray = new Uint8Array(dataLength);
  29752. var srcData = new Uint8Array(arrayBuffer);
  29753. var index = 0;
  29754. for (var y = height - 1; y >= 0; y--) {
  29755. for (var x = 0; x < width; x++) {
  29756. var srcPos = dataOffset + (x + y * width);
  29757. byteArray[index] = srcData[srcPos];
  29758. index++;
  29759. }
  29760. }
  29761. return byteArray;
  29762. };
  29763. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  29764. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  29765. if (header[off_magic] != DDS_MAGIC) {
  29766. BABYLON.Tools.Error("Invalid magic number in DDS header");
  29767. return;
  29768. }
  29769. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  29770. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  29771. return;
  29772. }
  29773. if (info.isFourCC) {
  29774. fourCC = header[off_pfFourCC];
  29775. switch (fourCC) {
  29776. case FOURCC_DXT1:
  29777. blockBytes = 8;
  29778. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  29779. break;
  29780. case FOURCC_DXT3:
  29781. blockBytes = 16;
  29782. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  29783. break;
  29784. case FOURCC_DXT5:
  29785. blockBytes = 16;
  29786. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  29787. break;
  29788. default:
  29789. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  29790. return;
  29791. }
  29792. }
  29793. mipmapCount = 1;
  29794. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  29795. mipmapCount = Math.max(1, header[off_mipmapCount]);
  29796. }
  29797. var bpp = header[off_RGBbpp];
  29798. for (var face = 0; face < faces; face++) {
  29799. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  29800. width = header[off_width];
  29801. height = header[off_height];
  29802. dataOffset = header[off_size] + 4;
  29803. for (i = 0; i < mipmapCount; ++i) {
  29804. if (info.isRGB) {
  29805. if (bpp === 24) {
  29806. dataLength = width * height * 3;
  29807. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  29808. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  29809. }
  29810. else {
  29811. dataLength = width * height * 4;
  29812. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  29813. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  29814. }
  29815. }
  29816. else if (info.isLuminance) {
  29817. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  29818. var unpaddedRowSize = width;
  29819. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  29820. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  29821. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  29822. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  29823. }
  29824. else {
  29825. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  29826. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  29827. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  29828. }
  29829. dataOffset += dataLength;
  29830. width *= 0.5;
  29831. height *= 0.5;
  29832. width = Math.max(1.0, width);
  29833. height = Math.max(1.0, height);
  29834. }
  29835. }
  29836. };
  29837. return DDSTools;
  29838. })();
  29839. Internals.DDSTools = DDSTools;
  29840. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  29841. })(BABYLON || (BABYLON = {}));
  29842. var BABYLON;
  29843. (function (BABYLON) {
  29844. var CannonJSPlugin = (function () {
  29845. function CannonJSPlugin(_useDeltaForWorldStep) {
  29846. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  29847. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  29848. this._registeredMeshes = [];
  29849. this._physicsMaterials = [];
  29850. this._fixedTimeStep = 1 / 60;
  29851. //private _maxSubSteps : number = 15;
  29852. this.name = "CannonJS";
  29853. this.updateBodyPosition = function (mesh) {
  29854. for (var index = 0; index < this._registeredMeshes.length; index++) {
  29855. var registeredMesh = this._registeredMeshes[index];
  29856. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  29857. var body = registeredMesh.body;
  29858. var center = mesh.getBoundingInfo().boundingBox.center.clone();
  29859. body.quaternion.copy(mesh.rotationQuaternion);
  29860. if (registeredMesh.deltaRotation) {
  29861. var tmpQ = new CANNON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  29862. body.quaternion = body.quaternion.mult(tmpQ);
  29863. }
  29864. if (registeredMesh.type === CANNON.Shape.types.HEIGHTFIELD) {
  29865. //calculate the correct body position:
  29866. var rotationQuaternion = mesh.rotationQuaternion;
  29867. mesh.rotationQuaternion = new BABYLON.Quaternion();
  29868. mesh.computeWorldMatrix(true);
  29869. //get original center with no rotation
  29870. var center = mesh.getBoundingInfo().boundingBox.center.clone();
  29871. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  29872. //rotation is back
  29873. mesh.rotationQuaternion = rotationQuaternion;
  29874. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  29875. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  29876. mesh.setPivotMatrix(p);
  29877. mesh.computeWorldMatrix(true);
  29878. //calculate the translation
  29879. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  29880. center.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  29881. //add it inverted to the delta
  29882. registeredMesh.delta = mesh.getBoundingInfo().boundingBox.center.subtract(center);
  29883. registeredMesh.delta.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  29884. mesh.setPivotMatrix(oldPivot);
  29885. mesh.computeWorldMatrix(true);
  29886. }
  29887. else if (registeredMesh.type === CANNON.Shape.types.TRIMESH) {
  29888. center.copyFromFloats(mesh.position.x, mesh.position.y, mesh.position.z);
  29889. }
  29890. body.position.set(center.x, center.y, center.z);
  29891. return;
  29892. }
  29893. }
  29894. };
  29895. }
  29896. CannonJSPlugin.prototype.initialize = function (iterations) {
  29897. if (iterations === void 0) { iterations = 10; }
  29898. this._world = new CANNON.World();
  29899. this._world.broadphase = new CANNON.NaiveBroadphase();
  29900. this._world.solver.iterations = iterations;
  29901. };
  29902. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  29903. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  29904. };
  29905. CannonJSPlugin.prototype.runOneStep = function (delta) {
  29906. var _this = this;
  29907. this._world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0);
  29908. this._registeredMeshes.forEach(function (registeredMesh) {
  29909. // Body position
  29910. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  29911. registeredMesh.mesh.position.x = bodyX + registeredMesh.delta.x;
  29912. registeredMesh.mesh.position.y = bodyY + registeredMesh.delta.y;
  29913. registeredMesh.mesh.position.z = bodyZ + registeredMesh.delta.z;
  29914. registeredMesh.mesh.rotationQuaternion.copyFrom(registeredMesh.body.quaternion);
  29915. if (registeredMesh.deltaRotation) {
  29916. registeredMesh.mesh.rotationQuaternion.multiplyInPlace(registeredMesh.deltaRotation);
  29917. }
  29918. //is the physics collision callback is set?
  29919. if (registeredMesh.mesh.onPhysicsCollide) {
  29920. if (!registeredMesh.collisionFunction) {
  29921. registeredMesh.collisionFunction = function (e) {
  29922. //find the mesh that collided with the registered mesh
  29923. for (var idx = 0; idx < _this._registeredMeshes.length; idx++) {
  29924. if (_this._registeredMeshes[idx].body == e.body) {
  29925. registeredMesh.mesh.onPhysicsCollide(_this._registeredMeshes[idx].mesh, e.contact);
  29926. }
  29927. }
  29928. };
  29929. registeredMesh.body.addEventListener("collide", registeredMesh.collisionFunction);
  29930. }
  29931. }
  29932. else {
  29933. //unregister, in case the function was removed for some reason
  29934. if (registeredMesh.collisionFunction) {
  29935. registeredMesh.body.removeEventListener("collide", registeredMesh.collisionFunction);
  29936. }
  29937. }
  29938. });
  29939. };
  29940. CannonJSPlugin.prototype.setGravity = function (gravity) {
  29941. this._gravity = gravity;
  29942. this._world.gravity.set(gravity.x, gravity.y, gravity.z);
  29943. };
  29944. CannonJSPlugin.prototype.getGravity = function () {
  29945. return this._gravity;
  29946. };
  29947. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  29948. this.unregisterMesh(mesh);
  29949. if (!mesh.rotationQuaternion) {
  29950. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  29951. }
  29952. mesh.computeWorldMatrix(true);
  29953. var shape = this._createShape(mesh, impostor);
  29954. return this._createRigidBodyFromShape(shape, mesh, options);
  29955. };
  29956. CannonJSPlugin.prototype._createShape = function (mesh, impostor) {
  29957. //get the correct bounding box
  29958. var oldQuaternion = mesh.rotationQuaternion;
  29959. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  29960. mesh.computeWorldMatrix(true);
  29961. var returnValue;
  29962. switch (impostor) {
  29963. case BABYLON.PhysicsEngine.SphereImpostor:
  29964. var bbox = mesh.getBoundingInfo().boundingBox;
  29965. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  29966. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  29967. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  29968. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  29969. break;
  29970. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  29971. case BABYLON.PhysicsEngine.CylinderImpostor:
  29972. BABYLON.Tools.Warn("CylinderImposter not yet implemented, using BoxImposter instead");
  29973. case BABYLON.PhysicsEngine.BoxImpostor:
  29974. bbox = mesh.getBoundingInfo().boundingBox;
  29975. var min = bbox.minimumWorld;
  29976. var max = bbox.maximumWorld;
  29977. var box = max.subtract(min).scale(0.5);
  29978. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  29979. break;
  29980. case BABYLON.PhysicsEngine.PlaneImpostor:
  29981. BABYLON.Tools.Warn("Attention, Cannon.js PlaneImposter might not behave as you wish. Consider using BoxImposter instead");
  29982. returnValue = new CANNON.Plane();
  29983. break;
  29984. case BABYLON.PhysicsEngine.MeshImpostor:
  29985. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29986. var rawFaces = mesh.getIndices();
  29987. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  29988. returnValue = new CANNON.Trimesh(rawVerts, rawFaces); //this._createConvexPolyhedron(rawVerts, rawFaces, mesh);
  29989. break;
  29990. case BABYLON.PhysicsEngine.HeightmapImpostor:
  29991. returnValue = this._createHeightmap(mesh);
  29992. break;
  29993. }
  29994. mesh.rotationQuaternion = oldQuaternion;
  29995. return returnValue;
  29996. };
  29997. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh) {
  29998. var verts = [], faces = [];
  29999. mesh.computeWorldMatrix(true);
  30000. //reuse this variable
  30001. var transformed = BABYLON.Vector3.Zero();
  30002. // Get vertices
  30003. for (var i = 0; i < rawVerts.length; i += 3) {
  30004. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  30005. verts.push(new CANNON.Vec3(transformed.x, transformed.y, transformed.z));
  30006. }
  30007. // Get faces
  30008. for (var j = 0; j < rawFaces.length; j += 3) {
  30009. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  30010. }
  30011. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  30012. return shape;
  30013. };
  30014. CannonJSPlugin.prototype._createHeightmap = function (mesh, pointDepth) {
  30015. var pos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30016. var matrix = [];
  30017. //For now pointDepth will not be used and will be automatically calculated.
  30018. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  30019. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  30020. var dim = Math.min(mesh.getBoundingInfo().boundingBox.extendSize.x, mesh.getBoundingInfo().boundingBox.extendSize.z);
  30021. var elementSize = dim * 2 / arraySize;
  30022. var minY = mesh.getBoundingInfo().boundingBox.extendSize.y;
  30023. for (var i = 0; i < pos.length; i = i + 3) {
  30024. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  30025. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  30026. var y = pos[i + 1] + minY;
  30027. if (!matrix[x]) {
  30028. matrix[x] = [];
  30029. }
  30030. if (!matrix[x][z]) {
  30031. matrix[x][z] = y;
  30032. }
  30033. matrix[x][z] = Math.max(y, matrix[x][z]);
  30034. }
  30035. for (var x = 0; x <= arraySize; ++x) {
  30036. if (!matrix[x]) {
  30037. var loc = 1;
  30038. while (!matrix[(x + loc) % arraySize]) {
  30039. loc++;
  30040. }
  30041. matrix[x] = matrix[(x + loc) % arraySize].slice();
  30042. }
  30043. for (var z = 0; z <= arraySize; ++z) {
  30044. if (!matrix[x][z]) {
  30045. var loc = 1;
  30046. var newValue;
  30047. while (newValue === undefined) {
  30048. newValue = matrix[x][(z + loc++) % arraySize];
  30049. }
  30050. matrix[x][z] = newValue;
  30051. }
  30052. }
  30053. }
  30054. var shape = new CANNON.Heightfield(matrix, {
  30055. elementSize: elementSize
  30056. });
  30057. //For future reference, needed for body transformation
  30058. shape.minY = minY;
  30059. return shape;
  30060. };
  30061. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  30062. var index;
  30063. var mat;
  30064. for (index = 0; index < this._physicsMaterials.length; index++) {
  30065. mat = this._physicsMaterials[index];
  30066. if (mat.friction === friction && mat.restitution === restitution) {
  30067. return mat;
  30068. }
  30069. }
  30070. var currentMat = new CANNON.Material("mat");
  30071. this._physicsMaterials.push(currentMat);
  30072. for (index = 0; index < this._physicsMaterials.length; index++) {
  30073. mat = this._physicsMaterials[index];
  30074. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, { friction: friction, restitution: restitution });
  30075. this._world.addContactMaterial(contactMaterial);
  30076. }
  30077. return currentMat;
  30078. };
  30079. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, options) {
  30080. if (!mesh.rotationQuaternion) {
  30081. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  30082. }
  30083. // The delta between the mesh position and the mesh bounding box center
  30084. var bbox = mesh.getBoundingInfo().boundingBox;
  30085. var deltaPosition = mesh.position.subtract(bbox.center);
  30086. var deltaRotation;
  30087. var material = this._addMaterial(options.friction, options.restitution);
  30088. var body = new CANNON.Body({
  30089. mass: options.mass,
  30090. material: material,
  30091. position: new CANNON.Vec3(bbox.center.x, bbox.center.y, bbox.center.z)
  30092. });
  30093. body.quaternion = new CANNON.Quaternion(mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z, mesh.rotationQuaternion.w);
  30094. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  30095. if (shape.type === CANNON.Shape.types.PLANE || shape.type === CANNON.Shape.types.HEIGHTFIELD) {
  30096. //-90 DEG in X, precalculated
  30097. var tmpQ = new CANNON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  30098. body.quaternion = body.quaternion.mult(tmpQ);
  30099. //Invert! (Precalculated, 90 deg in X)
  30100. deltaRotation = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  30101. }
  30102. //If it is a heightfield, if should be centered.
  30103. if (shape.type === CANNON.Shape.types.HEIGHTFIELD) {
  30104. //calculate the correct body position:
  30105. var rotationQuaternion = mesh.rotationQuaternion;
  30106. mesh.rotationQuaternion = new BABYLON.Quaternion();
  30107. mesh.computeWorldMatrix(true);
  30108. //get original center with no rotation
  30109. var center = mesh.getBoundingInfo().boundingBox.center.clone();
  30110. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  30111. //rotation is back
  30112. mesh.rotationQuaternion = rotationQuaternion;
  30113. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  30114. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  30115. mesh.setPivotMatrix(p);
  30116. mesh.computeWorldMatrix(true);
  30117. //calculate the translation
  30118. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  30119. body.position = new CANNON.Vec3(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  30120. //add it inverted to the delta
  30121. deltaPosition = mesh.getBoundingInfo().boundingBox.center.subtract(center);
  30122. deltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  30123. mesh.setPivotMatrix(oldPivot);
  30124. mesh.computeWorldMatrix(true);
  30125. }
  30126. else if (shape.type === CANNON.Shape.types.TRIMESH) {
  30127. deltaPosition = BABYLON.Vector3.Zero();
  30128. }
  30129. //add the shape
  30130. body.addShape(shape);
  30131. this._world.add(body);
  30132. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition, deltaRotation: deltaRotation, type: shape.type });
  30133. return body;
  30134. };
  30135. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  30136. var initialMesh = parts[0].mesh;
  30137. this.unregisterMesh(initialMesh);
  30138. initialMesh.computeWorldMatrix(true);
  30139. var initialShape = this._createShape(initialMesh, parts[0].impostor);
  30140. var body = this._createRigidBodyFromShape(initialShape, initialMesh, options);
  30141. for (var index = 1; index < parts.length; index++) {
  30142. var mesh = parts[index].mesh;
  30143. mesh.computeWorldMatrix(true);
  30144. var shape = this._createShape(mesh, parts[index].impostor);
  30145. var localPosition = mesh.position;
  30146. body.addShape(shape, new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  30147. }
  30148. return body;
  30149. };
  30150. CannonJSPlugin.prototype._unbindBody = function (body) {
  30151. for (var index = 0; index < this._registeredMeshes.length; index++) {
  30152. var registeredMesh = this._registeredMeshes[index];
  30153. if (registeredMesh.body === body) {
  30154. this._world.remove(registeredMesh.body);
  30155. registeredMesh.body = null;
  30156. registeredMesh.delta = null;
  30157. registeredMesh.deltaRotation = null;
  30158. }
  30159. }
  30160. };
  30161. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  30162. for (var index = 0; index < this._registeredMeshes.length; index++) {
  30163. var registeredMesh = this._registeredMeshes[index];
  30164. if (registeredMesh.mesh === mesh) {
  30165. // Remove body
  30166. if (registeredMesh.body) {
  30167. this._unbindBody(registeredMesh.body);
  30168. }
  30169. this._registeredMeshes.splice(index, 1);
  30170. return;
  30171. }
  30172. }
  30173. };
  30174. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  30175. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  30176. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  30177. for (var index = 0; index < this._registeredMeshes.length; index++) {
  30178. var registeredMesh = this._registeredMeshes[index];
  30179. if (registeredMesh.mesh === mesh) {
  30180. registeredMesh.body.applyImpulse(impulse, worldPoint);
  30181. return;
  30182. }
  30183. }
  30184. };
  30185. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  30186. var body1 = null, body2 = null;
  30187. for (var index = 0; index < this._registeredMeshes.length; index++) {
  30188. var registeredMesh = this._registeredMeshes[index];
  30189. if (registeredMesh.mesh === mesh1) {
  30190. body1 = registeredMesh.body;
  30191. if (body2)
  30192. break;
  30193. }
  30194. else if (registeredMesh.mesh === mesh2) {
  30195. body2 = registeredMesh.body;
  30196. if (body1)
  30197. break;
  30198. }
  30199. }
  30200. if (!body1 || !body2) {
  30201. return false;
  30202. }
  30203. 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));
  30204. this._world.addConstraint(constraint);
  30205. return true;
  30206. };
  30207. CannonJSPlugin.prototype.dispose = function () {
  30208. while (this._registeredMeshes.length) {
  30209. this.unregisterMesh(this._registeredMeshes[0].mesh);
  30210. }
  30211. };
  30212. CannonJSPlugin.prototype.isSupported = function () {
  30213. return window.CANNON !== undefined;
  30214. };
  30215. CannonJSPlugin.prototype.getWorldObject = function () {
  30216. return this._world;
  30217. };
  30218. CannonJSPlugin.prototype.getPhysicsBodyOfMesh = function (mesh) {
  30219. for (var index = 0; index < this._registeredMeshes.length; index++) {
  30220. var registeredMesh = this._registeredMeshes[index];
  30221. if (registeredMesh.mesh === mesh) {
  30222. return registeredMesh.body;
  30223. }
  30224. }
  30225. return null;
  30226. };
  30227. return CannonJSPlugin;
  30228. })();
  30229. BABYLON.CannonJSPlugin = CannonJSPlugin;
  30230. })(BABYLON || (BABYLON = {}));
  30231. var BABYLON;
  30232. (function (BABYLON) {
  30233. var OimoJSPlugin = (function () {
  30234. function OimoJSPlugin() {
  30235. this._registeredMeshes = [];
  30236. this.name = "oimo";
  30237. /**
  30238. * Update the body position according to the mesh position
  30239. * @param mesh
  30240. */
  30241. this.updateBodyPosition = function (mesh) {
  30242. for (var index = 0; index < this._registeredMeshes.length; index++) {
  30243. var registeredMesh = this._registeredMeshes[index];
  30244. var body = registeredMesh.body.body;
  30245. var updated = false;
  30246. var newPosition;
  30247. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  30248. mesh.computeWorldMatrix(true);
  30249. newPosition = mesh.getBoundingInfo().boundingBox.center;
  30250. updated = true;
  30251. }
  30252. else if (registeredMesh.mesh.parent === mesh) {
  30253. mesh.computeWorldMatrix(true);
  30254. registeredMesh.mesh.computeWorldMatrix(true);
  30255. newPosition = registeredMesh.mesh.getAbsolutePosition();
  30256. updated = true;
  30257. }
  30258. if (updated) {
  30259. body.setPosition(new OIMO.Vec3(newPosition.x, newPosition.y, newPosition.z));
  30260. body.setQuaternion(mesh.rotationQuaternion);
  30261. body.sleeping = false;
  30262. //force Oimo to update the body's position
  30263. body.updatePosition(1);
  30264. }
  30265. }
  30266. };
  30267. }
  30268. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  30269. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  30270. };
  30271. OimoJSPlugin.prototype.initialize = function (iterations) {
  30272. this._world = new OIMO.World(null, null, iterations);
  30273. this._world.clear();
  30274. };
  30275. OimoJSPlugin.prototype.setGravity = function (gravity) {
  30276. this._gravity = this._world.gravity = gravity;
  30277. };
  30278. OimoJSPlugin.prototype.getGravity = function () {
  30279. return this._gravity;
  30280. };
  30281. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  30282. this.unregisterMesh(mesh);
  30283. if (!mesh.rotationQuaternion) {
  30284. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  30285. }
  30286. mesh.computeWorldMatrix(true);
  30287. var bbox = mesh.getBoundingInfo().boundingBox;
  30288. // The delta between the mesh position and the mesh bounding box center
  30289. var deltaPosition = mesh.position.subtract(bbox.center);
  30290. //calculate rotation to fit Oimo's needs (Euler...)
  30291. var rot = new OIMO.Euler().setFromQuaternion({ x: mesh.rotationQuaternion.x, y: mesh.rotationQuaternion.y, z: mesh.rotationQuaternion.z, s: mesh.rotationQuaternion.w });
  30292. //get the correct bounding box
  30293. var oldQuaternion = mesh.rotationQuaternion;
  30294. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  30295. mesh.computeWorldMatrix(true);
  30296. var bodyConfig = {
  30297. name: mesh.uniqueId,
  30298. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  30299. rot: [rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD],
  30300. move: options.mass != 0,
  30301. config: [options.mass, options.friction, options.restitution],
  30302. world: this._world
  30303. };
  30304. // register mesh
  30305. switch (impostor) {
  30306. case BABYLON.PhysicsEngine.SphereImpostor:
  30307. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  30308. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  30309. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  30310. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  30311. bodyConfig.type = 'sphere';
  30312. bodyConfig.size = [size];
  30313. break;
  30314. case BABYLON.PhysicsEngine.PlaneImpostor:
  30315. //Oimo "fakes" a cylinder as a box, so why don't we!
  30316. case BABYLON.PhysicsEngine.CylinderImpostor:
  30317. case BABYLON.PhysicsEngine.BoxImpostor:
  30318. var min = bbox.minimumWorld;
  30319. var max = bbox.maximumWorld;
  30320. var box = max.subtract(min);
  30321. var sizeX = this._checkWithEpsilon(box.x);
  30322. var sizeY = this._checkWithEpsilon(box.y);
  30323. var sizeZ = this._checkWithEpsilon(box.z);
  30324. bodyConfig.type = 'box';
  30325. bodyConfig.size = [sizeX, sizeY, sizeZ];
  30326. break;
  30327. }
  30328. var body = new OIMO.Body(bodyConfig);
  30329. //We have to access the rigid body's properties to set the quaternion.
  30330. //The setQuaternion function of Oimo only sets the newOrientation that is only set after an impulse is given or a collision.
  30331. //body.body.orientation = new OIMO.Quat(mesh.rotationQuaternion.w, mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z);
  30332. //TEST
  30333. //body.body.resetQuaternion(new OIMO.Quat(mesh.rotationQuaternion.w, mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z));
  30334. //update the internal rotation matrix
  30335. //body.body.syncShapes();
  30336. this._registeredMeshes.push({
  30337. mesh: mesh,
  30338. body: body,
  30339. delta: deltaPosition
  30340. });
  30341. //for the sake of consistency.
  30342. mesh.rotationQuaternion = oldQuaternion;
  30343. return body;
  30344. };
  30345. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  30346. var types = [], sizes = [], positions = [], rotations = [];
  30347. var initialMesh = parts[0].mesh;
  30348. for (var index = 0; index < parts.length; index++) {
  30349. var part = parts[index];
  30350. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  30351. types.push(bodyParameters.type);
  30352. sizes.push.apply(sizes, bodyParameters.size);
  30353. positions.push.apply(positions, bodyParameters.pos);
  30354. rotations.push.apply(rotations, bodyParameters.rot);
  30355. }
  30356. var body = new OIMO.Body({
  30357. name: initialMesh.uniqueId,
  30358. type: types,
  30359. size: sizes,
  30360. pos: positions,
  30361. rot: rotations,
  30362. move: options.mass != 0,
  30363. config: [options.mass, options.friction, options.restitution],
  30364. world: this._world
  30365. });
  30366. //Reset the body's rotation to be of the initial mesh's.
  30367. var rot = new OIMO.Euler().setFromQuaternion({ x: initialMesh.rotationQuaternion.x, y: initialMesh.rotationQuaternion.y, z: initialMesh.rotationQuaternion.z, s: initialMesh.rotationQuaternion.w });
  30368. body.resetRotation(rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD);
  30369. this._registeredMeshes.push({
  30370. mesh: initialMesh,
  30371. body: body
  30372. });
  30373. return body;
  30374. };
  30375. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  30376. var mesh = part.mesh;
  30377. if (!mesh.rotationQuaternion) {
  30378. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  30379. }
  30380. // We need the bounding box/sphere info to compute the physics body
  30381. mesh.computeWorldMatrix(true);
  30382. var rot = new OIMO.Euler().setFromQuaternion({ x: mesh.rotationQuaternion.x, y: mesh.rotationQuaternion.y, z: mesh.rotationQuaternion.z, s: mesh.rotationQuaternion.w });
  30383. var bodyParameters = {
  30384. name: mesh.uniqueId,
  30385. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  30386. //A bug in Oimo (Body class) prevents us from using rot directly.
  30387. rot: [0, 0, 0],
  30388. //For future reference, if the bug will ever be fixed.
  30389. realRot: [rot.x / OIMO.TO_RAD, rot.y / OIMO.TO_RAD, rot.z / OIMO.TO_RAD]
  30390. };
  30391. var oldQuaternion = mesh.rotationQuaternion;
  30392. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  30393. mesh.computeWorldMatrix(true);
  30394. switch (part.impostor) {
  30395. case BABYLON.PhysicsEngine.SphereImpostor:
  30396. var bbox = mesh.getBoundingInfo().boundingBox;
  30397. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  30398. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  30399. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  30400. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  30401. bodyParameters.type = 'sphere';
  30402. bodyParameters.size = [size, size, size];
  30403. break;
  30404. case BABYLON.PhysicsEngine.PlaneImpostor:
  30405. case BABYLON.PhysicsEngine.CylinderImpostor:
  30406. case BABYLON.PhysicsEngine.BoxImpostor:
  30407. bbox = mesh.getBoundingInfo().boundingBox;
  30408. var min = bbox.minimumWorld;
  30409. var max = bbox.maximumWorld;
  30410. var box = max.subtract(min);
  30411. var sizeX = this._checkWithEpsilon(box.x);
  30412. var sizeY = this._checkWithEpsilon(box.y);
  30413. var sizeZ = this._checkWithEpsilon(box.z);
  30414. bodyParameters.type = 'box';
  30415. bodyParameters.size = [sizeX, sizeY, sizeZ];
  30416. break;
  30417. }
  30418. mesh.rotationQuaternion = oldQuaternion;
  30419. return bodyParameters;
  30420. };
  30421. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  30422. for (var index = 0; index < this._registeredMeshes.length; index++) {
  30423. var registeredMesh = this._registeredMeshes[index];
  30424. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  30425. if (registeredMesh.body) {
  30426. this._world.removeRigidBody(registeredMesh.body.body);
  30427. this._unbindBody(registeredMesh.body);
  30428. }
  30429. this._registeredMeshes.splice(index, 1);
  30430. return;
  30431. }
  30432. }
  30433. };
  30434. OimoJSPlugin.prototype._unbindBody = function (body) {
  30435. for (var index = 0; index < this._registeredMeshes.length; index++) {
  30436. var registeredMesh = this._registeredMeshes[index];
  30437. if (registeredMesh.body === body) {
  30438. registeredMesh.body = null;
  30439. }
  30440. }
  30441. };
  30442. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  30443. for (var index = 0; index < this._registeredMeshes.length; index++) {
  30444. var registeredMesh = this._registeredMeshes[index];
  30445. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  30446. // Get object mass to have a behaviour similar to cannon.js
  30447. var mass = registeredMesh.body.body.massInfo.mass;
  30448. // The force is scaled with the mass of object
  30449. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  30450. return;
  30451. }
  30452. }
  30453. };
  30454. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  30455. var body1 = null, body2 = null;
  30456. for (var index = 0; index < this._registeredMeshes.length; index++) {
  30457. var registeredMesh = this._registeredMeshes[index];
  30458. if (registeredMesh.mesh === mesh1) {
  30459. body1 = registeredMesh.body.body;
  30460. }
  30461. else if (registeredMesh.mesh === mesh2) {
  30462. body2 = registeredMesh.body.body;
  30463. }
  30464. }
  30465. if (!body1 || !body2) {
  30466. return false;
  30467. }
  30468. if (!options) {
  30469. options = {};
  30470. }
  30471. new OIMO.Link({
  30472. type: options.type,
  30473. body1: body1,
  30474. body2: body2,
  30475. min: options.min,
  30476. max: options.max,
  30477. axe1: options.axe1,
  30478. axe2: options.axe2,
  30479. pos1: [pivot1.x, pivot1.y, pivot1.z],
  30480. pos2: [pivot2.x, pivot2.y, pivot2.z],
  30481. collision: options.collision,
  30482. spring: options.spring,
  30483. world: this._world
  30484. });
  30485. return true;
  30486. };
  30487. OimoJSPlugin.prototype.dispose = function () {
  30488. this._world.clear();
  30489. while (this._registeredMeshes.length) {
  30490. this.unregisterMesh(this._registeredMeshes[0].mesh);
  30491. }
  30492. };
  30493. OimoJSPlugin.prototype.isSupported = function () {
  30494. return OIMO !== undefined;
  30495. };
  30496. OimoJSPlugin.prototype.getWorldObject = function () {
  30497. return this._world;
  30498. };
  30499. OimoJSPlugin.prototype.getPhysicsBodyOfMesh = function (mesh) {
  30500. for (var index = 0; index < this._registeredMeshes.length; index++) {
  30501. var registeredMesh = this._registeredMeshes[index];
  30502. if (registeredMesh.mesh === mesh) {
  30503. return registeredMesh.body;
  30504. }
  30505. }
  30506. return null;
  30507. };
  30508. OimoJSPlugin.prototype._getLastShape = function (body) {
  30509. var lastShape = body.shapes;
  30510. while (lastShape.next) {
  30511. lastShape = lastShape.next;
  30512. }
  30513. return lastShape;
  30514. };
  30515. OimoJSPlugin.prototype.runOneStep = function (time) {
  30516. this._world.step();
  30517. // Update the position of all registered meshes
  30518. var i = this._registeredMeshes.length;
  30519. var m;
  30520. while (i--) {
  30521. var body = this._registeredMeshes[i].body.body;
  30522. var mesh = this._registeredMeshes[i].mesh;
  30523. if (!this._registeredMeshes[i].delta) {
  30524. this._registeredMeshes[i].delta = BABYLON.Vector3.Zero();
  30525. }
  30526. if (!body.sleeping) {
  30527. //TODO check that
  30528. if (body.shapes.next) {
  30529. var parentShape = this._getLastShape(body);
  30530. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  30531. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  30532. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  30533. }
  30534. else {
  30535. mesh.position.copyFrom(body.getPosition()).addInPlace(this._registeredMeshes[i].delta);
  30536. }
  30537. mesh.rotationQuaternion.copyFrom(body.getQuaternion());
  30538. mesh.computeWorldMatrix();
  30539. }
  30540. //check if the collide callback is set.
  30541. if (mesh.onPhysicsCollide) {
  30542. var meshUniqueName = mesh.uniqueId;
  30543. var contact = this._world.contacts;
  30544. while (contact !== null) {
  30545. //is this body colliding with any other?
  30546. if ((contact.body1.name == mesh.uniqueId || contact.body2.name == mesh.uniqueId) && contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  30547. var otherUniqueId = contact.body1.name == mesh.uniqueId ? contact.body2.name : contact.body1.name;
  30548. //get the mesh and execute the callback
  30549. var otherMesh = mesh.getScene().getMeshByUniqueID(otherUniqueId);
  30550. if (otherMesh)
  30551. mesh.onPhysicsCollide(otherMesh, contact);
  30552. }
  30553. contact = contact.next;
  30554. }
  30555. }
  30556. }
  30557. };
  30558. return OimoJSPlugin;
  30559. })();
  30560. BABYLON.OimoJSPlugin = OimoJSPlugin;
  30561. })(BABYLON || (BABYLON = {}));
  30562. var BABYLON;
  30563. (function (BABYLON) {
  30564. var DisplayPassPostProcess = (function (_super) {
  30565. __extends(DisplayPassPostProcess, _super);
  30566. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  30567. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  30568. }
  30569. return DisplayPassPostProcess;
  30570. })(BABYLON.PostProcess);
  30571. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  30572. })(BABYLON || (BABYLON = {}));
  30573. var BABYLON;
  30574. (function (BABYLON) {
  30575. var SimplificationSettings = (function () {
  30576. function SimplificationSettings(quality, distance, optimizeMesh) {
  30577. this.quality = quality;
  30578. this.distance = distance;
  30579. this.optimizeMesh = optimizeMesh;
  30580. }
  30581. return SimplificationSettings;
  30582. })();
  30583. BABYLON.SimplificationSettings = SimplificationSettings;
  30584. var SimplificationQueue = (function () {
  30585. function SimplificationQueue() {
  30586. this.running = false;
  30587. this._simplificationArray = [];
  30588. }
  30589. SimplificationQueue.prototype.addTask = function (task) {
  30590. this._simplificationArray.push(task);
  30591. };
  30592. SimplificationQueue.prototype.executeNext = function () {
  30593. var task = this._simplificationArray.pop();
  30594. if (task) {
  30595. this.running = true;
  30596. this.runSimplification(task);
  30597. }
  30598. else {
  30599. this.running = false;
  30600. }
  30601. };
  30602. SimplificationQueue.prototype.runSimplification = function (task) {
  30603. var _this = this;
  30604. if (task.parallelProcessing) {
  30605. //parallel simplifier
  30606. task.settings.forEach(function (setting) {
  30607. var simplifier = _this.getSimplifier(task);
  30608. simplifier.simplify(setting, function (newMesh) {
  30609. task.mesh.addLODLevel(setting.distance, newMesh);
  30610. newMesh.isVisible = true;
  30611. //check if it is the last
  30612. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  30613. //all done, run the success callback.
  30614. task.successCallback();
  30615. }
  30616. _this.executeNext();
  30617. });
  30618. });
  30619. }
  30620. else {
  30621. //single simplifier.
  30622. var simplifier = this.getSimplifier(task);
  30623. var runDecimation = function (setting, callback) {
  30624. simplifier.simplify(setting, function (newMesh) {
  30625. task.mesh.addLODLevel(setting.distance, newMesh);
  30626. newMesh.isVisible = true;
  30627. //run the next quality level
  30628. callback();
  30629. });
  30630. };
  30631. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  30632. runDecimation(task.settings[loop.index], function () {
  30633. loop.executeNext();
  30634. });
  30635. }, function () {
  30636. //execution ended, run the success callback.
  30637. if (task.successCallback) {
  30638. task.successCallback();
  30639. }
  30640. _this.executeNext();
  30641. });
  30642. }
  30643. };
  30644. SimplificationQueue.prototype.getSimplifier = function (task) {
  30645. switch (task.simplificationType) {
  30646. case SimplificationType.QUADRATIC:
  30647. default:
  30648. return new QuadraticErrorSimplification(task.mesh);
  30649. }
  30650. };
  30651. return SimplificationQueue;
  30652. })();
  30653. BABYLON.SimplificationQueue = SimplificationQueue;
  30654. /**
  30655. * The implemented types of simplification.
  30656. * At the moment only Quadratic Error Decimation is implemented.
  30657. */
  30658. (function (SimplificationType) {
  30659. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  30660. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  30661. var SimplificationType = BABYLON.SimplificationType;
  30662. var DecimationTriangle = (function () {
  30663. function DecimationTriangle(vertices) {
  30664. this.vertices = vertices;
  30665. this.error = new Array(4);
  30666. this.deleted = false;
  30667. this.isDirty = false;
  30668. this.deletePending = false;
  30669. this.borderFactor = 0;
  30670. }
  30671. return DecimationTriangle;
  30672. })();
  30673. BABYLON.DecimationTriangle = DecimationTriangle;
  30674. var DecimationVertex = (function () {
  30675. function DecimationVertex(position, id) {
  30676. this.position = position;
  30677. this.id = id;
  30678. this.isBorder = true;
  30679. this.q = new QuadraticMatrix();
  30680. this.triangleCount = 0;
  30681. this.triangleStart = 0;
  30682. this.originalOffsets = [];
  30683. }
  30684. DecimationVertex.prototype.updatePosition = function (newPosition) {
  30685. this.position.copyFrom(newPosition);
  30686. };
  30687. return DecimationVertex;
  30688. })();
  30689. BABYLON.DecimationVertex = DecimationVertex;
  30690. var QuadraticMatrix = (function () {
  30691. function QuadraticMatrix(data) {
  30692. this.data = new Array(10);
  30693. for (var i = 0; i < 10; ++i) {
  30694. if (data && data[i]) {
  30695. this.data[i] = data[i];
  30696. }
  30697. else {
  30698. this.data[i] = 0;
  30699. }
  30700. }
  30701. }
  30702. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  30703. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  30704. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  30705. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  30706. return det;
  30707. };
  30708. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  30709. for (var i = 0; i < 10; ++i) {
  30710. this.data[i] += matrix.data[i];
  30711. }
  30712. };
  30713. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  30714. for (var i = 0; i < 10; ++i) {
  30715. this.data[i] += data[i];
  30716. }
  30717. };
  30718. QuadraticMatrix.prototype.add = function (matrix) {
  30719. var m = new QuadraticMatrix();
  30720. for (var i = 0; i < 10; ++i) {
  30721. m.data[i] = this.data[i] + matrix.data[i];
  30722. }
  30723. return m;
  30724. };
  30725. QuadraticMatrix.FromData = function (a, b, c, d) {
  30726. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  30727. };
  30728. //returning an array to avoid garbage collection
  30729. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  30730. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  30731. };
  30732. return QuadraticMatrix;
  30733. })();
  30734. BABYLON.QuadraticMatrix = QuadraticMatrix;
  30735. var Reference = (function () {
  30736. function Reference(vertexId, triangleId) {
  30737. this.vertexId = vertexId;
  30738. this.triangleId = triangleId;
  30739. }
  30740. return Reference;
  30741. })();
  30742. BABYLON.Reference = Reference;
  30743. /**
  30744. * An implementation of the Quadratic Error simplification algorithm.
  30745. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  30746. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  30747. * @author RaananW
  30748. */
  30749. var QuadraticErrorSimplification = (function () {
  30750. function QuadraticErrorSimplification(_mesh) {
  30751. this._mesh = _mesh;
  30752. this.initialized = false;
  30753. this.syncIterations = 5000;
  30754. this.aggressiveness = 7;
  30755. this.decimationIterations = 100;
  30756. this.boundingBoxEpsilon = BABYLON.Engine.Epsilon;
  30757. }
  30758. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  30759. var _this = this;
  30760. this.initDecimatedMesh();
  30761. //iterating through the submeshes array, one after the other.
  30762. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  30763. _this.initWithMesh(loop.index, function () {
  30764. _this.runDecimation(settings, loop.index, function () {
  30765. loop.executeNext();
  30766. });
  30767. }, settings.optimizeMesh);
  30768. }, function () {
  30769. setTimeout(function () {
  30770. successCallback(_this._reconstructedMesh);
  30771. }, 0);
  30772. });
  30773. };
  30774. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  30775. var _this = this;
  30776. var gCount = 0;
  30777. triangle.vertices.forEach(function (vertex) {
  30778. var count = 0;
  30779. var vPos = vertex.position;
  30780. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  30781. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  30782. ++count;
  30783. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  30784. ++count;
  30785. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  30786. ++count;
  30787. if (count > 1) {
  30788. ++gCount;
  30789. }
  30790. ;
  30791. });
  30792. if (gCount > 1) {
  30793. console.log(triangle, gCount);
  30794. }
  30795. return gCount > 1;
  30796. };
  30797. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  30798. var _this = this;
  30799. var targetCount = ~~(this.triangles.length * settings.quality);
  30800. var deletedTriangles = 0;
  30801. var triangleCount = this.triangles.length;
  30802. var iterationFunction = function (iteration, callback) {
  30803. setTimeout(function () {
  30804. if (iteration % 5 === 0) {
  30805. _this.updateMesh(iteration === 0);
  30806. }
  30807. for (var i = 0; i < _this.triangles.length; ++i) {
  30808. _this.triangles[i].isDirty = false;
  30809. }
  30810. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  30811. var trianglesIterator = function (i) {
  30812. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  30813. var t = _this.triangles[tIdx];
  30814. if (!t)
  30815. return;
  30816. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  30817. return;
  30818. }
  30819. for (var j = 0; j < 3; ++j) {
  30820. if (t.error[j] < threshold) {
  30821. var deleted0 = [];
  30822. var deleted1 = [];
  30823. var v0 = t.vertices[j];
  30824. var v1 = t.vertices[(j + 1) % 3];
  30825. if (v0.isBorder !== v1.isBorder)
  30826. continue;
  30827. var p = BABYLON.Vector3.Zero();
  30828. var n = BABYLON.Vector3.Zero();
  30829. var uv = BABYLON.Vector2.Zero();
  30830. var color = new BABYLON.Color4(0, 0, 0, 1);
  30831. _this.calculateError(v0, v1, p, n, uv, color);
  30832. var delTr = [];
  30833. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  30834. continue;
  30835. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  30836. continue;
  30837. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  30838. continue;
  30839. var uniqueArray = [];
  30840. delTr.forEach(function (deletedT) {
  30841. if (uniqueArray.indexOf(deletedT) === -1) {
  30842. deletedT.deletePending = true;
  30843. uniqueArray.push(deletedT);
  30844. }
  30845. });
  30846. if (uniqueArray.length % 2 !== 0) {
  30847. continue;
  30848. }
  30849. v0.q = v1.q.add(v0.q);
  30850. v0.updatePosition(p);
  30851. var tStart = _this.references.length;
  30852. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  30853. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  30854. var tCount = _this.references.length - tStart;
  30855. if (tCount <= v0.triangleCount) {
  30856. if (tCount) {
  30857. for (var c = 0; c < tCount; c++) {
  30858. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  30859. }
  30860. }
  30861. }
  30862. else {
  30863. v0.triangleStart = tStart;
  30864. }
  30865. v0.triangleCount = tCount;
  30866. break;
  30867. }
  30868. }
  30869. };
  30870. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  30871. }, 0);
  30872. };
  30873. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  30874. if (triangleCount - deletedTriangles <= targetCount)
  30875. loop.breakLoop();
  30876. else {
  30877. iterationFunction(loop.index, function () {
  30878. loop.executeNext();
  30879. });
  30880. }
  30881. }, function () {
  30882. setTimeout(function () {
  30883. //reconstruct this part of the mesh
  30884. _this.reconstructMesh(submeshIndex);
  30885. successCallback();
  30886. }, 0);
  30887. });
  30888. };
  30889. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  30890. var _this = this;
  30891. this.vertices = [];
  30892. this.triangles = [];
  30893. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30894. var indices = this._mesh.getIndices();
  30895. var submesh = this._mesh.subMeshes[submeshIndex];
  30896. var findInVertices = function (positionToSearch) {
  30897. if (optimizeMesh) {
  30898. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  30899. if (_this.vertices[ii].position.equals(positionToSearch)) {
  30900. return _this.vertices[ii];
  30901. }
  30902. }
  30903. }
  30904. return null;
  30905. };
  30906. var vertexReferences = [];
  30907. var vertexInit = function (i) {
  30908. var offset = i + submesh.verticesStart;
  30909. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  30910. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  30911. vertex.originalOffsets.push(offset);
  30912. if (vertex.id === _this.vertices.length) {
  30913. _this.vertices.push(vertex);
  30914. }
  30915. vertexReferences.push(vertex.id);
  30916. };
  30917. //var totalVertices = mesh.getTotalVertices();
  30918. var totalVertices = submesh.verticesCount;
  30919. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  30920. var indicesInit = function (i) {
  30921. var offset = (submesh.indexStart / 3) + i;
  30922. var pos = (offset * 3);
  30923. var i0 = indices[pos + 0];
  30924. var i1 = indices[pos + 1];
  30925. var i2 = indices[pos + 2];
  30926. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  30927. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  30928. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  30929. var triangle = new DecimationTriangle([v0, v1, v2]);
  30930. triangle.originalOffset = pos;
  30931. _this.triangles.push(triangle);
  30932. };
  30933. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  30934. _this.init(callback);
  30935. });
  30936. });
  30937. };
  30938. QuadraticErrorSimplification.prototype.init = function (callback) {
  30939. var _this = this;
  30940. var triangleInit1 = function (i) {
  30941. var t = _this.triangles[i];
  30942. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  30943. for (var j = 0; j < 3; j++) {
  30944. 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))));
  30945. }
  30946. };
  30947. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  30948. var triangleInit2 = function (i) {
  30949. var t = _this.triangles[i];
  30950. for (var j = 0; j < 3; ++j) {
  30951. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  30952. }
  30953. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  30954. };
  30955. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  30956. _this.initialized = true;
  30957. callback();
  30958. });
  30959. });
  30960. };
  30961. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  30962. var newTriangles = [];
  30963. var i;
  30964. for (i = 0; i < this.vertices.length; ++i) {
  30965. this.vertices[i].triangleCount = 0;
  30966. }
  30967. var t;
  30968. var j;
  30969. for (i = 0; i < this.triangles.length; ++i) {
  30970. if (!this.triangles[i].deleted) {
  30971. t = this.triangles[i];
  30972. for (j = 0; j < 3; ++j) {
  30973. t.vertices[j].triangleCount = 1;
  30974. }
  30975. newTriangles.push(t);
  30976. }
  30977. }
  30978. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  30979. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  30980. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  30981. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  30982. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30983. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  30984. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  30985. var vertexCount = 0;
  30986. for (i = 0; i < this.vertices.length; ++i) {
  30987. var vertex = this.vertices[i];
  30988. vertex.id = vertexCount;
  30989. if (vertex.triangleCount) {
  30990. vertex.originalOffsets.forEach(function (originalOffset) {
  30991. newPositionData.push(vertex.position.x);
  30992. newPositionData.push(vertex.position.y);
  30993. newPositionData.push(vertex.position.z);
  30994. newNormalData.push(normalData[originalOffset * 3]);
  30995. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  30996. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  30997. if (uvs && uvs.length) {
  30998. newUVsData.push(uvs[(originalOffset * 2)]);
  30999. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  31000. }
  31001. else if (colorsData && colorsData.length) {
  31002. newColorsData.push(colorsData[(originalOffset * 4)]);
  31003. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  31004. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  31005. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  31006. }
  31007. ++vertexCount;
  31008. });
  31009. }
  31010. }
  31011. var startingIndex = this._reconstructedMesh.getTotalIndices();
  31012. var startingVertex = this._reconstructedMesh.getTotalVertices();
  31013. var submeshesArray = this._reconstructedMesh.subMeshes;
  31014. this._reconstructedMesh.subMeshes = [];
  31015. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  31016. var originalIndices = this._mesh.getIndices();
  31017. for (i = 0; i < newTriangles.length; ++i) {
  31018. t = newTriangles[i]; //now get the new referencing point for each vertex
  31019. [0, 1, 2].forEach(function (idx) {
  31020. var id = originalIndices[t.originalOffset + idx];
  31021. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  31022. if (offset < 0)
  31023. offset = 0;
  31024. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  31025. });
  31026. }
  31027. //overwriting the old vertex buffers and indices.
  31028. this._reconstructedMesh.setIndices(newIndicesArray);
  31029. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  31030. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  31031. if (newUVsData.length > 0)
  31032. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  31033. if (newColorsData.length > 0)
  31034. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  31035. //create submesh
  31036. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  31037. if (submeshIndex > 0) {
  31038. this._reconstructedMesh.subMeshes = [];
  31039. submeshesArray.forEach(function (submesh) {
  31040. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  31041. });
  31042. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  31043. }
  31044. };
  31045. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  31046. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  31047. this._reconstructedMesh.material = this._mesh.material;
  31048. this._reconstructedMesh.parent = this._mesh.parent;
  31049. this._reconstructedMesh.isVisible = false;
  31050. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  31051. };
  31052. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  31053. for (var i = 0; i < vertex1.triangleCount; ++i) {
  31054. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  31055. if (t.deleted)
  31056. continue;
  31057. var s = this.references[vertex1.triangleStart + i].vertexId;
  31058. var v1 = t.vertices[(s + 1) % 3];
  31059. var v2 = t.vertices[(s + 2) % 3];
  31060. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  31061. deletedArray[i] = true;
  31062. delTr.push(t);
  31063. continue;
  31064. }
  31065. var d1 = v1.position.subtract(point);
  31066. d1 = d1.normalize();
  31067. var d2 = v2.position.subtract(point);
  31068. d2 = d2.normalize();
  31069. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  31070. return true;
  31071. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  31072. deletedArray[i] = false;
  31073. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  31074. return true;
  31075. }
  31076. return false;
  31077. };
  31078. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  31079. var newDeleted = deletedTriangles;
  31080. for (var i = 0; i < vertex.triangleCount; ++i) {
  31081. var ref = this.references[vertex.triangleStart + i];
  31082. var t = this.triangles[ref.triangleId];
  31083. if (t.deleted)
  31084. continue;
  31085. if (deletedArray[i] && t.deletePending) {
  31086. t.deleted = true;
  31087. newDeleted++;
  31088. continue;
  31089. }
  31090. t.vertices[ref.vertexId] = origVertex;
  31091. t.isDirty = true;
  31092. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  31093. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  31094. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  31095. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  31096. this.references.push(ref);
  31097. }
  31098. return newDeleted;
  31099. };
  31100. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  31101. for (var i = 0; i < this.vertices.length; ++i) {
  31102. var vCount = [];
  31103. var vId = [];
  31104. var v = this.vertices[i];
  31105. var j;
  31106. for (j = 0; j < v.triangleCount; ++j) {
  31107. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  31108. for (var ii = 0; ii < 3; ii++) {
  31109. var ofs = 0;
  31110. var vv = triangle.vertices[ii];
  31111. while (ofs < vCount.length) {
  31112. if (vId[ofs] === vv.id)
  31113. break;
  31114. ++ofs;
  31115. }
  31116. if (ofs === vCount.length) {
  31117. vCount.push(1);
  31118. vId.push(vv.id);
  31119. }
  31120. else {
  31121. vCount[ofs]++;
  31122. }
  31123. }
  31124. }
  31125. for (j = 0; j < vCount.length; ++j) {
  31126. if (vCount[j] === 1) {
  31127. this.vertices[vId[j]].isBorder = true;
  31128. }
  31129. else {
  31130. this.vertices[vId[j]].isBorder = false;
  31131. }
  31132. }
  31133. }
  31134. };
  31135. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  31136. if (identifyBorders === void 0) { identifyBorders = false; }
  31137. var i;
  31138. if (!identifyBorders) {
  31139. var newTrianglesVector = [];
  31140. for (i = 0; i < this.triangles.length; ++i) {
  31141. if (!this.triangles[i].deleted) {
  31142. newTrianglesVector.push(this.triangles[i]);
  31143. }
  31144. }
  31145. this.triangles = newTrianglesVector;
  31146. }
  31147. for (i = 0; i < this.vertices.length; ++i) {
  31148. this.vertices[i].triangleCount = 0;
  31149. this.vertices[i].triangleStart = 0;
  31150. }
  31151. var t;
  31152. var j;
  31153. var v;
  31154. for (i = 0; i < this.triangles.length; ++i) {
  31155. t = this.triangles[i];
  31156. for (j = 0; j < 3; ++j) {
  31157. v = t.vertices[j];
  31158. v.triangleCount++;
  31159. }
  31160. }
  31161. var tStart = 0;
  31162. for (i = 0; i < this.vertices.length; ++i) {
  31163. this.vertices[i].triangleStart = tStart;
  31164. tStart += this.vertices[i].triangleCount;
  31165. this.vertices[i].triangleCount = 0;
  31166. }
  31167. var newReferences = new Array(this.triangles.length * 3);
  31168. for (i = 0; i < this.triangles.length; ++i) {
  31169. t = this.triangles[i];
  31170. for (j = 0; j < 3; ++j) {
  31171. v = t.vertices[j];
  31172. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  31173. v.triangleCount++;
  31174. }
  31175. }
  31176. this.references = newReferences;
  31177. if (identifyBorders) {
  31178. this.identifyBorder();
  31179. }
  31180. };
  31181. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  31182. var x = point.x;
  31183. var y = point.y;
  31184. var z = point.z;
  31185. 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
  31186. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  31187. };
  31188. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  31189. var q = vertex1.q.add(vertex2.q);
  31190. var border = vertex1.isBorder && vertex2.isBorder;
  31191. var error = 0;
  31192. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  31193. if (qDet !== 0 && !border) {
  31194. if (!pointResult) {
  31195. pointResult = BABYLON.Vector3.Zero();
  31196. }
  31197. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  31198. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  31199. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  31200. error = this.vertexError(q, pointResult);
  31201. }
  31202. else {
  31203. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  31204. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  31205. var error1 = this.vertexError(q, vertex1.position);
  31206. var error2 = this.vertexError(q, vertex2.position);
  31207. var error3 = this.vertexError(q, p3);
  31208. error = Math.min(error1, error2, error3);
  31209. if (error === error1) {
  31210. if (pointResult) {
  31211. pointResult.copyFrom(vertex1.position);
  31212. }
  31213. }
  31214. else if (error === error2) {
  31215. if (pointResult) {
  31216. pointResult.copyFrom(vertex2.position);
  31217. }
  31218. }
  31219. else {
  31220. if (pointResult) {
  31221. pointResult.copyFrom(p3);
  31222. }
  31223. }
  31224. }
  31225. return error;
  31226. };
  31227. return QuadraticErrorSimplification;
  31228. })();
  31229. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  31230. })(BABYLON || (BABYLON = {}));
  31231. var BABYLON;
  31232. (function (BABYLON) {
  31233. var serializedGeometries = [];
  31234. var serializeGeometry = function (geometry, serializationGeometries) {
  31235. if (serializedGeometries[geometry.id]) {
  31236. return;
  31237. }
  31238. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  31239. serializationGeometries.boxes.push(geometry.serialize());
  31240. }
  31241. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  31242. serializationGeometries.spheres.push(geometry.serialize());
  31243. }
  31244. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  31245. serializationGeometries.cylinders.push(geometry.serialize());
  31246. }
  31247. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  31248. serializationGeometries.toruses.push(geometry.serialize());
  31249. }
  31250. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  31251. serializationGeometries.grounds.push(geometry.serialize());
  31252. }
  31253. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  31254. serializationGeometries.planes.push(geometry.serialize());
  31255. }
  31256. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  31257. serializationGeometries.torusKnots.push(geometry.serialize());
  31258. }
  31259. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  31260. throw new Error("Unknown primitive type");
  31261. }
  31262. else {
  31263. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  31264. }
  31265. serializedGeometries[geometry.id] = true;
  31266. };
  31267. var serializeMesh = function (mesh, serializationScene) {
  31268. var serializationObject = {};
  31269. serializationObject.name = mesh.name;
  31270. serializationObject.id = mesh.id;
  31271. if (BABYLON.Tags.HasTags(mesh)) {
  31272. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  31273. }
  31274. serializationObject.position = mesh.position.asArray();
  31275. if (mesh.rotationQuaternion) {
  31276. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  31277. }
  31278. else if (mesh.rotation) {
  31279. serializationObject.rotation = mesh.rotation.asArray();
  31280. }
  31281. serializationObject.scaling = mesh.scaling.asArray();
  31282. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  31283. serializationObject.isEnabled = mesh.isEnabled();
  31284. serializationObject.isVisible = mesh.isVisible;
  31285. serializationObject.infiniteDistance = mesh.infiniteDistance;
  31286. serializationObject.pickable = mesh.isPickable;
  31287. serializationObject.receiveShadows = mesh.receiveShadows;
  31288. serializationObject.billboardMode = mesh.billboardMode;
  31289. serializationObject.visibility = mesh.visibility;
  31290. serializationObject.checkCollisions = mesh.checkCollisions;
  31291. // Parent
  31292. if (mesh.parent) {
  31293. serializationObject.parentId = mesh.parent.id;
  31294. }
  31295. // Geometry
  31296. var geometry = mesh._geometry;
  31297. if (geometry) {
  31298. var geometryId = geometry.id;
  31299. serializationObject.geometryId = geometryId;
  31300. if (!mesh.getScene().getGeometryByID(geometryId)) {
  31301. // 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
  31302. serializeGeometry(geometry, serializationScene.geometries);
  31303. }
  31304. // SubMeshes
  31305. serializationObject.subMeshes = [];
  31306. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  31307. var subMesh = mesh.subMeshes[subIndex];
  31308. serializationObject.subMeshes.push({
  31309. materialIndex: subMesh.materialIndex,
  31310. verticesStart: subMesh.verticesStart,
  31311. verticesCount: subMesh.verticesCount,
  31312. indexStart: subMesh.indexStart,
  31313. indexCount: subMesh.indexCount
  31314. });
  31315. }
  31316. }
  31317. // Material
  31318. if (mesh.material) {
  31319. serializationObject.materialId = mesh.material.id;
  31320. }
  31321. else {
  31322. mesh.material = null;
  31323. }
  31324. // Skeleton
  31325. if (mesh.skeleton) {
  31326. serializationObject.skeletonId = mesh.skeleton.id;
  31327. }
  31328. // Physics
  31329. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  31330. serializationObject.physicsMass = mesh.getPhysicsMass();
  31331. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  31332. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  31333. switch (mesh.getPhysicsImpostor()) {
  31334. case BABYLON.PhysicsEngine.BoxImpostor:
  31335. serializationObject.physicsImpostor = 1;
  31336. break;
  31337. case BABYLON.PhysicsEngine.SphereImpostor:
  31338. serializationObject.physicsImpostor = 2;
  31339. break;
  31340. }
  31341. }
  31342. // Instances
  31343. serializationObject.instances = [];
  31344. for (var index = 0; index < mesh.instances.length; index++) {
  31345. var instance = mesh.instances[index];
  31346. var serializationInstance = {
  31347. name: instance.name,
  31348. position: instance.position.asArray(),
  31349. scaling: instance.scaling.asArray()
  31350. };
  31351. if (instance.rotationQuaternion) {
  31352. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  31353. }
  31354. else if (instance.rotation) {
  31355. serializationInstance.rotation = instance.rotation.asArray();
  31356. }
  31357. serializationObject.instances.push(serializationInstance);
  31358. // Animations
  31359. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  31360. serializationInstance.ranges = instance.serializeAnimationRanges();
  31361. }
  31362. // Animations
  31363. BABYLON.Animation.AppendSerializedAnimations(mesh, serializationObject);
  31364. serializationObject.ranges = mesh.serializeAnimationRanges();
  31365. // Layer mask
  31366. serializationObject.layerMask = mesh.layerMask;
  31367. return serializationObject;
  31368. };
  31369. var finalizeSingleMesh = function (mesh, serializationObject) {
  31370. //only works if the mesh is already loaded
  31371. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  31372. //serialize material
  31373. if (mesh.material) {
  31374. if (mesh.material instanceof BABYLON.StandardMaterial) {
  31375. serializationObject.materials = serializationObject.materials || [];
  31376. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  31377. serializationObject.materials.push(mesh.material.serialize());
  31378. }
  31379. }
  31380. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  31381. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  31382. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  31383. serializationObject.multiMaterials.push(mesh.material.serialize());
  31384. }
  31385. }
  31386. }
  31387. //serialize geometry
  31388. var geometry = mesh._geometry;
  31389. if (geometry) {
  31390. if (!serializationObject.geometries) {
  31391. serializationObject.geometries = {};
  31392. serializationObject.geometries.boxes = [];
  31393. serializationObject.geometries.spheres = [];
  31394. serializationObject.geometries.cylinders = [];
  31395. serializationObject.geometries.toruses = [];
  31396. serializationObject.geometries.grounds = [];
  31397. serializationObject.geometries.planes = [];
  31398. serializationObject.geometries.torusKnots = [];
  31399. serializationObject.geometries.vertexData = [];
  31400. }
  31401. serializeGeometry(geometry, serializationObject.geometries);
  31402. }
  31403. // Skeletons
  31404. if (mesh.skeleton) {
  31405. serializationObject.skeletons = serializationObject.skeletons || [];
  31406. serializationObject.skeletons.push(mesh.skeleton.serialize());
  31407. }
  31408. //serialize the actual mesh
  31409. serializationObject.meshes = serializationObject.meshes || [];
  31410. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  31411. }
  31412. };
  31413. var SceneSerializer = (function () {
  31414. function SceneSerializer() {
  31415. }
  31416. SceneSerializer.ClearCache = function () {
  31417. serializedGeometries = [];
  31418. };
  31419. SceneSerializer.Serialize = function (scene) {
  31420. var serializationObject = {};
  31421. // Scene
  31422. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  31423. serializationObject.autoClear = scene.autoClear;
  31424. serializationObject.clearColor = scene.clearColor.asArray();
  31425. serializationObject.ambientColor = scene.ambientColor.asArray();
  31426. serializationObject.gravity = scene.gravity.asArray();
  31427. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  31428. serializationObject.workerCollisions = scene.workerCollisions;
  31429. // Fog
  31430. if (scene.fogMode && scene.fogMode !== 0) {
  31431. serializationObject.fogMode = scene.fogMode;
  31432. serializationObject.fogColor = scene.fogColor.asArray();
  31433. serializationObject.fogStart = scene.fogStart;
  31434. serializationObject.fogEnd = scene.fogEnd;
  31435. serializationObject.fogDensity = scene.fogDensity;
  31436. }
  31437. //Physics
  31438. if (scene.isPhysicsEnabled()) {
  31439. serializationObject.physicsEnabled = true;
  31440. serializationObject.physicsGravity = scene.getPhysicsEngine()._getGravity().asArray();
  31441. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  31442. }
  31443. // Lights
  31444. serializationObject.lights = [];
  31445. var index;
  31446. var light;
  31447. for (index = 0; index < scene.lights.length; index++) {
  31448. light = scene.lights[index];
  31449. serializationObject.lights.push(light.serialize());
  31450. }
  31451. // Cameras
  31452. serializationObject.cameras = [];
  31453. for (index = 0; index < scene.cameras.length; index++) {
  31454. var camera = scene.cameras[index];
  31455. serializationObject.cameras.push(camera.serialize());
  31456. }
  31457. if (scene.activeCamera) {
  31458. serializationObject.activeCameraID = scene.activeCamera.id;
  31459. }
  31460. // Animations
  31461. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  31462. // Materials
  31463. serializationObject.materials = [];
  31464. serializationObject.multiMaterials = [];
  31465. var material;
  31466. for (index = 0; index < scene.materials.length; index++) {
  31467. material = scene.materials[index];
  31468. serializationObject.materials.push(material.serialize());
  31469. }
  31470. // MultiMaterials
  31471. serializationObject.multiMaterials = [];
  31472. for (index = 0; index < scene.multiMaterials.length; index++) {
  31473. var multiMaterial = scene.multiMaterials[index];
  31474. serializationObject.multiMaterials.push(multiMaterial.serialize());
  31475. }
  31476. // Skeletons
  31477. serializationObject.skeletons = [];
  31478. for (index = 0; index < scene.skeletons.length; index++) {
  31479. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  31480. }
  31481. // Geometries
  31482. serializationObject.geometries = {};
  31483. serializationObject.geometries.boxes = [];
  31484. serializationObject.geometries.spheres = [];
  31485. serializationObject.geometries.cylinders = [];
  31486. serializationObject.geometries.toruses = [];
  31487. serializationObject.geometries.grounds = [];
  31488. serializationObject.geometries.planes = [];
  31489. serializationObject.geometries.torusKnots = [];
  31490. serializationObject.geometries.vertexData = [];
  31491. serializedGeometries = [];
  31492. var geometries = scene.getGeometries();
  31493. for (index = 0; index < geometries.length; index++) {
  31494. var geometry = geometries[index];
  31495. if (geometry.isReady()) {
  31496. serializeGeometry(geometry, serializationObject.geometries);
  31497. }
  31498. }
  31499. // Meshes
  31500. serializationObject.meshes = [];
  31501. for (index = 0; index < scene.meshes.length; index++) {
  31502. var abstractMesh = scene.meshes[index];
  31503. if (abstractMesh instanceof BABYLON.Mesh) {
  31504. var mesh = abstractMesh;
  31505. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  31506. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  31507. }
  31508. }
  31509. }
  31510. // Particles Systems
  31511. serializationObject.particleSystems = [];
  31512. for (index = 0; index < scene.particleSystems.length; index++) {
  31513. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  31514. }
  31515. // Lens flares
  31516. serializationObject.lensFlareSystems = [];
  31517. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  31518. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  31519. }
  31520. // Shadows
  31521. serializationObject.shadowGenerators = [];
  31522. for (index = 0; index < scene.lights.length; index++) {
  31523. light = scene.lights[index];
  31524. if (light.getShadowGenerator()) {
  31525. serializationObject.shadowGenerators.push(light.getShadowGenerator().serialize());
  31526. }
  31527. }
  31528. return serializationObject;
  31529. };
  31530. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  31531. if (withParents === void 0) { withParents = false; }
  31532. if (withChildren === void 0) { withChildren = false; }
  31533. var serializationObject = {};
  31534. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  31535. if (withParents || withChildren) {
  31536. //deliberate for loop! not for each, appended should be processed as well.
  31537. for (var i = 0; i < toSerialize.length; ++i) {
  31538. if (withChildren) {
  31539. toSerialize[i].getDescendants().forEach(function (node) {
  31540. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  31541. toSerialize.push(node);
  31542. }
  31543. });
  31544. }
  31545. //make sure the array doesn't contain the object already
  31546. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  31547. toSerialize.push(toSerialize[i].parent);
  31548. }
  31549. }
  31550. }
  31551. toSerialize.forEach(function (mesh) {
  31552. finalizeSingleMesh(mesh, serializationObject);
  31553. });
  31554. return serializationObject;
  31555. };
  31556. return SceneSerializer;
  31557. })();
  31558. BABYLON.SceneSerializer = SceneSerializer;
  31559. })(BABYLON || (BABYLON = {}));
  31560. var BABYLON;
  31561. (function (BABYLON) {
  31562. // Unique ID when we import meshes from Babylon to CSG
  31563. var currentCSGMeshId = 0;
  31564. // # class Vertex
  31565. // Represents a vertex of a polygon. Use your own vertex class instead of this
  31566. // one to provide additional features like texture coordinates and vertex
  31567. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  31568. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  31569. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  31570. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  31571. // is not used anywhere else.
  31572. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  31573. var Vertex = (function () {
  31574. function Vertex(pos, normal, uv) {
  31575. this.pos = pos;
  31576. this.normal = normal;
  31577. this.uv = uv;
  31578. }
  31579. Vertex.prototype.clone = function () {
  31580. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  31581. };
  31582. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  31583. // orientation of a polygon is flipped.
  31584. Vertex.prototype.flip = function () {
  31585. this.normal = this.normal.scale(-1);
  31586. };
  31587. // Create a new vertex between this vertex and `other` by linearly
  31588. // interpolating all properties using a parameter of `t`. Subclasses should
  31589. // override this to interpolate additional properties.
  31590. Vertex.prototype.interpolate = function (other, t) {
  31591. 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));
  31592. };
  31593. return Vertex;
  31594. })();
  31595. // # class Plane
  31596. // Represents a plane in 3D space.
  31597. var Plane = (function () {
  31598. function Plane(normal, w) {
  31599. this.normal = normal;
  31600. this.w = w;
  31601. }
  31602. Plane.FromPoints = function (a, b, c) {
  31603. var v0 = c.subtract(a);
  31604. var v1 = b.subtract(a);
  31605. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  31606. return null;
  31607. }
  31608. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  31609. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  31610. };
  31611. Plane.prototype.clone = function () {
  31612. return new Plane(this.normal.clone(), this.w);
  31613. };
  31614. Plane.prototype.flip = function () {
  31615. this.normal.scaleInPlace(-1);
  31616. this.w = -this.w;
  31617. };
  31618. // Split `polygon` by this plane if needed, then put the polygon or polygon
  31619. // fragments in the appropriate lists. Coplanar polygons go into either
  31620. // `coplanarFront` or `coplanarBack` depending on their orientation with
  31621. // respect to this plane. Polygons in front or in back of this plane go into
  31622. // either `front` or `back`.
  31623. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  31624. var COPLANAR = 0;
  31625. var FRONT = 1;
  31626. var BACK = 2;
  31627. var SPANNING = 3;
  31628. // Classify each point as well as the entire polygon into one of the above
  31629. // four classes.
  31630. var polygonType = 0;
  31631. var types = [];
  31632. var i;
  31633. var t;
  31634. for (i = 0; i < polygon.vertices.length; i++) {
  31635. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  31636. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  31637. polygonType |= type;
  31638. types.push(type);
  31639. }
  31640. // Put the polygon in the correct list, splitting it when necessary.
  31641. switch (polygonType) {
  31642. case COPLANAR:
  31643. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  31644. break;
  31645. case FRONT:
  31646. front.push(polygon);
  31647. break;
  31648. case BACK:
  31649. back.push(polygon);
  31650. break;
  31651. case SPANNING:
  31652. var f = [], b = [];
  31653. for (i = 0; i < polygon.vertices.length; i++) {
  31654. var j = (i + 1) % polygon.vertices.length;
  31655. var ti = types[i], tj = types[j];
  31656. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  31657. if (ti !== BACK)
  31658. f.push(vi);
  31659. if (ti !== FRONT)
  31660. b.push(ti !== BACK ? vi.clone() : vi);
  31661. if ((ti | tj) === SPANNING) {
  31662. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  31663. var v = vi.interpolate(vj, t);
  31664. f.push(v);
  31665. b.push(v.clone());
  31666. }
  31667. }
  31668. var poly;
  31669. if (f.length >= 3) {
  31670. poly = new Polygon(f, polygon.shared);
  31671. if (poly.plane)
  31672. front.push(poly);
  31673. }
  31674. if (b.length >= 3) {
  31675. poly = new Polygon(b, polygon.shared);
  31676. if (poly.plane)
  31677. back.push(poly);
  31678. }
  31679. break;
  31680. }
  31681. };
  31682. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  31683. // point is on the plane.
  31684. Plane.EPSILON = 1e-5;
  31685. return Plane;
  31686. })();
  31687. // # class Polygon
  31688. // Represents a convex polygon. The vertices used to initialize a polygon must
  31689. // be coplanar and form a convex loop.
  31690. //
  31691. // Each convex polygon has a `shared` property, which is shared between all
  31692. // polygons that are clones of each other or were split from the same polygon.
  31693. // This can be used to define per-polygon properties (such as surface color).
  31694. var Polygon = (function () {
  31695. function Polygon(vertices, shared) {
  31696. this.vertices = vertices;
  31697. this.shared = shared;
  31698. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  31699. }
  31700. Polygon.prototype.clone = function () {
  31701. var vertices = this.vertices.map(function (v) { return v.clone(); });
  31702. return new Polygon(vertices, this.shared);
  31703. };
  31704. Polygon.prototype.flip = function () {
  31705. this.vertices.reverse().map(function (v) { v.flip(); });
  31706. this.plane.flip();
  31707. };
  31708. return Polygon;
  31709. })();
  31710. // # class Node
  31711. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  31712. // by picking a polygon to split along. That polygon (and all other coplanar
  31713. // polygons) are added directly to that node and the other polygons are added to
  31714. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  31715. // no distinction between internal and leaf nodes.
  31716. var Node = (function () {
  31717. function Node(polygons) {
  31718. this.plane = null;
  31719. this.front = null;
  31720. this.back = null;
  31721. this.polygons = [];
  31722. if (polygons) {
  31723. this.build(polygons);
  31724. }
  31725. }
  31726. Node.prototype.clone = function () {
  31727. var node = new Node();
  31728. node.plane = this.plane && this.plane.clone();
  31729. node.front = this.front && this.front.clone();
  31730. node.back = this.back && this.back.clone();
  31731. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  31732. return node;
  31733. };
  31734. // Convert solid space to empty space and empty space to solid space.
  31735. Node.prototype.invert = function () {
  31736. for (var i = 0; i < this.polygons.length; i++) {
  31737. this.polygons[i].flip();
  31738. }
  31739. if (this.plane) {
  31740. this.plane.flip();
  31741. }
  31742. if (this.front) {
  31743. this.front.invert();
  31744. }
  31745. if (this.back) {
  31746. this.back.invert();
  31747. }
  31748. var temp = this.front;
  31749. this.front = this.back;
  31750. this.back = temp;
  31751. };
  31752. // Recursively remove all polygons in `polygons` that are inside this BSP
  31753. // tree.
  31754. Node.prototype.clipPolygons = function (polygons) {
  31755. if (!this.plane)
  31756. return polygons.slice();
  31757. var front = [], back = [];
  31758. for (var i = 0; i < polygons.length; i++) {
  31759. this.plane.splitPolygon(polygons[i], front, back, front, back);
  31760. }
  31761. if (this.front) {
  31762. front = this.front.clipPolygons(front);
  31763. }
  31764. if (this.back) {
  31765. back = this.back.clipPolygons(back);
  31766. }
  31767. else {
  31768. back = [];
  31769. }
  31770. return front.concat(back);
  31771. };
  31772. // Remove all polygons in this BSP tree that are inside the other BSP tree
  31773. // `bsp`.
  31774. Node.prototype.clipTo = function (bsp) {
  31775. this.polygons = bsp.clipPolygons(this.polygons);
  31776. if (this.front)
  31777. this.front.clipTo(bsp);
  31778. if (this.back)
  31779. this.back.clipTo(bsp);
  31780. };
  31781. // Return a list of all polygons in this BSP tree.
  31782. Node.prototype.allPolygons = function () {
  31783. var polygons = this.polygons.slice();
  31784. if (this.front)
  31785. polygons = polygons.concat(this.front.allPolygons());
  31786. if (this.back)
  31787. polygons = polygons.concat(this.back.allPolygons());
  31788. return polygons;
  31789. };
  31790. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  31791. // new polygons are filtered down to the bottom of the tree and become new
  31792. // nodes there. Each set of polygons is partitioned using the first polygon
  31793. // (no heuristic is used to pick a good split).
  31794. Node.prototype.build = function (polygons) {
  31795. if (!polygons.length)
  31796. return;
  31797. if (!this.plane)
  31798. this.plane = polygons[0].plane.clone();
  31799. var front = [], back = [];
  31800. for (var i = 0; i < polygons.length; i++) {
  31801. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  31802. }
  31803. if (front.length) {
  31804. if (!this.front)
  31805. this.front = new Node();
  31806. this.front.build(front);
  31807. }
  31808. if (back.length) {
  31809. if (!this.back)
  31810. this.back = new Node();
  31811. this.back.build(back);
  31812. }
  31813. };
  31814. return Node;
  31815. })();
  31816. var CSG = (function () {
  31817. function CSG() {
  31818. this.polygons = new Array();
  31819. }
  31820. // Convert BABYLON.Mesh to BABYLON.CSG
  31821. CSG.FromMesh = function (mesh) {
  31822. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  31823. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  31824. if (mesh instanceof BABYLON.Mesh) {
  31825. mesh.computeWorldMatrix(true);
  31826. matrix = mesh.getWorldMatrix();
  31827. meshPosition = mesh.position.clone();
  31828. meshRotation = mesh.rotation.clone();
  31829. if (mesh.rotationQuaternion) {
  31830. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  31831. }
  31832. meshScaling = mesh.scaling.clone();
  31833. }
  31834. else {
  31835. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  31836. }
  31837. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  31838. var subMeshes = mesh.subMeshes;
  31839. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  31840. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  31841. vertices = [];
  31842. for (var j = 0; j < 3; j++) {
  31843. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  31844. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  31845. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  31846. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  31847. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  31848. vertex = new Vertex(position, normal, uv);
  31849. vertices.push(vertex);
  31850. }
  31851. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  31852. // To handle the case of degenerated triangle
  31853. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  31854. if (polygon.plane)
  31855. polygons.push(polygon);
  31856. }
  31857. }
  31858. var csg = CSG.FromPolygons(polygons);
  31859. csg.matrix = matrix;
  31860. csg.position = meshPosition;
  31861. csg.rotation = meshRotation;
  31862. csg.scaling = meshScaling;
  31863. csg.rotationQuaternion = meshRotationQuaternion;
  31864. currentCSGMeshId++;
  31865. return csg;
  31866. };
  31867. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  31868. CSG.FromPolygons = function (polygons) {
  31869. var csg = new CSG();
  31870. csg.polygons = polygons;
  31871. return csg;
  31872. };
  31873. CSG.prototype.clone = function () {
  31874. var csg = new CSG();
  31875. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  31876. csg.copyTransformAttributes(this);
  31877. return csg;
  31878. };
  31879. CSG.prototype.toPolygons = function () {
  31880. return this.polygons;
  31881. };
  31882. CSG.prototype.union = function (csg) {
  31883. var a = new Node(this.clone().polygons);
  31884. var b = new Node(csg.clone().polygons);
  31885. a.clipTo(b);
  31886. b.clipTo(a);
  31887. b.invert();
  31888. b.clipTo(a);
  31889. b.invert();
  31890. a.build(b.allPolygons());
  31891. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  31892. };
  31893. CSG.prototype.unionInPlace = function (csg) {
  31894. var a = new Node(this.polygons);
  31895. var b = new Node(csg.polygons);
  31896. a.clipTo(b);
  31897. b.clipTo(a);
  31898. b.invert();
  31899. b.clipTo(a);
  31900. b.invert();
  31901. a.build(b.allPolygons());
  31902. this.polygons = a.allPolygons();
  31903. };
  31904. CSG.prototype.subtract = function (csg) {
  31905. var a = new Node(this.clone().polygons);
  31906. var b = new Node(csg.clone().polygons);
  31907. a.invert();
  31908. a.clipTo(b);
  31909. b.clipTo(a);
  31910. b.invert();
  31911. b.clipTo(a);
  31912. b.invert();
  31913. a.build(b.allPolygons());
  31914. a.invert();
  31915. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  31916. };
  31917. CSG.prototype.subtractInPlace = function (csg) {
  31918. var a = new Node(this.polygons);
  31919. var b = new Node(csg.polygons);
  31920. a.invert();
  31921. a.clipTo(b);
  31922. b.clipTo(a);
  31923. b.invert();
  31924. b.clipTo(a);
  31925. b.invert();
  31926. a.build(b.allPolygons());
  31927. a.invert();
  31928. this.polygons = a.allPolygons();
  31929. };
  31930. CSG.prototype.intersect = function (csg) {
  31931. var a = new Node(this.clone().polygons);
  31932. var b = new Node(csg.clone().polygons);
  31933. a.invert();
  31934. b.clipTo(a);
  31935. b.invert();
  31936. a.clipTo(b);
  31937. b.clipTo(a);
  31938. a.build(b.allPolygons());
  31939. a.invert();
  31940. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  31941. };
  31942. CSG.prototype.intersectInPlace = function (csg) {
  31943. var a = new Node(this.polygons);
  31944. var b = new Node(csg.polygons);
  31945. a.invert();
  31946. b.clipTo(a);
  31947. b.invert();
  31948. a.clipTo(b);
  31949. b.clipTo(a);
  31950. a.build(b.allPolygons());
  31951. a.invert();
  31952. this.polygons = a.allPolygons();
  31953. };
  31954. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  31955. // not modified.
  31956. CSG.prototype.inverse = function () {
  31957. var csg = this.clone();
  31958. csg.inverseInPlace();
  31959. return csg;
  31960. };
  31961. CSG.prototype.inverseInPlace = function () {
  31962. this.polygons.map(function (p) { p.flip(); });
  31963. };
  31964. // This is used to keep meshes transformations so they can be restored
  31965. // when we build back a Babylon Mesh
  31966. // NB : All CSG operations are performed in world coordinates
  31967. CSG.prototype.copyTransformAttributes = function (csg) {
  31968. this.matrix = csg.matrix;
  31969. this.position = csg.position;
  31970. this.rotation = csg.rotation;
  31971. this.scaling = csg.scaling;
  31972. this.rotationQuaternion = csg.rotationQuaternion;
  31973. return this;
  31974. };
  31975. // Build Raw mesh from CSG
  31976. // Coordinates here are in world space
  31977. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  31978. var matrix = this.matrix.clone();
  31979. matrix.invert();
  31980. 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;
  31981. if (keepSubMeshes) {
  31982. // Sort Polygons, since subMeshes are indices range
  31983. polygons.sort(function (a, b) {
  31984. if (a.shared.meshId === b.shared.meshId) {
  31985. return a.shared.subMeshId - b.shared.subMeshId;
  31986. }
  31987. else {
  31988. return a.shared.meshId - b.shared.meshId;
  31989. }
  31990. });
  31991. }
  31992. for (var i = 0, il = polygons.length; i < il; i++) {
  31993. polygon = polygons[i];
  31994. // Building SubMeshes
  31995. if (!subMesh_dict[polygon.shared.meshId]) {
  31996. subMesh_dict[polygon.shared.meshId] = {};
  31997. }
  31998. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  31999. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  32000. indexStart: +Infinity,
  32001. indexEnd: -Infinity,
  32002. materialIndex: polygon.shared.materialIndex
  32003. };
  32004. }
  32005. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  32006. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  32007. polygonIndices[0] = 0;
  32008. polygonIndices[1] = j - 1;
  32009. polygonIndices[2] = j;
  32010. for (var k = 0; k < 3; k++) {
  32011. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  32012. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  32013. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  32014. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  32015. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  32016. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  32017. // Check if 2 points can be merged
  32018. if (!(typeof vertex_idx !== 'undefined' &&
  32019. normals[vertex_idx * 3] === localNormal.x &&
  32020. normals[vertex_idx * 3 + 1] === localNormal.y &&
  32021. normals[vertex_idx * 3 + 2] === localNormal.z &&
  32022. uvs[vertex_idx * 2] === uv.x &&
  32023. uvs[vertex_idx * 2 + 1] === uv.y)) {
  32024. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  32025. uvs.push(uv.x, uv.y);
  32026. normals.push(normal.x, normal.y, normal.z);
  32027. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  32028. }
  32029. indices.push(vertex_idx);
  32030. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  32031. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  32032. currentIndex++;
  32033. }
  32034. }
  32035. }
  32036. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  32037. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32038. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  32039. mesh.setIndices(indices);
  32040. if (keepSubMeshes) {
  32041. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  32042. var materialIndexOffset = 0, materialMaxIndex;
  32043. mesh.subMeshes = new Array();
  32044. for (var m in subMesh_dict) {
  32045. materialMaxIndex = -1;
  32046. for (var sm in subMesh_dict[m]) {
  32047. subMesh_obj = subMesh_dict[m][sm];
  32048. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  32049. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  32050. }
  32051. materialIndexOffset += ++materialMaxIndex;
  32052. }
  32053. }
  32054. return mesh;
  32055. };
  32056. // Build Mesh from CSG taking material and transforms into account
  32057. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  32058. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  32059. mesh.material = material;
  32060. mesh.position.copyFrom(this.position);
  32061. mesh.rotation.copyFrom(this.rotation);
  32062. if (this.rotationQuaternion) {
  32063. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  32064. }
  32065. mesh.scaling.copyFrom(this.scaling);
  32066. mesh.computeWorldMatrix(true);
  32067. return mesh;
  32068. };
  32069. return CSG;
  32070. })();
  32071. BABYLON.CSG = CSG;
  32072. })(BABYLON || (BABYLON = {}));
  32073. var BABYLON;
  32074. (function (BABYLON) {
  32075. var VRDistortionCorrectionPostProcess = (function (_super) {
  32076. __extends(VRDistortionCorrectionPostProcess, _super);
  32077. //ANY
  32078. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  32079. var _this = this;
  32080. _super.call(this, name, "vrDistortionCorrection", [
  32081. 'LensCenter',
  32082. 'Scale',
  32083. 'ScaleIn',
  32084. 'HmdWarpParam'
  32085. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  32086. this._isRightEye = isRightEye;
  32087. this._distortionFactors = vrMetrics.distortionK;
  32088. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  32089. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  32090. this.onSizeChanged = function () {
  32091. _this.aspectRatio = _this.width * .5 / _this.height;
  32092. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  32093. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  32094. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  32095. };
  32096. this.onApply = function (effect) {
  32097. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  32098. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  32099. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  32100. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  32101. };
  32102. }
  32103. return VRDistortionCorrectionPostProcess;
  32104. })(BABYLON.PostProcess);
  32105. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  32106. })(BABYLON || (BABYLON = {}));
  32107. // Mainly based on these 2 articles :
  32108. // 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
  32109. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  32110. var BABYLON;
  32111. (function (BABYLON) {
  32112. (function (JoystickAxis) {
  32113. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  32114. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  32115. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  32116. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  32117. var JoystickAxis = BABYLON.JoystickAxis;
  32118. var VirtualJoystick = (function () {
  32119. function VirtualJoystick(leftJoystick) {
  32120. var _this = this;
  32121. if (leftJoystick) {
  32122. this._leftJoystick = true;
  32123. }
  32124. else {
  32125. this._leftJoystick = false;
  32126. }
  32127. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  32128. VirtualJoystick._globalJoystickIndex++;
  32129. // By default left & right arrow keys are moving the X
  32130. // and up & down keys are moving the Y
  32131. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  32132. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  32133. this.reverseLeftRight = false;
  32134. this.reverseUpDown = false;
  32135. // collections of pointers
  32136. this._touches = new BABYLON.SmartCollection();
  32137. this.deltaPosition = BABYLON.Vector3.Zero();
  32138. this._joystickSensibility = 25;
  32139. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  32140. this._rotationSpeed = 25;
  32141. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  32142. this._rotateOnAxisRelativeToMesh = false;
  32143. this._onResize = function (evt) {
  32144. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  32145. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  32146. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  32147. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  32148. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  32149. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  32150. };
  32151. // injecting a canvas element on top of the canvas 3D game
  32152. if (!VirtualJoystick.vjCanvas) {
  32153. window.addEventListener("resize", this._onResize, false);
  32154. VirtualJoystick.vjCanvas = document.createElement("canvas");
  32155. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  32156. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  32157. VirtualJoystick.vjCanvas.width = window.innerWidth;
  32158. VirtualJoystick.vjCanvas.height = window.innerHeight;
  32159. VirtualJoystick.vjCanvas.style.width = "100%";
  32160. VirtualJoystick.vjCanvas.style.height = "100%";
  32161. VirtualJoystick.vjCanvas.style.position = "absolute";
  32162. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  32163. VirtualJoystick.vjCanvas.style.top = "0px";
  32164. VirtualJoystick.vjCanvas.style.left = "0px";
  32165. VirtualJoystick.vjCanvas.style.zIndex = "5";
  32166. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  32167. // Support for jQuery PEP polyfill
  32168. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  32169. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  32170. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  32171. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  32172. document.body.appendChild(VirtualJoystick.vjCanvas);
  32173. }
  32174. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  32175. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  32176. this.pressed = false;
  32177. // default joystick color
  32178. this._joystickColor = "cyan";
  32179. this._joystickPointerID = -1;
  32180. // current joystick position
  32181. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  32182. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  32183. // origin joystick position
  32184. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  32185. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  32186. this._onPointerDownHandlerRef = function (evt) {
  32187. _this._onPointerDown(evt);
  32188. };
  32189. this._onPointerMoveHandlerRef = function (evt) {
  32190. _this._onPointerMove(evt);
  32191. };
  32192. this._onPointerOutHandlerRef = function (evt) {
  32193. _this._onPointerUp(evt);
  32194. };
  32195. this._onPointerUpHandlerRef = function (evt) {
  32196. _this._onPointerUp(evt);
  32197. };
  32198. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  32199. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  32200. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  32201. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  32202. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  32203. evt.preventDefault(); // Disables system menu
  32204. }, false);
  32205. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  32206. }
  32207. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  32208. this._joystickSensibility = newJoystickSensibility;
  32209. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  32210. };
  32211. VirtualJoystick.prototype._onPointerDown = function (e) {
  32212. var positionOnScreenCondition;
  32213. e.preventDefault();
  32214. if (this._leftJoystick === true) {
  32215. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  32216. }
  32217. else {
  32218. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  32219. }
  32220. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  32221. // First contact will be dedicated to the virtual joystick
  32222. this._joystickPointerID = e.pointerId;
  32223. this._joystickPointerStartPos.x = e.clientX;
  32224. this._joystickPointerStartPos.y = e.clientY;
  32225. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  32226. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  32227. this._deltaJoystickVector.x = 0;
  32228. this._deltaJoystickVector.y = 0;
  32229. this.pressed = true;
  32230. this._touches.add(e.pointerId.toString(), e);
  32231. }
  32232. else {
  32233. // You can only trigger the action buttons with a joystick declared
  32234. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  32235. this._action();
  32236. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  32237. }
  32238. }
  32239. };
  32240. VirtualJoystick.prototype._onPointerMove = function (e) {
  32241. // If the current pointer is the one associated to the joystick (first touch contact)
  32242. if (this._joystickPointerID == e.pointerId) {
  32243. this._joystickPointerPos.x = e.clientX;
  32244. this._joystickPointerPos.y = e.clientY;
  32245. this._deltaJoystickVector = this._joystickPointerPos.clone();
  32246. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  32247. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  32248. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  32249. switch (this._axisTargetedByLeftAndRight) {
  32250. case JoystickAxis.X:
  32251. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  32252. break;
  32253. case JoystickAxis.Y:
  32254. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  32255. break;
  32256. case JoystickAxis.Z:
  32257. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  32258. break;
  32259. }
  32260. var directionUpDown = this.reverseUpDown ? 1 : -1;
  32261. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  32262. switch (this._axisTargetedByUpAndDown) {
  32263. case JoystickAxis.X:
  32264. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  32265. break;
  32266. case JoystickAxis.Y:
  32267. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  32268. break;
  32269. case JoystickAxis.Z:
  32270. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  32271. break;
  32272. }
  32273. }
  32274. else {
  32275. if (this._touches.item(e.pointerId.toString())) {
  32276. this._touches.item(e.pointerId.toString()).x = e.clientX;
  32277. this._touches.item(e.pointerId.toString()).y = e.clientY;
  32278. }
  32279. }
  32280. };
  32281. VirtualJoystick.prototype._onPointerUp = function (e) {
  32282. if (this._joystickPointerID == e.pointerId) {
  32283. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  32284. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  32285. this._joystickPointerID = -1;
  32286. this.pressed = false;
  32287. }
  32288. else {
  32289. var touch = this._touches.item(e.pointerId.toString());
  32290. if (touch) {
  32291. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  32292. }
  32293. }
  32294. this._deltaJoystickVector.x = 0;
  32295. this._deltaJoystickVector.y = 0;
  32296. this._touches.remove(e.pointerId.toString());
  32297. };
  32298. /**
  32299. * Change the color of the virtual joystick
  32300. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  32301. */
  32302. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  32303. this._joystickColor = newColor;
  32304. };
  32305. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  32306. this._action = action;
  32307. };
  32308. // Define which axis you'd like to control for left & right
  32309. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  32310. switch (axis) {
  32311. case JoystickAxis.X:
  32312. case JoystickAxis.Y:
  32313. case JoystickAxis.Z:
  32314. this._axisTargetedByLeftAndRight = axis;
  32315. break;
  32316. default:
  32317. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  32318. break;
  32319. }
  32320. };
  32321. // Define which axis you'd like to control for up & down
  32322. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  32323. switch (axis) {
  32324. case JoystickAxis.X:
  32325. case JoystickAxis.Y:
  32326. case JoystickAxis.Z:
  32327. this._axisTargetedByUpAndDown = axis;
  32328. break;
  32329. default:
  32330. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  32331. break;
  32332. }
  32333. };
  32334. VirtualJoystick.prototype._clearCanvas = function () {
  32335. if (this._leftJoystick) {
  32336. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  32337. }
  32338. else {
  32339. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  32340. }
  32341. };
  32342. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  32343. var _this = this;
  32344. if (this.pressed) {
  32345. this._touches.forEach(function (touch) {
  32346. if (touch.pointerId === _this._joystickPointerID) {
  32347. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  32348. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  32349. VirtualJoystick.vjCanvasContext.beginPath();
  32350. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  32351. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  32352. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  32353. VirtualJoystick.vjCanvasContext.stroke();
  32354. VirtualJoystick.vjCanvasContext.closePath();
  32355. VirtualJoystick.vjCanvasContext.beginPath();
  32356. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  32357. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  32358. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  32359. VirtualJoystick.vjCanvasContext.stroke();
  32360. VirtualJoystick.vjCanvasContext.closePath();
  32361. VirtualJoystick.vjCanvasContext.beginPath();
  32362. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  32363. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  32364. VirtualJoystick.vjCanvasContext.stroke();
  32365. VirtualJoystick.vjCanvasContext.closePath();
  32366. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  32367. }
  32368. else {
  32369. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  32370. VirtualJoystick.vjCanvasContext.beginPath();
  32371. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  32372. VirtualJoystick.vjCanvasContext.beginPath();
  32373. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  32374. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  32375. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  32376. VirtualJoystick.vjCanvasContext.stroke();
  32377. VirtualJoystick.vjCanvasContext.closePath();
  32378. touch.prevX = touch.x;
  32379. touch.prevY = touch.y;
  32380. }
  32381. ;
  32382. });
  32383. }
  32384. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  32385. };
  32386. VirtualJoystick.prototype.releaseCanvas = function () {
  32387. if (VirtualJoystick.vjCanvas) {
  32388. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  32389. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  32390. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  32391. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  32392. window.removeEventListener("resize", this._onResize);
  32393. document.body.removeChild(VirtualJoystick.vjCanvas);
  32394. VirtualJoystick.vjCanvas = null;
  32395. }
  32396. };
  32397. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  32398. VirtualJoystick._globalJoystickIndex = 0;
  32399. return VirtualJoystick;
  32400. })();
  32401. BABYLON.VirtualJoystick = VirtualJoystick;
  32402. })(BABYLON || (BABYLON = {}));
  32403. var BABYLON;
  32404. (function (BABYLON) {
  32405. // We're mainly based on the logic defined into the FreeCamera code
  32406. var VirtualJoysticksCamera = (function (_super) {
  32407. __extends(VirtualJoysticksCamera, _super);
  32408. function VirtualJoysticksCamera(name, position, scene) {
  32409. _super.call(this, name, position, scene);
  32410. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  32411. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  32412. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  32413. this._leftjoystick.setJoystickSensibility(0.15);
  32414. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  32415. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  32416. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  32417. this._rightjoystick.reverseUpDown = true;
  32418. this._rightjoystick.setJoystickSensibility(0.05);
  32419. this._rightjoystick.setJoystickColor("yellow");
  32420. }
  32421. VirtualJoysticksCamera.prototype.getLeftJoystick = function () {
  32422. return this._leftjoystick;
  32423. };
  32424. VirtualJoysticksCamera.prototype.getRightJoystick = function () {
  32425. return this._rightjoystick;
  32426. };
  32427. VirtualJoysticksCamera.prototype._checkInputs = function () {
  32428. var speed = this._computeLocalCameraSpeed() * 50;
  32429. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  32430. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  32431. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  32432. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  32433. if (!this._leftjoystick.pressed) {
  32434. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  32435. }
  32436. if (!this._rightjoystick.pressed) {
  32437. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  32438. }
  32439. _super.prototype._checkInputs.call(this);
  32440. };
  32441. VirtualJoysticksCamera.prototype.dispose = function () {
  32442. this._leftjoystick.releaseCanvas();
  32443. _super.prototype.dispose.call(this);
  32444. };
  32445. return VirtualJoysticksCamera;
  32446. })(BABYLON.FreeCamera);
  32447. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  32448. })(BABYLON || (BABYLON = {}));
  32449. var BABYLON;
  32450. (function (BABYLON) {
  32451. var AnaglyphPostProcess = (function (_super) {
  32452. __extends(AnaglyphPostProcess, _super);
  32453. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  32454. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  32455. }
  32456. return AnaglyphPostProcess;
  32457. })(BABYLON.PostProcess);
  32458. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  32459. })(BABYLON || (BABYLON = {}));
  32460. var BABYLON;
  32461. (function (BABYLON) {
  32462. var OutlineRenderer = (function () {
  32463. function OutlineRenderer(scene) {
  32464. this._scene = scene;
  32465. }
  32466. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  32467. var _this = this;
  32468. if (useOverlay === void 0) { useOverlay = false; }
  32469. var scene = this._scene;
  32470. var engine = this._scene.getEngine();
  32471. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32472. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  32473. return;
  32474. }
  32475. var mesh = subMesh.getRenderingMesh();
  32476. var material = subMesh.getMaterial();
  32477. engine.enableEffect(this._effect);
  32478. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  32479. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  32480. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  32481. // Bones
  32482. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  32483. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  32484. }
  32485. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  32486. // Alpha test
  32487. if (material && material.needAlphaTesting()) {
  32488. var alphaTexture = material.getAlphaTestTexture();
  32489. this._effect.setTexture("diffuseSampler", alphaTexture);
  32490. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  32491. }
  32492. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  32493. };
  32494. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  32495. var defines = [];
  32496. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  32497. var mesh = subMesh.getMesh();
  32498. var material = subMesh.getMaterial();
  32499. // Alpha test
  32500. if (material && material.needAlphaTesting()) {
  32501. defines.push("#define ALPHATEST");
  32502. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32503. attribs.push(BABYLON.VertexBuffer.UVKind);
  32504. defines.push("#define UV1");
  32505. }
  32506. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32507. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  32508. defines.push("#define UV2");
  32509. }
  32510. }
  32511. // Bones
  32512. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  32513. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  32514. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  32515. if (mesh.numBoneInfluencers > 4) {
  32516. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32517. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  32518. }
  32519. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  32520. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  32521. }
  32522. else {
  32523. defines.push("#define NUM_BONE_INFLUENCERS 0");
  32524. }
  32525. // Instances
  32526. if (useInstances) {
  32527. defines.push("#define INSTANCES");
  32528. attribs.push("world0");
  32529. attribs.push("world1");
  32530. attribs.push("world2");
  32531. attribs.push("world3");
  32532. }
  32533. // Get correct effect
  32534. var join = defines.join("\n");
  32535. if (this._cachedDefines !== join) {
  32536. this._cachedDefines = join;
  32537. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  32538. }
  32539. return this._effect.isReady();
  32540. };
  32541. return OutlineRenderer;
  32542. })();
  32543. BABYLON.OutlineRenderer = OutlineRenderer;
  32544. })(BABYLON || (BABYLON = {}));
  32545. var BABYLON;
  32546. (function (BABYLON) {
  32547. var MeshAssetTask = (function () {
  32548. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  32549. this.name = name;
  32550. this.meshesNames = meshesNames;
  32551. this.rootUrl = rootUrl;
  32552. this.sceneFilename = sceneFilename;
  32553. this.isCompleted = false;
  32554. }
  32555. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  32556. var _this = this;
  32557. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  32558. _this.loadedMeshes = meshes;
  32559. _this.loadedParticleSystems = particleSystems;
  32560. _this.loadedSkeletons = skeletons;
  32561. _this.isCompleted = true;
  32562. if (_this.onSuccess) {
  32563. _this.onSuccess(_this);
  32564. }
  32565. onSuccess();
  32566. }, null, function () {
  32567. if (_this.onError) {
  32568. _this.onError(_this);
  32569. }
  32570. onError();
  32571. });
  32572. };
  32573. return MeshAssetTask;
  32574. })();
  32575. BABYLON.MeshAssetTask = MeshAssetTask;
  32576. var TextFileAssetTask = (function () {
  32577. function TextFileAssetTask(name, url) {
  32578. this.name = name;
  32579. this.url = url;
  32580. this.isCompleted = false;
  32581. }
  32582. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  32583. var _this = this;
  32584. BABYLON.Tools.LoadFile(this.url, function (data) {
  32585. _this.text = data;
  32586. _this.isCompleted = true;
  32587. if (_this.onSuccess) {
  32588. _this.onSuccess(_this);
  32589. }
  32590. onSuccess();
  32591. }, null, scene.database, false, function () {
  32592. if (_this.onError) {
  32593. _this.onError(_this);
  32594. }
  32595. onError();
  32596. });
  32597. };
  32598. return TextFileAssetTask;
  32599. })();
  32600. BABYLON.TextFileAssetTask = TextFileAssetTask;
  32601. var BinaryFileAssetTask = (function () {
  32602. function BinaryFileAssetTask(name, url) {
  32603. this.name = name;
  32604. this.url = url;
  32605. this.isCompleted = false;
  32606. }
  32607. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  32608. var _this = this;
  32609. BABYLON.Tools.LoadFile(this.url, function (data) {
  32610. _this.data = data;
  32611. _this.isCompleted = true;
  32612. if (_this.onSuccess) {
  32613. _this.onSuccess(_this);
  32614. }
  32615. onSuccess();
  32616. }, null, scene.database, true, function () {
  32617. if (_this.onError) {
  32618. _this.onError(_this);
  32619. }
  32620. onError();
  32621. });
  32622. };
  32623. return BinaryFileAssetTask;
  32624. })();
  32625. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  32626. var ImageAssetTask = (function () {
  32627. function ImageAssetTask(name, url) {
  32628. this.name = name;
  32629. this.url = url;
  32630. this.isCompleted = false;
  32631. }
  32632. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  32633. var _this = this;
  32634. var img = new Image();
  32635. img.onload = function () {
  32636. _this.image = img;
  32637. _this.isCompleted = true;
  32638. if (_this.onSuccess) {
  32639. _this.onSuccess(_this);
  32640. }
  32641. onSuccess();
  32642. };
  32643. img.onerror = function () {
  32644. if (_this.onError) {
  32645. _this.onError(_this);
  32646. }
  32647. onError();
  32648. };
  32649. img.src = this.url;
  32650. };
  32651. return ImageAssetTask;
  32652. })();
  32653. BABYLON.ImageAssetTask = ImageAssetTask;
  32654. var TextureAssetTask = (function () {
  32655. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  32656. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32657. this.name = name;
  32658. this.url = url;
  32659. this.noMipmap = noMipmap;
  32660. this.invertY = invertY;
  32661. this.samplingMode = samplingMode;
  32662. this.isCompleted = false;
  32663. }
  32664. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  32665. var _this = this;
  32666. var onload = function () {
  32667. _this.isCompleted = true;
  32668. if (_this.onSuccess) {
  32669. _this.onSuccess(_this);
  32670. }
  32671. onSuccess();
  32672. };
  32673. var onerror = function () {
  32674. if (_this.onError) {
  32675. _this.onError(_this);
  32676. }
  32677. onError();
  32678. };
  32679. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  32680. };
  32681. return TextureAssetTask;
  32682. })();
  32683. BABYLON.TextureAssetTask = TextureAssetTask;
  32684. var AssetsManager = (function () {
  32685. function AssetsManager(scene) {
  32686. this._tasks = new Array();
  32687. this._waitingTasksCount = 0;
  32688. this.useDefaultLoadingScreen = true;
  32689. this._scene = scene;
  32690. }
  32691. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  32692. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  32693. this._tasks.push(task);
  32694. return task;
  32695. };
  32696. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  32697. var task = new TextFileAssetTask(taskName, url);
  32698. this._tasks.push(task);
  32699. return task;
  32700. };
  32701. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  32702. var task = new BinaryFileAssetTask(taskName, url);
  32703. this._tasks.push(task);
  32704. return task;
  32705. };
  32706. AssetsManager.prototype.addImageTask = function (taskName, url) {
  32707. var task = new ImageAssetTask(taskName, url);
  32708. this._tasks.push(task);
  32709. return task;
  32710. };
  32711. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  32712. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32713. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  32714. this._tasks.push(task);
  32715. return task;
  32716. };
  32717. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  32718. this._waitingTasksCount--;
  32719. if (this._waitingTasksCount === 0) {
  32720. if (this.onFinish) {
  32721. this.onFinish(this._tasks);
  32722. }
  32723. this._scene.getEngine().hideLoadingUI();
  32724. }
  32725. };
  32726. AssetsManager.prototype._runTask = function (task) {
  32727. var _this = this;
  32728. task.run(this._scene, function () {
  32729. if (_this.onTaskSuccess) {
  32730. _this.onTaskSuccess(task);
  32731. }
  32732. _this._decreaseWaitingTasksCount();
  32733. }, function () {
  32734. if (_this.onTaskError) {
  32735. _this.onTaskError(task);
  32736. }
  32737. _this._decreaseWaitingTasksCount();
  32738. });
  32739. };
  32740. AssetsManager.prototype.reset = function () {
  32741. this._tasks = new Array();
  32742. return this;
  32743. };
  32744. AssetsManager.prototype.load = function () {
  32745. this._waitingTasksCount = this._tasks.length;
  32746. if (this._waitingTasksCount === 0) {
  32747. if (this.onFinish) {
  32748. this.onFinish(this._tasks);
  32749. }
  32750. return this;
  32751. }
  32752. if (this.useDefaultLoadingScreen) {
  32753. this._scene.getEngine().displayLoadingUI();
  32754. }
  32755. for (var index = 0; index < this._tasks.length; index++) {
  32756. var task = this._tasks[index];
  32757. this._runTask(task);
  32758. }
  32759. return this;
  32760. };
  32761. return AssetsManager;
  32762. })();
  32763. BABYLON.AssetsManager = AssetsManager;
  32764. })(BABYLON || (BABYLON = {}));
  32765. var BABYLON;
  32766. (function (BABYLON) {
  32767. var VRDeviceOrientationFreeCamera = (function (_super) {
  32768. __extends(VRDeviceOrientationFreeCamera, _super);
  32769. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion) {
  32770. if (compensateDistortion === void 0) { compensateDistortion = true; }
  32771. _super.call(this, name, position, scene);
  32772. this._alpha = 0;
  32773. this._beta = 0;
  32774. this._gamma = 0;
  32775. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  32776. metrics.compensateDistortion = compensateDistortion;
  32777. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  32778. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  32779. }
  32780. VRDeviceOrientationFreeCamera.prototype._onOrientationEvent = function (evt) {
  32781. this._alpha = +evt.alpha | 0;
  32782. this._beta = +evt.beta | 0;
  32783. this._gamma = +evt.gamma | 0;
  32784. if (this._gamma < 0) {
  32785. this._gamma = 90 + this._gamma;
  32786. }
  32787. else {
  32788. // Incline it in the correct angle.
  32789. this._gamma = 270 - this._gamma;
  32790. }
  32791. this.rotation.x = this._gamma / 180.0 * Math.PI;
  32792. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  32793. this.rotation.z = this._beta / 180.0 * Math.PI;
  32794. };
  32795. VRDeviceOrientationFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  32796. _super.prototype.attachControl.call(this, element, noPreventDefault);
  32797. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  32798. };
  32799. VRDeviceOrientationFreeCamera.prototype.detachControl = function (element) {
  32800. _super.prototype.detachControl.call(this, element);
  32801. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  32802. };
  32803. return VRDeviceOrientationFreeCamera;
  32804. })(BABYLON.FreeCamera);
  32805. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  32806. })(BABYLON || (BABYLON = {}));
  32807. var BABYLON;
  32808. (function (BABYLON) {
  32809. var WebVRFreeCamera = (function (_super) {
  32810. __extends(WebVRFreeCamera, _super);
  32811. function WebVRFreeCamera(name, position, scene, compensateDistortion) {
  32812. if (compensateDistortion === void 0) { compensateDistortion = true; }
  32813. _super.call(this, name, position, scene);
  32814. this._hmdDevice = null;
  32815. this._sensorDevice = null;
  32816. this._cacheState = null;
  32817. this._cacheQuaternion = new BABYLON.Quaternion();
  32818. this._cacheRotation = BABYLON.Vector3.Zero();
  32819. this._vrEnabled = false;
  32820. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  32821. metrics.compensateDistortion = compensateDistortion;
  32822. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  32823. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  32824. }
  32825. WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
  32826. var size = devices.length;
  32827. var i = 0;
  32828. // Reset devices.
  32829. this._sensorDevice = null;
  32830. this._hmdDevice = null;
  32831. // Search for a HmdDevice.
  32832. while (i < size && this._hmdDevice === null) {
  32833. if (devices[i] instanceof HMDVRDevice) {
  32834. this._hmdDevice = devices[i];
  32835. }
  32836. i++;
  32837. }
  32838. i = 0;
  32839. while (i < size && this._sensorDevice === null) {
  32840. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  32841. this._sensorDevice = devices[i];
  32842. }
  32843. i++;
  32844. }
  32845. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  32846. };
  32847. WebVRFreeCamera.prototype._checkInputs = function () {
  32848. if (this._vrEnabled) {
  32849. this._cacheState = this._sensorDevice.getState();
  32850. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  32851. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  32852. this.rotation.x = -this._cacheRotation.z;
  32853. this.rotation.y = -this._cacheRotation.y;
  32854. this.rotation.z = this._cacheRotation.x;
  32855. }
  32856. _super.prototype._checkInputs.call(this);
  32857. };
  32858. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  32859. _super.prototype.attachControl.call(this, element, noPreventDefault);
  32860. if (navigator.getVRDevices) {
  32861. navigator.getVRDevices().then(this._getWebVRDevices);
  32862. }
  32863. else if (navigator.mozGetVRDevices) {
  32864. navigator.mozGetVRDevices(this._getWebVRDevices);
  32865. }
  32866. };
  32867. WebVRFreeCamera.prototype.detachControl = function (element) {
  32868. _super.prototype.detachControl.call(this, element);
  32869. this._vrEnabled = false;
  32870. };
  32871. return WebVRFreeCamera;
  32872. })(BABYLON.FreeCamera);
  32873. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  32874. })(BABYLON || (BABYLON = {}));
  32875. var BABYLON;
  32876. (function (BABYLON) {
  32877. // Standard optimizations
  32878. var SceneOptimization = (function () {
  32879. function SceneOptimization(priority) {
  32880. if (priority === void 0) { priority = 0; }
  32881. this.priority = priority;
  32882. this.apply = function (scene) {
  32883. return true; // Return true if everything that can be done was applied
  32884. };
  32885. }
  32886. return SceneOptimization;
  32887. })();
  32888. BABYLON.SceneOptimization = SceneOptimization;
  32889. var TextureOptimization = (function (_super) {
  32890. __extends(TextureOptimization, _super);
  32891. function TextureOptimization(priority, maximumSize) {
  32892. var _this = this;
  32893. if (priority === void 0) { priority = 0; }
  32894. if (maximumSize === void 0) { maximumSize = 1024; }
  32895. _super.call(this, priority);
  32896. this.priority = priority;
  32897. this.maximumSize = maximumSize;
  32898. this.apply = function (scene) {
  32899. var allDone = true;
  32900. for (var index = 0; index < scene.textures.length; index++) {
  32901. var texture = scene.textures[index];
  32902. if (!texture.canRescale) {
  32903. continue;
  32904. }
  32905. var currentSize = texture.getSize();
  32906. var maxDimension = Math.max(currentSize.width, currentSize.height);
  32907. if (maxDimension > _this.maximumSize) {
  32908. texture.scale(0.5);
  32909. allDone = false;
  32910. }
  32911. }
  32912. return allDone;
  32913. };
  32914. }
  32915. return TextureOptimization;
  32916. })(SceneOptimization);
  32917. BABYLON.TextureOptimization = TextureOptimization;
  32918. var HardwareScalingOptimization = (function (_super) {
  32919. __extends(HardwareScalingOptimization, _super);
  32920. function HardwareScalingOptimization(priority, maximumScale) {
  32921. var _this = this;
  32922. if (priority === void 0) { priority = 0; }
  32923. if (maximumScale === void 0) { maximumScale = 2; }
  32924. _super.call(this, priority);
  32925. this.priority = priority;
  32926. this.maximumScale = maximumScale;
  32927. this._currentScale = 1;
  32928. this.apply = function (scene) {
  32929. _this._currentScale++;
  32930. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  32931. return _this._currentScale >= _this.maximumScale;
  32932. };
  32933. }
  32934. return HardwareScalingOptimization;
  32935. })(SceneOptimization);
  32936. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  32937. var ShadowsOptimization = (function (_super) {
  32938. __extends(ShadowsOptimization, _super);
  32939. function ShadowsOptimization() {
  32940. _super.apply(this, arguments);
  32941. this.apply = function (scene) {
  32942. scene.shadowsEnabled = false;
  32943. return true;
  32944. };
  32945. }
  32946. return ShadowsOptimization;
  32947. })(SceneOptimization);
  32948. BABYLON.ShadowsOptimization = ShadowsOptimization;
  32949. var PostProcessesOptimization = (function (_super) {
  32950. __extends(PostProcessesOptimization, _super);
  32951. function PostProcessesOptimization() {
  32952. _super.apply(this, arguments);
  32953. this.apply = function (scene) {
  32954. scene.postProcessesEnabled = false;
  32955. return true;
  32956. };
  32957. }
  32958. return PostProcessesOptimization;
  32959. })(SceneOptimization);
  32960. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  32961. var LensFlaresOptimization = (function (_super) {
  32962. __extends(LensFlaresOptimization, _super);
  32963. function LensFlaresOptimization() {
  32964. _super.apply(this, arguments);
  32965. this.apply = function (scene) {
  32966. scene.lensFlaresEnabled = false;
  32967. return true;
  32968. };
  32969. }
  32970. return LensFlaresOptimization;
  32971. })(SceneOptimization);
  32972. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  32973. var ParticlesOptimization = (function (_super) {
  32974. __extends(ParticlesOptimization, _super);
  32975. function ParticlesOptimization() {
  32976. _super.apply(this, arguments);
  32977. this.apply = function (scene) {
  32978. scene.particlesEnabled = false;
  32979. return true;
  32980. };
  32981. }
  32982. return ParticlesOptimization;
  32983. })(SceneOptimization);
  32984. BABYLON.ParticlesOptimization = ParticlesOptimization;
  32985. var RenderTargetsOptimization = (function (_super) {
  32986. __extends(RenderTargetsOptimization, _super);
  32987. function RenderTargetsOptimization() {
  32988. _super.apply(this, arguments);
  32989. this.apply = function (scene) {
  32990. scene.renderTargetsEnabled = false;
  32991. return true;
  32992. };
  32993. }
  32994. return RenderTargetsOptimization;
  32995. })(SceneOptimization);
  32996. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  32997. var MergeMeshesOptimization = (function (_super) {
  32998. __extends(MergeMeshesOptimization, _super);
  32999. function MergeMeshesOptimization() {
  33000. var _this = this;
  33001. _super.apply(this, arguments);
  33002. this._canBeMerged = function (abstractMesh) {
  33003. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  33004. return false;
  33005. }
  33006. var mesh = abstractMesh;
  33007. if (!mesh.isVisible || !mesh.isEnabled()) {
  33008. return false;
  33009. }
  33010. if (mesh.instances.length > 0) {
  33011. return false;
  33012. }
  33013. if (mesh.skeleton || mesh.hasLODLevels) {
  33014. return false;
  33015. }
  33016. if (mesh.parent) {
  33017. return false;
  33018. }
  33019. return true;
  33020. };
  33021. this.apply = function (scene, updateSelectionTree) {
  33022. var globalPool = scene.meshes.slice(0);
  33023. var globalLength = globalPool.length;
  33024. for (var index = 0; index < globalLength; index++) {
  33025. var currentPool = new Array();
  33026. var current = globalPool[index];
  33027. // Checks
  33028. if (!_this._canBeMerged(current)) {
  33029. continue;
  33030. }
  33031. currentPool.push(current);
  33032. // Find compatible meshes
  33033. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  33034. var otherMesh = globalPool[subIndex];
  33035. if (!_this._canBeMerged(otherMesh)) {
  33036. continue;
  33037. }
  33038. if (otherMesh.material !== current.material) {
  33039. continue;
  33040. }
  33041. if (otherMesh.checkCollisions !== current.checkCollisions) {
  33042. continue;
  33043. }
  33044. currentPool.push(otherMesh);
  33045. globalLength--;
  33046. globalPool.splice(subIndex, 1);
  33047. subIndex--;
  33048. }
  33049. if (currentPool.length < 2) {
  33050. continue;
  33051. }
  33052. // Merge meshes
  33053. BABYLON.Mesh.MergeMeshes(currentPool);
  33054. }
  33055. if (updateSelectionTree != undefined) {
  33056. if (updateSelectionTree) {
  33057. scene.createOrUpdateSelectionOctree();
  33058. }
  33059. }
  33060. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  33061. scene.createOrUpdateSelectionOctree();
  33062. }
  33063. return true;
  33064. };
  33065. }
  33066. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  33067. get: function () {
  33068. return MergeMeshesOptimization._UpdateSelectionTree;
  33069. },
  33070. set: function (value) {
  33071. MergeMeshesOptimization._UpdateSelectionTree = value;
  33072. },
  33073. enumerable: true,
  33074. configurable: true
  33075. });
  33076. MergeMeshesOptimization._UpdateSelectionTree = false;
  33077. return MergeMeshesOptimization;
  33078. })(SceneOptimization);
  33079. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  33080. // Options
  33081. var SceneOptimizerOptions = (function () {
  33082. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  33083. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  33084. if (trackerDuration === void 0) { trackerDuration = 2000; }
  33085. this.targetFrameRate = targetFrameRate;
  33086. this.trackerDuration = trackerDuration;
  33087. this.optimizations = new Array();
  33088. }
  33089. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  33090. var result = new SceneOptimizerOptions(targetFrameRate);
  33091. var priority = 0;
  33092. result.optimizations.push(new MergeMeshesOptimization(priority));
  33093. result.optimizations.push(new ShadowsOptimization(priority));
  33094. result.optimizations.push(new LensFlaresOptimization(priority));
  33095. // Next priority
  33096. priority++;
  33097. result.optimizations.push(new PostProcessesOptimization(priority));
  33098. result.optimizations.push(new ParticlesOptimization(priority));
  33099. // Next priority
  33100. priority++;
  33101. result.optimizations.push(new TextureOptimization(priority, 1024));
  33102. return result;
  33103. };
  33104. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  33105. var result = new SceneOptimizerOptions(targetFrameRate);
  33106. var priority = 0;
  33107. result.optimizations.push(new MergeMeshesOptimization(priority));
  33108. result.optimizations.push(new ShadowsOptimization(priority));
  33109. result.optimizations.push(new LensFlaresOptimization(priority));
  33110. // Next priority
  33111. priority++;
  33112. result.optimizations.push(new PostProcessesOptimization(priority));
  33113. result.optimizations.push(new ParticlesOptimization(priority));
  33114. // Next priority
  33115. priority++;
  33116. result.optimizations.push(new TextureOptimization(priority, 512));
  33117. // Next priority
  33118. priority++;
  33119. result.optimizations.push(new RenderTargetsOptimization(priority));
  33120. // Next priority
  33121. priority++;
  33122. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  33123. return result;
  33124. };
  33125. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  33126. var result = new SceneOptimizerOptions(targetFrameRate);
  33127. var priority = 0;
  33128. result.optimizations.push(new MergeMeshesOptimization(priority));
  33129. result.optimizations.push(new ShadowsOptimization(priority));
  33130. result.optimizations.push(new LensFlaresOptimization(priority));
  33131. // Next priority
  33132. priority++;
  33133. result.optimizations.push(new PostProcessesOptimization(priority));
  33134. result.optimizations.push(new ParticlesOptimization(priority));
  33135. // Next priority
  33136. priority++;
  33137. result.optimizations.push(new TextureOptimization(priority, 256));
  33138. // Next priority
  33139. priority++;
  33140. result.optimizations.push(new RenderTargetsOptimization(priority));
  33141. // Next priority
  33142. priority++;
  33143. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  33144. return result;
  33145. };
  33146. return SceneOptimizerOptions;
  33147. })();
  33148. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  33149. // Scene optimizer tool
  33150. var SceneOptimizer = (function () {
  33151. function SceneOptimizer() {
  33152. }
  33153. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  33154. // TODO: add an epsilon
  33155. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  33156. if (onSuccess) {
  33157. onSuccess();
  33158. }
  33159. return;
  33160. }
  33161. // Apply current level of optimizations
  33162. var allDone = true;
  33163. var noOptimizationApplied = true;
  33164. for (var index = 0; index < options.optimizations.length; index++) {
  33165. var optimization = options.optimizations[index];
  33166. if (optimization.priority === currentPriorityLevel) {
  33167. noOptimizationApplied = false;
  33168. allDone = allDone && optimization.apply(scene);
  33169. }
  33170. }
  33171. // If no optimization was applied, this is a failure :(
  33172. if (noOptimizationApplied) {
  33173. if (onFailure) {
  33174. onFailure();
  33175. }
  33176. return;
  33177. }
  33178. // If all optimizations were done, move to next level
  33179. if (allDone) {
  33180. currentPriorityLevel++;
  33181. }
  33182. // Let's the system running for a specific amount of time before checking FPS
  33183. scene.executeWhenReady(function () {
  33184. setTimeout(function () {
  33185. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  33186. }, options.trackerDuration);
  33187. });
  33188. };
  33189. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  33190. if (!options) {
  33191. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  33192. }
  33193. // Let's the system running for a specific amount of time before checking FPS
  33194. scene.executeWhenReady(function () {
  33195. setTimeout(function () {
  33196. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  33197. }, options.trackerDuration);
  33198. });
  33199. };
  33200. return SceneOptimizer;
  33201. })();
  33202. BABYLON.SceneOptimizer = SceneOptimizer;
  33203. })(BABYLON || (BABYLON = {}));
  33204. var BABYLON;
  33205. (function (BABYLON) {
  33206. var Internals;
  33207. (function (Internals) {
  33208. var MeshLODLevel = (function () {
  33209. function MeshLODLevel(distance, mesh) {
  33210. this.distance = distance;
  33211. this.mesh = mesh;
  33212. }
  33213. return MeshLODLevel;
  33214. })();
  33215. Internals.MeshLODLevel = MeshLODLevel;
  33216. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  33217. })(BABYLON || (BABYLON = {}));
  33218. var BABYLON;
  33219. (function (BABYLON) {
  33220. var RawTexture = (function (_super) {
  33221. __extends(RawTexture, _super);
  33222. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  33223. if (generateMipMaps === void 0) { generateMipMaps = true; }
  33224. if (invertY === void 0) { invertY = false; }
  33225. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33226. _super.call(this, null, scene, !generateMipMaps, invertY);
  33227. this.format = format;
  33228. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  33229. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33230. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33231. }
  33232. RawTexture.prototype.update = function (data) {
  33233. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  33234. };
  33235. // Statics
  33236. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  33237. if (generateMipMaps === void 0) { generateMipMaps = true; }
  33238. if (invertY === void 0) { invertY = false; }
  33239. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33240. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  33241. };
  33242. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  33243. if (generateMipMaps === void 0) { generateMipMaps = true; }
  33244. if (invertY === void 0) { invertY = false; }
  33245. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33246. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  33247. };
  33248. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  33249. if (generateMipMaps === void 0) { generateMipMaps = true; }
  33250. if (invertY === void 0) { invertY = false; }
  33251. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33252. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  33253. };
  33254. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  33255. if (generateMipMaps === void 0) { generateMipMaps = true; }
  33256. if (invertY === void 0) { invertY = false; }
  33257. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33258. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  33259. };
  33260. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  33261. if (generateMipMaps === void 0) { generateMipMaps = true; }
  33262. if (invertY === void 0) { invertY = false; }
  33263. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33264. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  33265. };
  33266. return RawTexture;
  33267. })(BABYLON.Texture);
  33268. BABYLON.RawTexture = RawTexture;
  33269. })(BABYLON || (BABYLON = {}));
  33270. var BABYLON;
  33271. (function (BABYLON) {
  33272. var IndexedVector2 = (function (_super) {
  33273. __extends(IndexedVector2, _super);
  33274. function IndexedVector2(original, index) {
  33275. _super.call(this, original.x, original.y);
  33276. this.index = index;
  33277. }
  33278. return IndexedVector2;
  33279. })(BABYLON.Vector2);
  33280. var PolygonPoints = (function () {
  33281. function PolygonPoints() {
  33282. this.elements = new Array();
  33283. }
  33284. PolygonPoints.prototype.add = function (originalPoints) {
  33285. var _this = this;
  33286. var result = new Array();
  33287. originalPoints.forEach(function (point) {
  33288. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  33289. var newPoint = new IndexedVector2(point, _this.elements.length);
  33290. result.push(newPoint);
  33291. _this.elements.push(newPoint);
  33292. }
  33293. });
  33294. return result;
  33295. };
  33296. PolygonPoints.prototype.computeBounds = function () {
  33297. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  33298. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  33299. this.elements.forEach(function (point) {
  33300. // x
  33301. if (point.x < lmin.x) {
  33302. lmin.x = point.x;
  33303. }
  33304. else if (point.x > lmax.x) {
  33305. lmax.x = point.x;
  33306. }
  33307. // y
  33308. if (point.y < lmin.y) {
  33309. lmin.y = point.y;
  33310. }
  33311. else if (point.y > lmax.y) {
  33312. lmax.y = point.y;
  33313. }
  33314. });
  33315. return {
  33316. min: lmin,
  33317. max: lmax,
  33318. width: lmax.x - lmin.x,
  33319. height: lmax.y - lmin.y
  33320. };
  33321. };
  33322. return PolygonPoints;
  33323. })();
  33324. var Polygon = (function () {
  33325. function Polygon() {
  33326. }
  33327. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  33328. return [
  33329. new BABYLON.Vector2(xmin, ymin),
  33330. new BABYLON.Vector2(xmax, ymin),
  33331. new BABYLON.Vector2(xmax, ymax),
  33332. new BABYLON.Vector2(xmin, ymax)
  33333. ];
  33334. };
  33335. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  33336. if (cx === void 0) { cx = 0; }
  33337. if (cy === void 0) { cy = 0; }
  33338. if (numberOfSides === void 0) { numberOfSides = 32; }
  33339. var result = new Array();
  33340. var angle = 0;
  33341. var increment = (Math.PI * 2) / numberOfSides;
  33342. for (var i = 0; i < numberOfSides; i++) {
  33343. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  33344. angle -= increment;
  33345. }
  33346. return result;
  33347. };
  33348. Polygon.Parse = function (input) {
  33349. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  33350. var i, result = [];
  33351. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  33352. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  33353. }
  33354. return result;
  33355. };
  33356. Polygon.StartingAt = function (x, y) {
  33357. return BABYLON.Path2.StartingAt(x, y);
  33358. };
  33359. return Polygon;
  33360. })();
  33361. BABYLON.Polygon = Polygon;
  33362. var PolygonMeshBuilder = (function () {
  33363. function PolygonMeshBuilder(name, contours, scene) {
  33364. this._points = new PolygonPoints();
  33365. this._outlinepoints = new PolygonPoints();
  33366. this._holes = [];
  33367. if (!("poly2tri" in window)) {
  33368. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  33369. }
  33370. this._name = name;
  33371. this._scene = scene;
  33372. var points;
  33373. if (contours instanceof BABYLON.Path2) {
  33374. points = contours.getPoints();
  33375. }
  33376. else {
  33377. points = contours;
  33378. }
  33379. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  33380. this._outlinepoints.add(points);
  33381. }
  33382. PolygonMeshBuilder.prototype.addHole = function (hole) {
  33383. this._swctx.addHole(this._points.add(hole));
  33384. var holepoints = new PolygonPoints();
  33385. holepoints.add(hole);
  33386. this._holes.push(holepoints);
  33387. return this;
  33388. };
  33389. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  33390. var _this = this;
  33391. if (updatable === void 0) { updatable = false; }
  33392. var result = new BABYLON.Mesh(this._name, this._scene);
  33393. var normals = [];
  33394. var positions = [];
  33395. var uvs = [];
  33396. var bounds = this._points.computeBounds();
  33397. this._points.elements.forEach(function (p) {
  33398. normals.push(0, 1.0, 0);
  33399. positions.push(p.x, 0, p.y);
  33400. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  33401. });
  33402. var indices = [];
  33403. this._swctx.triangulate();
  33404. this._swctx.getTriangles().forEach(function (triangle) {
  33405. triangle.getPoints().forEach(function (point) {
  33406. indices.push(point.index);
  33407. });
  33408. });
  33409. if (depth > 0) {
  33410. var positionscount = (positions.length / 3); //get the current pointcount
  33411. this._points.elements.forEach(function (p) {
  33412. normals.push(0, -1.0, 0);
  33413. positions.push(p.x, -depth, p.y);
  33414. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  33415. });
  33416. var p1; //we need to change order of point so the triangles are made in the rigth way.
  33417. var p2;
  33418. var poscounter = 0;
  33419. this._swctx.getTriangles().forEach(function (triangle) {
  33420. triangle.getPoints().forEach(function (point) {
  33421. switch (poscounter) {
  33422. case 0:
  33423. p1 = point;
  33424. break;
  33425. case 1:
  33426. p2 = point;
  33427. break;
  33428. case 2:
  33429. indices.push(point.index + positionscount);
  33430. indices.push(p2.index + positionscount);
  33431. indices.push(p1.index + positionscount);
  33432. poscounter = -1;
  33433. break;
  33434. }
  33435. poscounter++;
  33436. //indices.push((<IndexedVector2>point).index + positionscount);
  33437. });
  33438. });
  33439. //Add the sides
  33440. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  33441. this._holes.forEach(function (hole) {
  33442. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  33443. });
  33444. }
  33445. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  33446. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  33447. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  33448. result.setIndices(indices);
  33449. return result;
  33450. };
  33451. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  33452. var StartIndex = positions.length / 3;
  33453. var ulength = 0;
  33454. for (var i = 0; i < points.elements.length; i++) {
  33455. var p = points.elements[i];
  33456. var p1;
  33457. if ((i + 1) > points.elements.length - 1) {
  33458. p1 = points.elements[0];
  33459. }
  33460. else {
  33461. p1 = points.elements[i + 1];
  33462. }
  33463. positions.push(p.x, 0, p.y);
  33464. positions.push(p.x, -depth, p.y);
  33465. positions.push(p1.x, 0, p1.y);
  33466. positions.push(p1.x, -depth, p1.y);
  33467. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  33468. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  33469. var v3 = v2.subtract(v1);
  33470. var v4 = new BABYLON.Vector3(0, 1, 0);
  33471. var vn = BABYLON.Vector3.Cross(v3, v4);
  33472. vn = vn.normalize();
  33473. uvs.push(ulength / bounds.width, 0);
  33474. uvs.push(ulength / bounds.width, 1);
  33475. ulength += v3.length();
  33476. uvs.push((ulength / bounds.width), 0);
  33477. uvs.push((ulength / bounds.width), 1);
  33478. if (!flip) {
  33479. normals.push(-vn.x, -vn.y, -vn.z);
  33480. normals.push(-vn.x, -vn.y, -vn.z);
  33481. normals.push(-vn.x, -vn.y, -vn.z);
  33482. normals.push(-vn.x, -vn.y, -vn.z);
  33483. indices.push(StartIndex);
  33484. indices.push(StartIndex + 1);
  33485. indices.push(StartIndex + 2);
  33486. indices.push(StartIndex + 1);
  33487. indices.push(StartIndex + 3);
  33488. indices.push(StartIndex + 2);
  33489. }
  33490. else {
  33491. normals.push(vn.x, vn.y, vn.z);
  33492. normals.push(vn.x, vn.y, vn.z);
  33493. normals.push(vn.x, vn.y, vn.z);
  33494. normals.push(vn.x, vn.y, vn.z);
  33495. indices.push(StartIndex);
  33496. indices.push(StartIndex + 2);
  33497. indices.push(StartIndex + 1);
  33498. indices.push(StartIndex + 1);
  33499. indices.push(StartIndex + 2);
  33500. indices.push(StartIndex + 3);
  33501. }
  33502. StartIndex += 4;
  33503. }
  33504. ;
  33505. };
  33506. return PolygonMeshBuilder;
  33507. })();
  33508. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  33509. })(BABYLON || (BABYLON = {}));
  33510. var BABYLON;
  33511. (function (BABYLON) {
  33512. var Octree = (function () {
  33513. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  33514. if (maxDepth === void 0) { maxDepth = 2; }
  33515. this.maxDepth = maxDepth;
  33516. this.dynamicContent = new Array();
  33517. this._maxBlockCapacity = maxBlockCapacity || 64;
  33518. this._selectionContent = new BABYLON.SmartArray(1024);
  33519. this._creationFunc = creationFunc;
  33520. }
  33521. // Methods
  33522. Octree.prototype.update = function (worldMin, worldMax, entries) {
  33523. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  33524. };
  33525. Octree.prototype.addMesh = function (entry) {
  33526. for (var index = 0; index < this.blocks.length; index++) {
  33527. var block = this.blocks[index];
  33528. block.addEntry(entry);
  33529. }
  33530. };
  33531. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  33532. this._selectionContent.reset();
  33533. for (var index = 0; index < this.blocks.length; index++) {
  33534. var block = this.blocks[index];
  33535. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  33536. }
  33537. if (allowDuplicate) {
  33538. this._selectionContent.concat(this.dynamicContent);
  33539. }
  33540. else {
  33541. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  33542. }
  33543. return this._selectionContent;
  33544. };
  33545. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  33546. this._selectionContent.reset();
  33547. for (var index = 0; index < this.blocks.length; index++) {
  33548. var block = this.blocks[index];
  33549. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  33550. }
  33551. if (allowDuplicate) {
  33552. this._selectionContent.concat(this.dynamicContent);
  33553. }
  33554. else {
  33555. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  33556. }
  33557. return this._selectionContent;
  33558. };
  33559. Octree.prototype.intersectsRay = function (ray) {
  33560. this._selectionContent.reset();
  33561. for (var index = 0; index < this.blocks.length; index++) {
  33562. var block = this.blocks[index];
  33563. block.intersectsRay(ray, this._selectionContent);
  33564. }
  33565. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  33566. return this._selectionContent;
  33567. };
  33568. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  33569. target.blocks = new Array();
  33570. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  33571. // Segmenting space
  33572. for (var x = 0; x < 2; x++) {
  33573. for (var y = 0; y < 2; y++) {
  33574. for (var z = 0; z < 2; z++) {
  33575. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  33576. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  33577. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  33578. block.addEntries(entries);
  33579. target.blocks.push(block);
  33580. }
  33581. }
  33582. }
  33583. };
  33584. Octree.CreationFuncForMeshes = function (entry, block) {
  33585. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  33586. block.entries.push(entry);
  33587. }
  33588. };
  33589. Octree.CreationFuncForSubMeshes = function (entry, block) {
  33590. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  33591. block.entries.push(entry);
  33592. }
  33593. };
  33594. return Octree;
  33595. })();
  33596. BABYLON.Octree = Octree;
  33597. })(BABYLON || (BABYLON = {}));
  33598. var BABYLON;
  33599. (function (BABYLON) {
  33600. var OctreeBlock = (function () {
  33601. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  33602. this.entries = new Array();
  33603. this._boundingVectors = new Array();
  33604. this._capacity = capacity;
  33605. this._depth = depth;
  33606. this._maxDepth = maxDepth;
  33607. this._creationFunc = creationFunc;
  33608. this._minPoint = minPoint;
  33609. this._maxPoint = maxPoint;
  33610. this._boundingVectors.push(minPoint.clone());
  33611. this._boundingVectors.push(maxPoint.clone());
  33612. this._boundingVectors.push(minPoint.clone());
  33613. this._boundingVectors[2].x = maxPoint.x;
  33614. this._boundingVectors.push(minPoint.clone());
  33615. this._boundingVectors[3].y = maxPoint.y;
  33616. this._boundingVectors.push(minPoint.clone());
  33617. this._boundingVectors[4].z = maxPoint.z;
  33618. this._boundingVectors.push(maxPoint.clone());
  33619. this._boundingVectors[5].z = minPoint.z;
  33620. this._boundingVectors.push(maxPoint.clone());
  33621. this._boundingVectors[6].x = minPoint.x;
  33622. this._boundingVectors.push(maxPoint.clone());
  33623. this._boundingVectors[7].y = minPoint.y;
  33624. }
  33625. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  33626. // Property
  33627. get: function () {
  33628. return this._capacity;
  33629. },
  33630. enumerable: true,
  33631. configurable: true
  33632. });
  33633. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  33634. get: function () {
  33635. return this._minPoint;
  33636. },
  33637. enumerable: true,
  33638. configurable: true
  33639. });
  33640. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  33641. get: function () {
  33642. return this._maxPoint;
  33643. },
  33644. enumerable: true,
  33645. configurable: true
  33646. });
  33647. // Methods
  33648. OctreeBlock.prototype.addEntry = function (entry) {
  33649. if (this.blocks) {
  33650. for (var index = 0; index < this.blocks.length; index++) {
  33651. var block = this.blocks[index];
  33652. block.addEntry(entry);
  33653. }
  33654. return;
  33655. }
  33656. this._creationFunc(entry, this);
  33657. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  33658. this.createInnerBlocks();
  33659. }
  33660. };
  33661. OctreeBlock.prototype.addEntries = function (entries) {
  33662. for (var index = 0; index < entries.length; index++) {
  33663. var mesh = entries[index];
  33664. this.addEntry(mesh);
  33665. }
  33666. };
  33667. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  33668. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  33669. if (this.blocks) {
  33670. for (var index = 0; index < this.blocks.length; index++) {
  33671. var block = this.blocks[index];
  33672. block.select(frustumPlanes, selection, allowDuplicate);
  33673. }
  33674. return;
  33675. }
  33676. if (allowDuplicate) {
  33677. selection.concat(this.entries);
  33678. }
  33679. else {
  33680. selection.concatWithNoDuplicate(this.entries);
  33681. }
  33682. }
  33683. };
  33684. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  33685. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  33686. if (this.blocks) {
  33687. for (var index = 0; index < this.blocks.length; index++) {
  33688. var block = this.blocks[index];
  33689. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  33690. }
  33691. return;
  33692. }
  33693. if (allowDuplicate) {
  33694. selection.concat(this.entries);
  33695. }
  33696. else {
  33697. selection.concatWithNoDuplicate(this.entries);
  33698. }
  33699. }
  33700. };
  33701. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  33702. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  33703. if (this.blocks) {
  33704. for (var index = 0; index < this.blocks.length; index++) {
  33705. var block = this.blocks[index];
  33706. block.intersectsRay(ray, selection);
  33707. }
  33708. return;
  33709. }
  33710. selection.concatWithNoDuplicate(this.entries);
  33711. }
  33712. };
  33713. OctreeBlock.prototype.createInnerBlocks = function () {
  33714. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  33715. };
  33716. return OctreeBlock;
  33717. })();
  33718. BABYLON.OctreeBlock = OctreeBlock;
  33719. })(BABYLON || (BABYLON = {}));
  33720. var BABYLON;
  33721. (function (BABYLON) {
  33722. var BlurPostProcess = (function (_super) {
  33723. __extends(BlurPostProcess, _super);
  33724. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  33725. var _this = this;
  33726. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  33727. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  33728. this.direction = direction;
  33729. this.blurWidth = blurWidth;
  33730. this.onApply = function (effect) {
  33731. effect.setFloat2("screenSize", _this.width, _this.height);
  33732. effect.setVector2("direction", _this.direction);
  33733. effect.setFloat("blurWidth", _this.blurWidth);
  33734. };
  33735. }
  33736. return BlurPostProcess;
  33737. })(BABYLON.PostProcess);
  33738. BABYLON.BlurPostProcess = BlurPostProcess;
  33739. })(BABYLON || (BABYLON = {}));
  33740. var BABYLON;
  33741. (function (BABYLON) {
  33742. var RefractionPostProcess = (function (_super) {
  33743. __extends(RefractionPostProcess, _super);
  33744. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  33745. var _this = this;
  33746. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  33747. this.color = color;
  33748. this.depth = depth;
  33749. this.colorLevel = colorLevel;
  33750. this.onActivate = function (cam) {
  33751. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  33752. };
  33753. this.onApply = function (effect) {
  33754. effect.setColor3("baseColor", _this.color);
  33755. effect.setFloat("depth", _this.depth);
  33756. effect.setFloat("colorLevel", _this.colorLevel);
  33757. effect.setTexture("refractionSampler", _this._refRexture);
  33758. };
  33759. }
  33760. // Methods
  33761. RefractionPostProcess.prototype.dispose = function (camera) {
  33762. if (this._refRexture) {
  33763. this._refRexture.dispose();
  33764. }
  33765. _super.prototype.dispose.call(this, camera);
  33766. };
  33767. return RefractionPostProcess;
  33768. })(BABYLON.PostProcess);
  33769. BABYLON.RefractionPostProcess = RefractionPostProcess;
  33770. })(BABYLON || (BABYLON = {}));
  33771. var BABYLON;
  33772. (function (BABYLON) {
  33773. var BlackAndWhitePostProcess = (function (_super) {
  33774. __extends(BlackAndWhitePostProcess, _super);
  33775. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  33776. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  33777. }
  33778. return BlackAndWhitePostProcess;
  33779. })(BABYLON.PostProcess);
  33780. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  33781. })(BABYLON || (BABYLON = {}));
  33782. var BABYLON;
  33783. (function (BABYLON) {
  33784. var ConvolutionPostProcess = (function (_super) {
  33785. __extends(ConvolutionPostProcess, _super);
  33786. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  33787. var _this = this;
  33788. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  33789. this.kernel = kernel;
  33790. this.onApply = function (effect) {
  33791. effect.setFloat2("screenSize", _this.width, _this.height);
  33792. effect.setArray("kernel", _this.kernel);
  33793. };
  33794. }
  33795. // Statics
  33796. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  33797. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  33798. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  33799. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  33800. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  33801. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  33802. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  33803. return ConvolutionPostProcess;
  33804. })(BABYLON.PostProcess);
  33805. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  33806. })(BABYLON || (BABYLON = {}));
  33807. var BABYLON;
  33808. (function (BABYLON) {
  33809. var FilterPostProcess = (function (_super) {
  33810. __extends(FilterPostProcess, _super);
  33811. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  33812. var _this = this;
  33813. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  33814. this.kernelMatrix = kernelMatrix;
  33815. this.onApply = function (effect) {
  33816. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  33817. };
  33818. }
  33819. return FilterPostProcess;
  33820. })(BABYLON.PostProcess);
  33821. BABYLON.FilterPostProcess = FilterPostProcess;
  33822. })(BABYLON || (BABYLON = {}));
  33823. var BABYLON;
  33824. (function (BABYLON) {
  33825. var FxaaPostProcess = (function (_super) {
  33826. __extends(FxaaPostProcess, _super);
  33827. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  33828. var _this = this;
  33829. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  33830. this.onSizeChanged = function () {
  33831. _this.texelWidth = 1.0 / _this.width;
  33832. _this.texelHeight = 1.0 / _this.height;
  33833. };
  33834. this.onApply = function (effect) {
  33835. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  33836. };
  33837. }
  33838. return FxaaPostProcess;
  33839. })(BABYLON.PostProcess);
  33840. BABYLON.FxaaPostProcess = FxaaPostProcess;
  33841. })(BABYLON || (BABYLON = {}));
  33842. var BABYLON;
  33843. (function (BABYLON) {
  33844. var StereoscopicInterlacePostProcess = (function (_super) {
  33845. __extends(StereoscopicInterlacePostProcess, _super);
  33846. function StereoscopicInterlacePostProcess(name, camB, postProcessA, isStereoscopicHoriz, samplingMode) {
  33847. var _this = this;
  33848. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, camB, samplingMode, camB.getScene().getEngine(), false, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  33849. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  33850. this.onSizeChanged = function () {
  33851. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  33852. };
  33853. this.onApply = function (effect) {
  33854. effect.setTextureFromPostProcess("camASampler", postProcessA);
  33855. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  33856. };
  33857. }
  33858. return StereoscopicInterlacePostProcess;
  33859. })(BABYLON.PostProcess);
  33860. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  33861. })(BABYLON || (BABYLON = {}));
  33862. var BABYLON;
  33863. (function (BABYLON) {
  33864. var LensFlare = (function () {
  33865. function LensFlare(size, position, color, imgUrl, system) {
  33866. this.size = size;
  33867. this.position = position;
  33868. this.dispose = function () {
  33869. if (this.texture) {
  33870. this.texture.dispose();
  33871. }
  33872. // Remove from scene
  33873. var index = this._system.lensFlares.indexOf(this);
  33874. this._system.lensFlares.splice(index, 1);
  33875. };
  33876. this.color = color || new BABYLON.Color3(1, 1, 1);
  33877. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  33878. this._system = system;
  33879. system.lensFlares.push(this);
  33880. }
  33881. return LensFlare;
  33882. })();
  33883. BABYLON.LensFlare = LensFlare;
  33884. })(BABYLON || (BABYLON = {}));
  33885. var BABYLON;
  33886. (function (BABYLON) {
  33887. var LensFlareSystem = (function () {
  33888. function LensFlareSystem(name, emitter, scene) {
  33889. this.name = name;
  33890. this.lensFlares = new Array();
  33891. this.borderLimit = 300;
  33892. this.layerMask = 0x0FFFFFFF;
  33893. this._vertexDeclaration = [2];
  33894. this._vertexStrideSize = 2 * 4;
  33895. this._isEnabled = true;
  33896. this._scene = scene;
  33897. this._emitter = emitter;
  33898. scene.lensFlareSystems.push(this);
  33899. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  33900. // VBO
  33901. var vertices = [];
  33902. vertices.push(1, 1);
  33903. vertices.push(-1, 1);
  33904. vertices.push(-1, -1);
  33905. vertices.push(1, -1);
  33906. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  33907. // Indices
  33908. var indices = [];
  33909. indices.push(0);
  33910. indices.push(1);
  33911. indices.push(2);
  33912. indices.push(0);
  33913. indices.push(2);
  33914. indices.push(3);
  33915. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  33916. // Effects
  33917. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  33918. }
  33919. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  33920. get: function () {
  33921. return this._isEnabled;
  33922. },
  33923. set: function (value) {
  33924. this._isEnabled = value;
  33925. },
  33926. enumerable: true,
  33927. configurable: true
  33928. });
  33929. LensFlareSystem.prototype.getScene = function () {
  33930. return this._scene;
  33931. };
  33932. LensFlareSystem.prototype.getEmitter = function () {
  33933. return this._emitter;
  33934. };
  33935. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  33936. this._emitter = newEmitter;
  33937. };
  33938. LensFlareSystem.prototype.getEmitterPosition = function () {
  33939. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  33940. };
  33941. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  33942. var position = this.getEmitterPosition();
  33943. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  33944. this._positionX = position.x;
  33945. this._positionY = position.y;
  33946. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  33947. if (position.z > 0) {
  33948. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  33949. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  33950. return true;
  33951. }
  33952. }
  33953. return false;
  33954. };
  33955. LensFlareSystem.prototype._isVisible = function () {
  33956. if (!this._isEnabled) {
  33957. return false;
  33958. }
  33959. var emitterPosition = this.getEmitterPosition();
  33960. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  33961. var distance = direction.length();
  33962. direction.normalize();
  33963. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  33964. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  33965. return !pickInfo.hit || pickInfo.distance > distance;
  33966. };
  33967. LensFlareSystem.prototype.render = function () {
  33968. if (!this._effect.isReady())
  33969. return false;
  33970. var engine = this._scene.getEngine();
  33971. var viewport = this._scene.activeCamera.viewport;
  33972. var globalViewport = viewport.toScreenGlobal(engine);
  33973. // Position
  33974. if (!this.computeEffectivePosition(globalViewport)) {
  33975. return false;
  33976. }
  33977. // Visibility
  33978. if (!this._isVisible()) {
  33979. return false;
  33980. }
  33981. // Intensity
  33982. var awayX;
  33983. var awayY;
  33984. if (this._positionX < this.borderLimit + globalViewport.x) {
  33985. awayX = this.borderLimit + globalViewport.x - this._positionX;
  33986. }
  33987. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  33988. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  33989. }
  33990. else {
  33991. awayX = 0;
  33992. }
  33993. if (this._positionY < this.borderLimit + globalViewport.y) {
  33994. awayY = this.borderLimit + globalViewport.y - this._positionY;
  33995. }
  33996. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  33997. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  33998. }
  33999. else {
  34000. awayY = 0;
  34001. }
  34002. var away = (awayX > awayY) ? awayX : awayY;
  34003. if (away > this.borderLimit) {
  34004. away = this.borderLimit;
  34005. }
  34006. var intensity = 1.0 - (away / this.borderLimit);
  34007. if (intensity < 0) {
  34008. return false;
  34009. }
  34010. if (intensity > 1.0) {
  34011. intensity = 1.0;
  34012. }
  34013. // Position
  34014. var centerX = globalViewport.x + globalViewport.width / 2;
  34015. var centerY = globalViewport.y + globalViewport.height / 2;
  34016. var distX = centerX - this._positionX;
  34017. var distY = centerY - this._positionY;
  34018. // Effects
  34019. engine.enableEffect(this._effect);
  34020. engine.setState(false);
  34021. engine.setDepthBuffer(false);
  34022. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  34023. // VBOs
  34024. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  34025. // Flares
  34026. for (var index = 0; index < this.lensFlares.length; index++) {
  34027. var flare = this.lensFlares[index];
  34028. var x = centerX - (distX * flare.position);
  34029. var y = centerY - (distY * flare.position);
  34030. var cw = flare.size;
  34031. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  34032. var cx = 2 * (x / globalViewport.width) - 1.0;
  34033. var cy = 1.0 - 2 * (y / globalViewport.height);
  34034. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  34035. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  34036. // Texture
  34037. this._effect.setTexture("textureSampler", flare.texture);
  34038. // Color
  34039. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  34040. // Draw order
  34041. engine.draw(true, 0, 6);
  34042. }
  34043. engine.setDepthBuffer(true);
  34044. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  34045. return true;
  34046. };
  34047. LensFlareSystem.prototype.dispose = function () {
  34048. if (this._vertexBuffer) {
  34049. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  34050. this._vertexBuffer = null;
  34051. }
  34052. if (this._indexBuffer) {
  34053. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  34054. this._indexBuffer = null;
  34055. }
  34056. while (this.lensFlares.length) {
  34057. this.lensFlares[0].dispose();
  34058. }
  34059. // Remove from scene
  34060. var index = this._scene.lensFlareSystems.indexOf(this);
  34061. this._scene.lensFlareSystems.splice(index, 1);
  34062. };
  34063. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  34064. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  34065. var lensFlareSystem = new LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  34066. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  34067. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  34068. var parsedFlare = parsedLensFlareSystem.flares[index];
  34069. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  34070. }
  34071. return lensFlareSystem;
  34072. };
  34073. LensFlareSystem.prototype.serialize = function () {
  34074. var serializationObject = {};
  34075. serializationObject.emitterId = this.getEmitter().id;
  34076. serializationObject.borderLimit = this.borderLimit;
  34077. serializationObject.flares = [];
  34078. for (var index = 0; index < this.lensFlares.length; index++) {
  34079. var flare = this.lensFlares[index];
  34080. serializationObject.flares.push({
  34081. size: flare.size,
  34082. position: flare.position,
  34083. color: flare.color.asArray(),
  34084. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  34085. });
  34086. }
  34087. return serializationObject;
  34088. };
  34089. return LensFlareSystem;
  34090. })();
  34091. BABYLON.LensFlareSystem = LensFlareSystem;
  34092. })(BABYLON || (BABYLON = {}));
  34093. var BABYLON;
  34094. (function (BABYLON) {
  34095. // We're mainly based on the logic defined into the FreeCamera code
  34096. var DeviceOrientationCamera = (function (_super) {
  34097. __extends(DeviceOrientationCamera, _super);
  34098. function DeviceOrientationCamera(name, position, scene) {
  34099. var _this = this;
  34100. _super.call(this, name, position, scene);
  34101. this._offsetX = null;
  34102. this._offsetY = null;
  34103. this._orientationGamma = 0;
  34104. this._orientationBeta = 0;
  34105. this._initialOrientationGamma = 0;
  34106. this._initialOrientationBeta = 0;
  34107. this.angularSensibility = 10000.0;
  34108. this.moveSensibility = 50.0;
  34109. window.addEventListener("resize", function () {
  34110. _this._initialOrientationGamma = null;
  34111. }, false);
  34112. }
  34113. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  34114. var _this = this;
  34115. if (this._attachedCanvas) {
  34116. return;
  34117. }
  34118. this._attachedCanvas = canvas;
  34119. if (!this._orientationChanged) {
  34120. this._orientationChanged = function (evt) {
  34121. if (!_this._initialOrientationGamma) {
  34122. _this._initialOrientationGamma = evt.gamma;
  34123. _this._initialOrientationBeta = evt.beta;
  34124. }
  34125. _this._orientationGamma = evt.gamma;
  34126. _this._orientationBeta = evt.beta;
  34127. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  34128. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  34129. };
  34130. }
  34131. window.addEventListener("deviceorientation", this._orientationChanged);
  34132. };
  34133. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  34134. if (this._attachedCanvas !== canvas) {
  34135. return;
  34136. }
  34137. window.removeEventListener("deviceorientation", this._orientationChanged);
  34138. this._attachedCanvas = null;
  34139. this._orientationGamma = 0;
  34140. this._orientationBeta = 0;
  34141. this._initialOrientationGamma = 0;
  34142. this._initialOrientationBeta = 0;
  34143. };
  34144. DeviceOrientationCamera.prototype._checkInputs = function () {
  34145. if (!this._offsetX) {
  34146. return;
  34147. }
  34148. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  34149. var speed = this._computeLocalCameraSpeed();
  34150. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  34151. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  34152. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  34153. _super.prototype._checkInputs.call(this);
  34154. };
  34155. return DeviceOrientationCamera;
  34156. })(BABYLON.FreeCamera);
  34157. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  34158. })(BABYLON || (BABYLON = {}));
  34159. var BABYLON;
  34160. (function (BABYLON) {
  34161. var Analyser = (function () {
  34162. function Analyser(scene) {
  34163. this.SMOOTHING = 0.75;
  34164. this.FFT_SIZE = 512;
  34165. this.BARGRAPHAMPLITUDE = 256;
  34166. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  34167. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  34168. this._scene = scene;
  34169. this._audioEngine = BABYLON.Engine.audioEngine;
  34170. if (this._audioEngine.canUseWebAudio) {
  34171. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  34172. this._webAudioAnalyser.minDecibels = -140;
  34173. this._webAudioAnalyser.maxDecibels = 0;
  34174. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  34175. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  34176. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  34177. }
  34178. }
  34179. Analyser.prototype.getFrequencyBinCount = function () {
  34180. if (this._audioEngine.canUseWebAudio) {
  34181. return this._webAudioAnalyser.frequencyBinCount;
  34182. }
  34183. else {
  34184. return 0;
  34185. }
  34186. };
  34187. Analyser.prototype.getByteFrequencyData = function () {
  34188. if (this._audioEngine.canUseWebAudio) {
  34189. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  34190. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  34191. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  34192. }
  34193. return this._byteFreqs;
  34194. };
  34195. Analyser.prototype.getByteTimeDomainData = function () {
  34196. if (this._audioEngine.canUseWebAudio) {
  34197. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  34198. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  34199. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  34200. }
  34201. return this._byteTime;
  34202. };
  34203. Analyser.prototype.getFloatFrequencyData = function () {
  34204. if (this._audioEngine.canUseWebAudio) {
  34205. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  34206. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  34207. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  34208. }
  34209. return this._floatFreqs;
  34210. };
  34211. Analyser.prototype.drawDebugCanvas = function () {
  34212. var _this = this;
  34213. if (this._audioEngine.canUseWebAudio) {
  34214. if (!this._debugCanvas) {
  34215. this._debugCanvas = document.createElement("canvas");
  34216. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  34217. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  34218. this._debugCanvas.style.position = "absolute";
  34219. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  34220. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  34221. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  34222. document.body.appendChild(this._debugCanvas);
  34223. this._registerFunc = function () {
  34224. _this.drawDebugCanvas();
  34225. };
  34226. this._scene.registerBeforeRender(this._registerFunc);
  34227. }
  34228. if (this._registerFunc) {
  34229. var workingArray = this.getByteFrequencyData();
  34230. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  34231. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  34232. // Draw the frequency domain chart.
  34233. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  34234. var value = workingArray[i];
  34235. var percent = value / this.BARGRAPHAMPLITUDE;
  34236. var height = this.DEBUGCANVASSIZE.height * percent;
  34237. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  34238. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  34239. var hue = i / this.getFrequencyBinCount() * 360;
  34240. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  34241. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  34242. }
  34243. }
  34244. }
  34245. };
  34246. Analyser.prototype.stopDebugCanvas = function () {
  34247. if (this._debugCanvas) {
  34248. this._scene.unregisterBeforeRender(this._registerFunc);
  34249. this._registerFunc = null;
  34250. document.body.removeChild(this._debugCanvas);
  34251. this._debugCanvas = null;
  34252. this._debugCanvasContext = null;
  34253. }
  34254. };
  34255. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  34256. if (this._audioEngine.canUseWebAudio) {
  34257. inputAudioNode.connect(this._webAudioAnalyser);
  34258. this._webAudioAnalyser.connect(outputAudioNode);
  34259. }
  34260. };
  34261. Analyser.prototype.dispose = function () {
  34262. if (this._audioEngine.canUseWebAudio) {
  34263. this._webAudioAnalyser.disconnect();
  34264. }
  34265. };
  34266. return Analyser;
  34267. })();
  34268. BABYLON.Analyser = Analyser;
  34269. })(BABYLON || (BABYLON = {}));
  34270. var BABYLON;
  34271. (function (BABYLON) {
  34272. var AudioEngine = (function () {
  34273. function AudioEngine() {
  34274. this._audioContext = null;
  34275. this._audioContextInitialized = false;
  34276. this.canUseWebAudio = false;
  34277. this.WarnedWebAudioUnsupported = false;
  34278. this.unlocked = false;
  34279. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  34280. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  34281. this.canUseWebAudio = true;
  34282. }
  34283. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  34284. this._unlockiOSaudio();
  34285. }
  34286. else {
  34287. this.unlocked = true;
  34288. }
  34289. }
  34290. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  34291. get: function () {
  34292. if (!this._audioContextInitialized) {
  34293. this._initializeAudioContext();
  34294. }
  34295. return this._audioContext;
  34296. },
  34297. enumerable: true,
  34298. configurable: true
  34299. });
  34300. AudioEngine.prototype._unlockiOSaudio = function () {
  34301. var _this = this;
  34302. var unlockaudio = function () {
  34303. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  34304. var source = _this.audioContext.createBufferSource();
  34305. source.buffer = buffer;
  34306. source.connect(_this.audioContext.destination);
  34307. source.start(0);
  34308. setTimeout(function () {
  34309. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  34310. _this.unlocked = true;
  34311. window.removeEventListener('touchend', unlockaudio, false);
  34312. if (_this.onAudioUnlocked) {
  34313. _this.onAudioUnlocked();
  34314. }
  34315. }
  34316. }, 0);
  34317. };
  34318. window.addEventListener('touchend', unlockaudio, false);
  34319. };
  34320. AudioEngine.prototype._initializeAudioContext = function () {
  34321. try {
  34322. if (this.canUseWebAudio) {
  34323. this._audioContext = new AudioContext();
  34324. // create a global volume gain node
  34325. this.masterGain = this._audioContext.createGain();
  34326. this.masterGain.gain.value = 1;
  34327. this.masterGain.connect(this._audioContext.destination);
  34328. this._audioContextInitialized = true;
  34329. }
  34330. }
  34331. catch (e) {
  34332. this.canUseWebAudio = false;
  34333. BABYLON.Tools.Error("Web Audio: " + e.message);
  34334. }
  34335. };
  34336. AudioEngine.prototype.dispose = function () {
  34337. if (this.canUseWebAudio && this._audioContextInitialized) {
  34338. if (this._connectedAnalyser) {
  34339. this._connectedAnalyser.stopDebugCanvas();
  34340. this._connectedAnalyser.dispose();
  34341. this.masterGain.disconnect();
  34342. this.masterGain.connect(this._audioContext.destination);
  34343. this._connectedAnalyser = null;
  34344. }
  34345. this.masterGain.gain.value = 1;
  34346. }
  34347. this.WarnedWebAudioUnsupported = false;
  34348. };
  34349. AudioEngine.prototype.getGlobalVolume = function () {
  34350. if (this.canUseWebAudio && this._audioContextInitialized) {
  34351. return this.masterGain.gain.value;
  34352. }
  34353. else {
  34354. return -1;
  34355. }
  34356. };
  34357. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  34358. if (this.canUseWebAudio && this._audioContextInitialized) {
  34359. this.masterGain.gain.value = newVolume;
  34360. }
  34361. };
  34362. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  34363. if (this._connectedAnalyser) {
  34364. this._connectedAnalyser.stopDebugCanvas();
  34365. }
  34366. if (this.canUseWebAudio && this._audioContextInitialized) {
  34367. this._connectedAnalyser = analyser;
  34368. this.masterGain.disconnect();
  34369. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  34370. }
  34371. };
  34372. return AudioEngine;
  34373. })();
  34374. BABYLON.AudioEngine = AudioEngine;
  34375. })(BABYLON || (BABYLON = {}));
  34376. var BABYLON;
  34377. (function (BABYLON) {
  34378. var Sound = (function () {
  34379. /**
  34380. * Create a sound and attach it to a scene
  34381. * @param name Name of your sound
  34382. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  34383. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  34384. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  34385. */
  34386. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  34387. var _this = this;
  34388. this.autoplay = false;
  34389. this.loop = false;
  34390. this.useCustomAttenuation = false;
  34391. this.spatialSound = false;
  34392. this.refDistance = 1;
  34393. this.rolloffFactor = 1;
  34394. this.maxDistance = 100;
  34395. this.distanceModel = "linear";
  34396. this._panningModel = "equalpower";
  34397. this._playbackRate = 1;
  34398. this._streaming = false;
  34399. this._startTime = 0;
  34400. this._startOffset = 0;
  34401. this._position = BABYLON.Vector3.Zero();
  34402. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  34403. this._volume = 1;
  34404. this._isLoaded = false;
  34405. this._isReadyToPlay = false;
  34406. this.isPlaying = false;
  34407. this.isPaused = false;
  34408. this._isDirectional = false;
  34409. // Used if you'd like to create a directional sound.
  34410. // If not set, the sound will be omnidirectional
  34411. this._coneInnerAngle = 360;
  34412. this._coneOuterAngle = 360;
  34413. this._coneOuterGain = 0;
  34414. this._isOutputConnected = false;
  34415. this.name = name;
  34416. this._scene = scene;
  34417. this._readyToPlayCallback = readyToPlayCallback;
  34418. // Default custom attenuation function is a linear attenuation
  34419. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  34420. if (currentDistance < maxDistance) {
  34421. return currentVolume * (1 - currentDistance / maxDistance);
  34422. }
  34423. else {
  34424. return 0;
  34425. }
  34426. };
  34427. if (options) {
  34428. this.autoplay = options.autoplay || false;
  34429. this.loop = options.loop || false;
  34430. // if volume === 0, we need another way to check this option
  34431. if (options.volume !== undefined) {
  34432. this._volume = options.volume;
  34433. }
  34434. this.spatialSound = options.spatialSound || false;
  34435. this.maxDistance = options.maxDistance || 100;
  34436. this.useCustomAttenuation = options.useCustomAttenuation || false;
  34437. this.rolloffFactor = options.rolloffFactor || 1;
  34438. this.refDistance = options.refDistance || 1;
  34439. this.distanceModel = options.distanceModel || "linear";
  34440. this._playbackRate = options.playbackRate || 1;
  34441. this._streaming = options.streaming || false;
  34442. }
  34443. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34444. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  34445. this._soundGain.gain.value = this._volume;
  34446. this._inputAudioNode = this._soundGain;
  34447. this._ouputAudioNode = this._soundGain;
  34448. if (this.spatialSound) {
  34449. this._createSpatialParameters();
  34450. }
  34451. this._scene.mainSoundTrack.AddSound(this);
  34452. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  34453. if (urlOrArrayBuffer) {
  34454. // If it's an URL
  34455. if (typeof (urlOrArrayBuffer) === "string") {
  34456. // Loading sound using XHR2
  34457. if (!this._streaming) {
  34458. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  34459. }
  34460. else {
  34461. this._htmlAudioElement = new Audio(urlOrArrayBuffer);
  34462. this._htmlAudioElement.controls = false;
  34463. this._htmlAudioElement.loop = this.loop;
  34464. this._htmlAudioElement.crossOrigin = "anonymous";
  34465. this._htmlAudioElement.preload = "auto";
  34466. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  34467. _this._isReadyToPlay = true;
  34468. if (_this.autoplay) {
  34469. _this.play();
  34470. }
  34471. if (_this._readyToPlayCallback) {
  34472. _this._readyToPlayCallback();
  34473. }
  34474. });
  34475. document.body.appendChild(this._htmlAudioElement);
  34476. }
  34477. }
  34478. else {
  34479. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  34480. if (urlOrArrayBuffer.byteLength > 0) {
  34481. this._soundLoaded(urlOrArrayBuffer);
  34482. }
  34483. }
  34484. else {
  34485. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  34486. }
  34487. }
  34488. }
  34489. }
  34490. else {
  34491. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  34492. this._scene.mainSoundTrack.AddSound(this);
  34493. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  34494. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  34495. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  34496. }
  34497. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  34498. if (this._readyToPlayCallback) {
  34499. window.setTimeout(function () {
  34500. _this._readyToPlayCallback();
  34501. }, 1000);
  34502. }
  34503. }
  34504. }
  34505. Sound.prototype.dispose = function () {
  34506. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  34507. if (this.isPlaying) {
  34508. this.stop();
  34509. }
  34510. this._isReadyToPlay = false;
  34511. if (this.soundTrackId === -1) {
  34512. this._scene.mainSoundTrack.RemoveSound(this);
  34513. }
  34514. else {
  34515. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  34516. }
  34517. if (this._soundGain) {
  34518. this._soundGain.disconnect();
  34519. this._soundGain = null;
  34520. }
  34521. if (this._soundPanner) {
  34522. this._soundPanner.disconnect();
  34523. this._soundPanner = null;
  34524. }
  34525. if (this._soundSource) {
  34526. this._soundSource.disconnect();
  34527. this._soundSource = null;
  34528. }
  34529. this._audioBuffer = null;
  34530. if (this._htmlAudioElement) {
  34531. this._htmlAudioElement.pause();
  34532. this._htmlAudioElement.src = "";
  34533. document.body.removeChild(this._htmlAudioElement);
  34534. }
  34535. if (this._connectedMesh) {
  34536. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  34537. this._connectedMesh = null;
  34538. }
  34539. }
  34540. };
  34541. Sound.prototype._soundLoaded = function (audioData) {
  34542. var _this = this;
  34543. this._isLoaded = true;
  34544. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  34545. _this._audioBuffer = buffer;
  34546. _this._isReadyToPlay = true;
  34547. if (_this.autoplay) {
  34548. _this.play();
  34549. }
  34550. if (_this._readyToPlayCallback) {
  34551. _this._readyToPlayCallback();
  34552. }
  34553. }, function () { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name); });
  34554. };
  34555. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  34556. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34557. this._audioBuffer = audioBuffer;
  34558. this._isReadyToPlay = true;
  34559. }
  34560. };
  34561. Sound.prototype.updateOptions = function (options) {
  34562. if (options) {
  34563. this.loop = options.loop || this.loop;
  34564. this.maxDistance = options.maxDistance || this.maxDistance;
  34565. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  34566. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  34567. this.refDistance = options.refDistance || this.refDistance;
  34568. this.distanceModel = options.distanceModel || this.distanceModel;
  34569. this._playbackRate = options.playbackRate || this._playbackRate;
  34570. this._updateSpatialParameters();
  34571. if (this.isPlaying) {
  34572. if (this._streaming) {
  34573. this._htmlAudioElement.playbackRate = this._playbackRate;
  34574. }
  34575. else {
  34576. this._soundSource.playbackRate.value = this._playbackRate;
  34577. }
  34578. }
  34579. }
  34580. };
  34581. Sound.prototype._createSpatialParameters = function () {
  34582. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34583. if (this._scene.headphone) {
  34584. this._panningModel = "HRTF";
  34585. }
  34586. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  34587. this._updateSpatialParameters();
  34588. this._soundPanner.connect(this._ouputAudioNode);
  34589. this._inputAudioNode = this._soundPanner;
  34590. }
  34591. };
  34592. Sound.prototype._updateSpatialParameters = function () {
  34593. if (this.spatialSound) {
  34594. if (this.useCustomAttenuation) {
  34595. // Tricks to disable in a way embedded Web Audio attenuation
  34596. this._soundPanner.distanceModel = "linear";
  34597. this._soundPanner.maxDistance = Number.MAX_VALUE;
  34598. this._soundPanner.refDistance = 1;
  34599. this._soundPanner.rolloffFactor = 1;
  34600. this._soundPanner.panningModel = this._panningModel;
  34601. }
  34602. else {
  34603. this._soundPanner.distanceModel = this.distanceModel;
  34604. this._soundPanner.maxDistance = this.maxDistance;
  34605. this._soundPanner.refDistance = this.refDistance;
  34606. this._soundPanner.rolloffFactor = this.rolloffFactor;
  34607. this._soundPanner.panningModel = this._panningModel;
  34608. }
  34609. }
  34610. };
  34611. Sound.prototype.switchPanningModelToHRTF = function () {
  34612. this._panningModel = "HRTF";
  34613. this._switchPanningModel();
  34614. };
  34615. Sound.prototype.switchPanningModelToEqualPower = function () {
  34616. this._panningModel = "equalpower";
  34617. this._switchPanningModel();
  34618. };
  34619. Sound.prototype._switchPanningModel = function () {
  34620. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  34621. this._soundPanner.panningModel = this._panningModel;
  34622. }
  34623. };
  34624. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  34625. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34626. if (this._isOutputConnected) {
  34627. this._ouputAudioNode.disconnect();
  34628. }
  34629. this._ouputAudioNode.connect(soundTrackAudioNode);
  34630. this._isOutputConnected = true;
  34631. }
  34632. };
  34633. /**
  34634. * Transform this sound into a directional source
  34635. * @param coneInnerAngle Size of the inner cone in degree
  34636. * @param coneOuterAngle Size of the outer cone in degree
  34637. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  34638. */
  34639. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  34640. if (coneOuterAngle < coneInnerAngle) {
  34641. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  34642. return;
  34643. }
  34644. this._coneInnerAngle = coneInnerAngle;
  34645. this._coneOuterAngle = coneOuterAngle;
  34646. this._coneOuterGain = coneOuterGain;
  34647. this._isDirectional = true;
  34648. if (this.isPlaying && this.loop) {
  34649. this.stop();
  34650. this.play();
  34651. }
  34652. };
  34653. Sound.prototype.setPosition = function (newPosition) {
  34654. this._position = newPosition;
  34655. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  34656. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  34657. }
  34658. };
  34659. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  34660. this._localDirection = newLocalDirection;
  34661. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  34662. this._updateDirection();
  34663. }
  34664. };
  34665. Sound.prototype._updateDirection = function () {
  34666. var mat = this._connectedMesh.getWorldMatrix();
  34667. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  34668. direction.normalize();
  34669. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  34670. };
  34671. Sound.prototype.updateDistanceFromListener = function () {
  34672. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  34673. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  34674. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  34675. }
  34676. };
  34677. Sound.prototype.setAttenuationFunction = function (callback) {
  34678. this._customAttenuationFunction = callback;
  34679. };
  34680. /**
  34681. * Play the sound
  34682. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  34683. */
  34684. Sound.prototype.play = function (time) {
  34685. var _this = this;
  34686. if (this._isReadyToPlay && this._scene.audioEnabled) {
  34687. try {
  34688. if (this._startOffset < 0) {
  34689. time = -this._startOffset;
  34690. this._startOffset = 0;
  34691. }
  34692. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  34693. if (!this._soundSource || !this._streamingSource) {
  34694. if (this.spatialSound) {
  34695. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  34696. if (this._isDirectional) {
  34697. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  34698. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  34699. this._soundPanner.coneOuterGain = this._coneOuterGain;
  34700. if (this._connectedMesh) {
  34701. this._updateDirection();
  34702. }
  34703. else {
  34704. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  34705. }
  34706. }
  34707. }
  34708. }
  34709. if (this._streaming) {
  34710. if (!this._streamingSource) {
  34711. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  34712. this._htmlAudioElement.onended = function () { _this._onended(); };
  34713. this._htmlAudioElement.playbackRate = this._playbackRate;
  34714. }
  34715. this._streamingSource.disconnect();
  34716. this._streamingSource.connect(this._inputAudioNode);
  34717. this._htmlAudioElement.play();
  34718. }
  34719. else {
  34720. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  34721. this._soundSource.buffer = this._audioBuffer;
  34722. this._soundSource.connect(this._inputAudioNode);
  34723. this._soundSource.loop = this.loop;
  34724. this._soundSource.playbackRate.value = this._playbackRate;
  34725. this._soundSource.onended = function () { _this._onended(); };
  34726. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  34727. }
  34728. this._startTime = startTime;
  34729. this.isPlaying = true;
  34730. this.isPaused = false;
  34731. }
  34732. catch (ex) {
  34733. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  34734. }
  34735. }
  34736. };
  34737. Sound.prototype._onended = function () {
  34738. this.isPlaying = false;
  34739. if (this.onended) {
  34740. this.onended();
  34741. }
  34742. };
  34743. /**
  34744. * Stop the sound
  34745. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  34746. */
  34747. Sound.prototype.stop = function (time) {
  34748. if (this.isPlaying) {
  34749. if (this._streaming) {
  34750. this._htmlAudioElement.pause();
  34751. // Test needed for Firefox or it will generate an Invalid State Error
  34752. if (this._htmlAudioElement.currentTime > 0) {
  34753. this._htmlAudioElement.currentTime = 0;
  34754. }
  34755. }
  34756. else {
  34757. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  34758. this._soundSource.stop(stopTime);
  34759. if (!this.isPaused) {
  34760. this._startOffset = 0;
  34761. }
  34762. }
  34763. this.isPlaying = false;
  34764. }
  34765. };
  34766. Sound.prototype.pause = function () {
  34767. if (this.isPlaying) {
  34768. this.isPaused = true;
  34769. if (this._streaming) {
  34770. this._htmlAudioElement.pause();
  34771. }
  34772. else {
  34773. this.stop(0);
  34774. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  34775. }
  34776. }
  34777. };
  34778. Sound.prototype.setVolume = function (newVolume, time) {
  34779. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34780. if (time) {
  34781. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  34782. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  34783. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  34784. }
  34785. else {
  34786. this._soundGain.gain.value = newVolume;
  34787. }
  34788. }
  34789. this._volume = newVolume;
  34790. };
  34791. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  34792. this._playbackRate = newPlaybackRate;
  34793. if (this.isPlaying) {
  34794. if (this._streaming) {
  34795. this._htmlAudioElement.playbackRate = this._playbackRate;
  34796. }
  34797. else {
  34798. this._soundSource.playbackRate.value = this._playbackRate;
  34799. }
  34800. }
  34801. };
  34802. Sound.prototype.getVolume = function () {
  34803. return this._volume;
  34804. };
  34805. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  34806. var _this = this;
  34807. if (this._connectedMesh) {
  34808. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  34809. this._registerFunc = null;
  34810. }
  34811. this._connectedMesh = meshToConnectTo;
  34812. if (!this.spatialSound) {
  34813. this.spatialSound = true;
  34814. this._createSpatialParameters();
  34815. if (this.isPlaying && this.loop) {
  34816. this.stop();
  34817. this.play();
  34818. }
  34819. }
  34820. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  34821. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  34822. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  34823. };
  34824. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  34825. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  34826. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  34827. this._updateDirection();
  34828. }
  34829. };
  34830. Sound.prototype.clone = function () {
  34831. var _this = this;
  34832. if (!this._streaming) {
  34833. var setBufferAndRun = function () {
  34834. if (_this._isReadyToPlay) {
  34835. clonedSound._audioBuffer = _this.getAudioBuffer();
  34836. clonedSound._isReadyToPlay = true;
  34837. if (clonedSound.autoplay) {
  34838. clonedSound.play();
  34839. }
  34840. }
  34841. else {
  34842. window.setTimeout(setBufferAndRun, 300);
  34843. }
  34844. };
  34845. var currentOptions = {
  34846. autoplay: this.autoplay, loop: this.loop,
  34847. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  34848. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  34849. refDistance: this.refDistance, distanceModel: this.distanceModel
  34850. };
  34851. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  34852. if (this.useCustomAttenuation) {
  34853. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  34854. }
  34855. clonedSound.setPosition(this._position);
  34856. clonedSound.setPlaybackRate(this._playbackRate);
  34857. setBufferAndRun();
  34858. return clonedSound;
  34859. }
  34860. else {
  34861. return null;
  34862. }
  34863. };
  34864. Sound.prototype.getAudioBuffer = function () {
  34865. return this._audioBuffer;
  34866. };
  34867. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  34868. var soundName = parsedSound.name;
  34869. var soundUrl;
  34870. if (parsedSound.url) {
  34871. soundUrl = rootUrl + parsedSound.url;
  34872. }
  34873. else {
  34874. soundUrl = rootUrl + soundName;
  34875. }
  34876. var options = {
  34877. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  34878. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  34879. rolloffFactor: parsedSound.rolloffFactor,
  34880. refDistance: parsedSound.refDistance,
  34881. distanceModel: parsedSound.distanceModel,
  34882. playbackRate: parsedSound.playbackRate
  34883. };
  34884. var newSound;
  34885. if (!sourceSound) {
  34886. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  34887. scene._addPendingData(newSound);
  34888. }
  34889. else {
  34890. var setBufferAndRun = function () {
  34891. if (sourceSound._isReadyToPlay) {
  34892. newSound._audioBuffer = sourceSound.getAudioBuffer();
  34893. newSound._isReadyToPlay = true;
  34894. if (newSound.autoplay) {
  34895. newSound.play();
  34896. }
  34897. }
  34898. else {
  34899. window.setTimeout(setBufferAndRun, 300);
  34900. }
  34901. };
  34902. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  34903. setBufferAndRun();
  34904. }
  34905. if (parsedSound.position) {
  34906. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  34907. newSound.setPosition(soundPosition);
  34908. }
  34909. if (parsedSound.isDirectional) {
  34910. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  34911. if (parsedSound.localDirectionToMesh) {
  34912. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  34913. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  34914. }
  34915. }
  34916. if (parsedSound.connectedMeshId) {
  34917. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  34918. if (connectedMesh) {
  34919. newSound.attachToMesh(connectedMesh);
  34920. }
  34921. }
  34922. return newSound;
  34923. };
  34924. return Sound;
  34925. })();
  34926. BABYLON.Sound = Sound;
  34927. })(BABYLON || (BABYLON = {}));
  34928. var BABYLON;
  34929. (function (BABYLON) {
  34930. var SoundTrack = (function () {
  34931. function SoundTrack(scene, options) {
  34932. this.id = -1;
  34933. this._isMainTrack = false;
  34934. this._isInitialized = false;
  34935. this._scene = scene;
  34936. this.soundCollection = new Array();
  34937. this._options = options;
  34938. if (!this._isMainTrack) {
  34939. this._scene.soundTracks.push(this);
  34940. this.id = this._scene.soundTracks.length - 1;
  34941. }
  34942. }
  34943. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  34944. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34945. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  34946. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  34947. if (this._options) {
  34948. if (this._options.volume) {
  34949. this._outputAudioNode.gain.value = this._options.volume;
  34950. }
  34951. if (this._options.mainTrack) {
  34952. this._isMainTrack = this._options.mainTrack;
  34953. }
  34954. }
  34955. this._isInitialized = true;
  34956. }
  34957. };
  34958. SoundTrack.prototype.dispose = function () {
  34959. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34960. if (this._connectedAnalyser) {
  34961. this._connectedAnalyser.stopDebugCanvas();
  34962. }
  34963. while (this.soundCollection.length) {
  34964. this.soundCollection[0].dispose();
  34965. }
  34966. if (this._outputAudioNode) {
  34967. this._outputAudioNode.disconnect();
  34968. }
  34969. this._outputAudioNode = null;
  34970. }
  34971. };
  34972. SoundTrack.prototype.AddSound = function (sound) {
  34973. if (!this._isInitialized) {
  34974. this._initializeSoundTrackAudioGraph();
  34975. }
  34976. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34977. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  34978. }
  34979. if (sound.soundTrackId) {
  34980. if (sound.soundTrackId === -1) {
  34981. this._scene.mainSoundTrack.RemoveSound(sound);
  34982. }
  34983. else {
  34984. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  34985. }
  34986. }
  34987. this.soundCollection.push(sound);
  34988. sound.soundTrackId = this.id;
  34989. };
  34990. SoundTrack.prototype.RemoveSound = function (sound) {
  34991. var index = this.soundCollection.indexOf(sound);
  34992. if (index !== -1) {
  34993. this.soundCollection.splice(index, 1);
  34994. }
  34995. };
  34996. SoundTrack.prototype.setVolume = function (newVolume) {
  34997. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34998. this._outputAudioNode.gain.value = newVolume;
  34999. }
  35000. };
  35001. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  35002. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35003. for (var i = 0; i < this.soundCollection.length; i++) {
  35004. this.soundCollection[i].switchPanningModelToHRTF();
  35005. }
  35006. }
  35007. };
  35008. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  35009. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35010. for (var i = 0; i < this.soundCollection.length; i++) {
  35011. this.soundCollection[i].switchPanningModelToEqualPower();
  35012. }
  35013. }
  35014. };
  35015. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  35016. if (this._connectedAnalyser) {
  35017. this._connectedAnalyser.stopDebugCanvas();
  35018. }
  35019. this._connectedAnalyser = analyser;
  35020. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35021. this._outputAudioNode.disconnect();
  35022. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  35023. }
  35024. };
  35025. return SoundTrack;
  35026. })();
  35027. BABYLON.SoundTrack = SoundTrack;
  35028. })(BABYLON || (BABYLON = {}));
  35029. var BABYLON;
  35030. (function (BABYLON) {
  35031. var DepthRenderer = (function () {
  35032. function DepthRenderer(scene, type) {
  35033. var _this = this;
  35034. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  35035. this._viewMatrix = BABYLON.Matrix.Zero();
  35036. this._projectionMatrix = BABYLON.Matrix.Zero();
  35037. this._transformMatrix = BABYLON.Matrix.Zero();
  35038. this._worldViewProjection = BABYLON.Matrix.Zero();
  35039. this._scene = scene;
  35040. var engine = scene.getEngine();
  35041. // Render target
  35042. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  35043. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35044. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35045. this._depthMap.refreshRate = 1;
  35046. this._depthMap.renderParticles = false;
  35047. this._depthMap.renderList = null;
  35048. // set default depth value to 1.0 (far away)
  35049. this._depthMap.onClear = function (engine) {
  35050. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  35051. };
  35052. // Custom render function
  35053. var renderSubMesh = function (subMesh) {
  35054. var mesh = subMesh.getRenderingMesh();
  35055. var scene = _this._scene;
  35056. var engine = scene.getEngine();
  35057. // Culling
  35058. engine.setState(subMesh.getMaterial().backFaceCulling);
  35059. // Managing instances
  35060. var batch = mesh._getInstancesRenderList(subMesh._id);
  35061. if (batch.mustReturn) {
  35062. return;
  35063. }
  35064. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  35065. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  35066. engine.enableEffect(_this._effect);
  35067. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  35068. var material = subMesh.getMaterial();
  35069. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  35070. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  35071. // Alpha test
  35072. if (material && material.needAlphaTesting()) {
  35073. var alphaTexture = material.getAlphaTestTexture();
  35074. _this._effect.setTexture("diffuseSampler", alphaTexture);
  35075. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  35076. }
  35077. // Bones
  35078. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  35079. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  35080. }
  35081. // Draw
  35082. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  35083. }
  35084. };
  35085. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  35086. var index;
  35087. for (index = 0; index < opaqueSubMeshes.length; index++) {
  35088. renderSubMesh(opaqueSubMeshes.data[index]);
  35089. }
  35090. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  35091. renderSubMesh(alphaTestSubMeshes.data[index]);
  35092. }
  35093. };
  35094. }
  35095. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  35096. var defines = [];
  35097. var attribs = [BABYLON.VertexBuffer.PositionKind];
  35098. var mesh = subMesh.getMesh();
  35099. var scene = mesh.getScene();
  35100. var material = subMesh.getMaterial();
  35101. // Alpha test
  35102. if (material && material.needAlphaTesting()) {
  35103. defines.push("#define ALPHATEST");
  35104. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35105. attribs.push(BABYLON.VertexBuffer.UVKind);
  35106. defines.push("#define UV1");
  35107. }
  35108. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35109. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  35110. defines.push("#define UV2");
  35111. }
  35112. }
  35113. // Bones
  35114. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  35115. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35116. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35117. if (mesh.numBoneInfluencers > 4) {
  35118. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  35119. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  35120. }
  35121. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  35122. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  35123. }
  35124. else {
  35125. defines.push("#define NUM_BONE_INFLUENCERS 0");
  35126. }
  35127. // Instances
  35128. if (useInstances) {
  35129. defines.push("#define INSTANCES");
  35130. attribs.push("world0");
  35131. attribs.push("world1");
  35132. attribs.push("world2");
  35133. attribs.push("world3");
  35134. }
  35135. // Get correct effect
  35136. var join = defines.join("\n");
  35137. if (this._cachedDefines !== join) {
  35138. this._cachedDefines = join;
  35139. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  35140. }
  35141. return this._effect.isReady();
  35142. };
  35143. DepthRenderer.prototype.getDepthMap = function () {
  35144. return this._depthMap;
  35145. };
  35146. // Methods
  35147. DepthRenderer.prototype.dispose = function () {
  35148. this._depthMap.dispose();
  35149. };
  35150. return DepthRenderer;
  35151. })();
  35152. BABYLON.DepthRenderer = DepthRenderer;
  35153. })(BABYLON || (BABYLON = {}));
  35154. var BABYLON;
  35155. (function (BABYLON) {
  35156. var SSAORenderingPipeline = (function (_super) {
  35157. __extends(SSAORenderingPipeline, _super);
  35158. /**
  35159. * @constructor
  35160. * @param {string} name - The rendering pipeline name
  35161. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  35162. * @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 }
  35163. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  35164. */
  35165. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  35166. var _this = this;
  35167. _super.call(this, scene.getEngine(), name);
  35168. // Members
  35169. /**
  35170. * The PassPostProcess id in the pipeline that contains the original scene color
  35171. * @type {string}
  35172. */
  35173. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  35174. /**
  35175. * The SSAO PostProcess id in the pipeline
  35176. * @type {string}
  35177. */
  35178. this.SSAORenderEffect = "SSAORenderEffect";
  35179. /**
  35180. * The horizontal blur PostProcess id in the pipeline
  35181. * @type {string}
  35182. */
  35183. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  35184. /**
  35185. * The vertical blur PostProcess id in the pipeline
  35186. * @type {string}
  35187. */
  35188. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  35189. /**
  35190. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  35191. * @type {string}
  35192. */
  35193. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  35194. /**
  35195. * The output strength of the SSAO post-process. Default value is 1.0.
  35196. * @type {number}
  35197. */
  35198. this.totalStrength = 1.0;
  35199. /**
  35200. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  35201. * @type {number}
  35202. */
  35203. this.radius = 0.0001;
  35204. /**
  35205. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  35206. * Must not be equal to fallOff and superior to fallOff.
  35207. * Default value is 0.975
  35208. * @type {number}
  35209. */
  35210. this.area = 0.0075;
  35211. /**
  35212. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  35213. * Must not be equal to area and inferior to area.
  35214. * Default value is 0.0
  35215. * @type {number}
  35216. */
  35217. this.fallOff = 0.000001;
  35218. /**
  35219. * The base color of the SSAO post-process
  35220. * The final result is "base + ssao" between [0, 1]
  35221. * @type {number}
  35222. */
  35223. this.base = 0.5;
  35224. this._firstUpdate = true;
  35225. this._scene = scene;
  35226. // Set up assets
  35227. this._createRandomTexture();
  35228. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  35229. var ssaoRatio = ratio.ssaoRatio || ratio;
  35230. var combineRatio = ratio.combineRatio || ratio;
  35231. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  35232. this._createSSAOPostProcess(ssaoRatio);
  35233. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(1.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  35234. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 1.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  35235. this._createSSAOCombinePostProcess(combineRatio);
  35236. // Set up pipeline
  35237. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  35238. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  35239. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  35240. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  35241. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  35242. // Finish
  35243. scene.postProcessRenderPipelineManager.addPipeline(this);
  35244. if (cameras)
  35245. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  35246. }
  35247. // Public Methods
  35248. /**
  35249. * Returns the horizontal blur PostProcess
  35250. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  35251. */
  35252. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  35253. return this._blurHPostProcess;
  35254. };
  35255. /**
  35256. * Returns the vertical blur PostProcess
  35257. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  35258. */
  35259. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  35260. return this._blurVPostProcess;
  35261. };
  35262. /**
  35263. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  35264. */
  35265. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  35266. if (disableDepthRender === void 0) { disableDepthRender = false; }
  35267. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  35268. this._originalColorPostProcess = undefined;
  35269. this._ssaoPostProcess = undefined;
  35270. this._blurHPostProcess = undefined;
  35271. this._blurVPostProcess = undefined;
  35272. this._ssaoCombinePostProcess = undefined;
  35273. this._randomTexture.dispose();
  35274. if (disableDepthRender)
  35275. this._scene.disableDepthRenderer();
  35276. };
  35277. // Private Methods
  35278. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  35279. var _this = this;
  35280. var numSamples = 16;
  35281. var sampleSphere = [
  35282. 0.5381, 0.1856, -0.4319,
  35283. 0.1379, 0.2486, 0.4430,
  35284. 0.3371, 0.5679, -0.0057,
  35285. -0.6999, -0.0451, -0.0019,
  35286. 0.0689, -0.1598, -0.8547,
  35287. 0.0560, 0.0069, -0.1843,
  35288. -0.0146, 0.1402, 0.0762,
  35289. 0.0100, -0.1924, -0.0344,
  35290. -0.3577, -0.5301, -0.4358,
  35291. -0.3169, 0.1063, 0.0158,
  35292. 0.0103, -0.5869, 0.0046,
  35293. -0.0897, -0.4940, 0.3287,
  35294. 0.7119, -0.0154, -0.0918,
  35295. -0.0533, 0.0596, -0.5411,
  35296. 0.0352, -0.0631, 0.5460,
  35297. -0.4776, 0.2847, -0.0271
  35298. ];
  35299. var samplesFactor = 1.0 / numSamples;
  35300. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  35301. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  35302. "area", "fallOff", "base"
  35303. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples);
  35304. this._ssaoPostProcess.onApply = function (effect) {
  35305. if (_this._firstUpdate) {
  35306. effect.setArray3("sampleSphere", sampleSphere);
  35307. effect.setFloat("samplesFactor", samplesFactor);
  35308. effect.setFloat("randTextureTiles", 4.0);
  35309. _this._firstUpdate = false;
  35310. }
  35311. effect.setFloat("totalStrength", _this.totalStrength);
  35312. effect.setFloat("radius", _this.radius);
  35313. effect.setFloat("area", _this.area);
  35314. effect.setFloat("fallOff", _this.fallOff);
  35315. effect.setFloat("base", _this.base);
  35316. effect.setTexture("textureSampler", _this._depthTexture);
  35317. effect.setTexture("randomSampler", _this._randomTexture);
  35318. };
  35319. };
  35320. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  35321. var _this = this;
  35322. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  35323. this._ssaoCombinePostProcess.onApply = function (effect) {
  35324. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  35325. };
  35326. };
  35327. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  35328. var size = 512;
  35329. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  35330. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  35331. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  35332. var context = this._randomTexture.getContext();
  35333. var rand = function (min, max) {
  35334. return Math.random() * (max - min) + min;
  35335. };
  35336. var randVector = BABYLON.Vector3.Zero();
  35337. for (var x = 0; x < size; x++) {
  35338. for (var y = 0; y < size; y++) {
  35339. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  35340. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  35341. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  35342. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  35343. context.fillRect(x, y, 1, 1);
  35344. }
  35345. }
  35346. this._randomTexture.update(false);
  35347. };
  35348. return SSAORenderingPipeline;
  35349. })(BABYLON.PostProcessRenderPipeline);
  35350. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  35351. })(BABYLON || (BABYLON = {}));
  35352. var BABYLON;
  35353. (function (BABYLON) {
  35354. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  35355. var VolumetricLightScatteringPostProcess = (function (_super) {
  35356. __extends(VolumetricLightScatteringPostProcess, _super);
  35357. /**
  35358. * @constructor
  35359. * @param {string} name - The post-process name
  35360. * @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)
  35361. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  35362. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  35363. * @param {number} samples - The post-process quality, default 100
  35364. * @param {number} samplingMode - The post-process filtering mode
  35365. * @param {BABYLON.Engine} engine - The babylon engine
  35366. * @param {boolean} reusable - If the post-process is reusable
  35367. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  35368. */
  35369. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  35370. var _this = this;
  35371. if (samples === void 0) { samples = 100; }
  35372. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  35373. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  35374. this._screenCoordinates = BABYLON.Vector2.Zero();
  35375. /**
  35376. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  35377. * @type {boolean}
  35378. */
  35379. this.useCustomMeshPosition = false;
  35380. /**
  35381. * If the post-process should inverse the light scattering direction
  35382. * @type {boolean}
  35383. */
  35384. this.invert = true;
  35385. /**
  35386. * Set to true to use the diffuseColor instead of the diffuseTexture
  35387. * @type {boolean}
  35388. */
  35389. this.useDiffuseColor = false;
  35390. /**
  35391. * Array containing the excluded meshes not rendered in the internal pass
  35392. */
  35393. this.excludedMeshes = new Array();
  35394. /**
  35395. * Controls the overall intensity of the post-process
  35396. * @type {number}
  35397. */
  35398. this.exposure = 0.3;
  35399. /**
  35400. * Dissipates each sample's contribution in range [0, 1]
  35401. * @type {number}
  35402. */
  35403. this.decay = 0.96815;
  35404. /**
  35405. * Controls the overall intensity of each sample
  35406. * @type {number}
  35407. */
  35408. this.weight = 0.58767;
  35409. /**
  35410. * Controls the density of each sample
  35411. * @type {number}
  35412. */
  35413. this.density = 0.926;
  35414. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  35415. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  35416. // Configure mesh
  35417. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  35418. // Configure
  35419. this._createPass(scene, ratio.passRatio || ratio);
  35420. this.onActivate = function (camera) {
  35421. if (!_this.isSupported) {
  35422. _this.dispose(camera);
  35423. }
  35424. _this.onActivate = null;
  35425. };
  35426. this.onApply = function (effect) {
  35427. _this._updateMeshScreenCoordinates(scene);
  35428. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  35429. effect.setFloat("exposure", _this.exposure);
  35430. effect.setFloat("decay", _this.decay);
  35431. effect.setFloat("weight", _this.weight);
  35432. effect.setFloat("density", _this.density);
  35433. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  35434. };
  35435. }
  35436. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  35437. var mesh = subMesh.getMesh();
  35438. var defines = [];
  35439. var attribs = [BABYLON.VertexBuffer.PositionKind];
  35440. var material = subMesh.getMaterial();
  35441. var needUV = false;
  35442. // Render this.mesh as default
  35443. if (mesh === this.mesh) {
  35444. if (this.useDiffuseColor) {
  35445. defines.push("#define DIFFUSE_COLOR_RENDER");
  35446. }
  35447. else if (material) {
  35448. if (material.diffuseTexture !== undefined) {
  35449. defines.push("#define BASIC_RENDER");
  35450. }
  35451. else {
  35452. defines.push("#define DIFFUSE_COLOR_RENDER");
  35453. }
  35454. }
  35455. defines.push("#define NEED_UV");
  35456. needUV = true;
  35457. }
  35458. // Alpha test
  35459. if (material) {
  35460. if (material.needAlphaTesting()) {
  35461. defines.push("#define ALPHATEST");
  35462. }
  35463. if (material.opacityTexture !== undefined) {
  35464. defines.push("#define OPACITY");
  35465. if (material.opacityTexture.getAlphaFromRGB) {
  35466. defines.push("#define OPACITYRGB");
  35467. }
  35468. if (!needUV) {
  35469. defines.push("#define NEED_UV");
  35470. }
  35471. }
  35472. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35473. attribs.push(BABYLON.VertexBuffer.UVKind);
  35474. defines.push("#define UV1");
  35475. }
  35476. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35477. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  35478. defines.push("#define UV2");
  35479. }
  35480. }
  35481. // Bones
  35482. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  35483. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35484. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35485. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  35486. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  35487. }
  35488. else {
  35489. defines.push("#define NUM_BONE_INFLUENCERS 0");
  35490. }
  35491. // Instances
  35492. if (useInstances) {
  35493. defines.push("#define INSTANCES");
  35494. attribs.push("world0");
  35495. attribs.push("world1");
  35496. attribs.push("world2");
  35497. attribs.push("world3");
  35498. }
  35499. // Get correct effect
  35500. var join = defines.join("\n");
  35501. if (this._cachedDefines !== join) {
  35502. this._cachedDefines = join;
  35503. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "opacityLevel", "color"], ["diffuseSampler", "opacitySampler"], join);
  35504. }
  35505. return this._volumetricLightScatteringPass.isReady();
  35506. };
  35507. /**
  35508. * Sets the new light position for light scattering effect
  35509. * @param {BABYLON.Vector3} The new custom light position
  35510. */
  35511. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  35512. this._customMeshPosition = position;
  35513. };
  35514. /**
  35515. * Returns the light position for light scattering effect
  35516. * @return {BABYLON.Vector3} The custom light position
  35517. */
  35518. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  35519. return this._customMeshPosition;
  35520. };
  35521. /**
  35522. * Disposes the internal assets and detaches the post-process from the camera
  35523. */
  35524. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  35525. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  35526. if (rttIndex !== -1) {
  35527. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  35528. }
  35529. this._volumetricLightScatteringRTT.dispose();
  35530. _super.prototype.dispose.call(this, camera);
  35531. };
  35532. /**
  35533. * Returns the render target texture used by the post-process
  35534. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  35535. */
  35536. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  35537. return this._volumetricLightScatteringRTT;
  35538. };
  35539. // Private methods
  35540. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  35541. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  35542. return true;
  35543. }
  35544. return false;
  35545. };
  35546. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  35547. var _this = this;
  35548. var engine = scene.getEngine();
  35549. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  35550. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35551. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35552. this._volumetricLightScatteringRTT.renderList = null;
  35553. this._volumetricLightScatteringRTT.renderParticles = false;
  35554. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  35555. // Custom render function for submeshes
  35556. var renderSubMesh = function (subMesh) {
  35557. var mesh = subMesh.getRenderingMesh();
  35558. if (_this._meshExcluded(mesh)) {
  35559. return;
  35560. }
  35561. var scene = mesh.getScene();
  35562. var engine = scene.getEngine();
  35563. // Culling
  35564. engine.setState(subMesh.getMaterial().backFaceCulling);
  35565. // Managing instances
  35566. var batch = mesh._getInstancesRenderList(subMesh._id);
  35567. if (batch.mustReturn) {
  35568. return;
  35569. }
  35570. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  35571. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  35572. engine.enableEffect(_this._volumetricLightScatteringPass);
  35573. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  35574. var material = subMesh.getMaterial();
  35575. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  35576. // Alpha test
  35577. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  35578. var alphaTexture = material.getAlphaTestTexture();
  35579. if ((_this.useDiffuseColor || alphaTexture === undefined) && mesh === _this.mesh) {
  35580. _this._volumetricLightScatteringPass.setColor3("color", material.diffuseColor);
  35581. }
  35582. if (material.needAlphaTesting() || (mesh === _this.mesh && alphaTexture && !_this.useDiffuseColor)) {
  35583. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  35584. if (alphaTexture) {
  35585. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  35586. }
  35587. }
  35588. if (material.opacityTexture !== undefined) {
  35589. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  35590. _this._volumetricLightScatteringPass.setFloat("opacityLevel", material.opacityTexture.level);
  35591. }
  35592. }
  35593. // Bones
  35594. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  35595. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  35596. }
  35597. // Draw
  35598. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  35599. }
  35600. };
  35601. // Render target texture callbacks
  35602. var savedSceneClearColor;
  35603. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  35604. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  35605. savedSceneClearColor = scene.clearColor;
  35606. scene.clearColor = sceneClearColor;
  35607. };
  35608. this._volumetricLightScatteringRTT.onAfterRender = function () {
  35609. scene.clearColor = savedSceneClearColor;
  35610. };
  35611. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  35612. var engine = scene.getEngine();
  35613. var index;
  35614. for (index = 0; index < opaqueSubMeshes.length; index++) {
  35615. renderSubMesh(opaqueSubMeshes.data[index]);
  35616. }
  35617. engine.setAlphaTesting(true);
  35618. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  35619. renderSubMesh(alphaTestSubMeshes.data[index]);
  35620. }
  35621. engine.setAlphaTesting(false);
  35622. if (transparentSubMeshes.length) {
  35623. // Sort sub meshes
  35624. for (index = 0; index < transparentSubMeshes.length; index++) {
  35625. var submesh = transparentSubMeshes.data[index];
  35626. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  35627. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  35628. }
  35629. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  35630. sortedArray.sort(function (a, b) {
  35631. // Alpha index first
  35632. if (a._alphaIndex > b._alphaIndex) {
  35633. return 1;
  35634. }
  35635. if (a._alphaIndex < b._alphaIndex) {
  35636. return -1;
  35637. }
  35638. // Then distance to camera
  35639. if (a._distanceToCamera < b._distanceToCamera) {
  35640. return 1;
  35641. }
  35642. if (a._distanceToCamera > b._distanceToCamera) {
  35643. return -1;
  35644. }
  35645. return 0;
  35646. });
  35647. // Render sub meshes
  35648. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  35649. for (index = 0; index < sortedArray.length; index++) {
  35650. renderSubMesh(sortedArray[index]);
  35651. }
  35652. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  35653. }
  35654. };
  35655. };
  35656. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  35657. var transform = scene.getTransformMatrix();
  35658. var meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  35659. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  35660. this._screenCoordinates.x = pos.x / this._viewPort.width;
  35661. this._screenCoordinates.y = pos.y / this._viewPort.height;
  35662. if (this.invert)
  35663. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  35664. };
  35665. // Static methods
  35666. /**
  35667. * Creates a default mesh for the Volumeric Light Scattering post-process
  35668. * @param {string} The mesh name
  35669. * @param {BABYLON.Scene} The scene where to create the mesh
  35670. * @return {BABYLON.Mesh} the default mesh
  35671. */
  35672. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  35673. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  35674. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  35675. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  35676. return mesh;
  35677. };
  35678. return VolumetricLightScatteringPostProcess;
  35679. })(BABYLON.PostProcess);
  35680. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  35681. })(BABYLON || (BABYLON = {}));
  35682. // BABYLON.JS Chromatic Aberration GLSL Shader
  35683. // Author: Olivier Guyot
  35684. // Separates very slightly R, G and B colors on the edges of the screen
  35685. // Inspired by Francois Tarlier & Martins Upitis
  35686. var BABYLON;
  35687. (function (BABYLON) {
  35688. var LensRenderingPipeline = (function (_super) {
  35689. __extends(LensRenderingPipeline, _super);
  35690. /**
  35691. * @constructor
  35692. *
  35693. * Effect parameters are as follow:
  35694. * {
  35695. * chromatic_aberration: number; // from 0 to x (1 for realism)
  35696. * edge_blur: number; // from 0 to x (1 for realism)
  35697. * distortion: number; // from 0 to x (1 for realism)
  35698. * grain_amount: number; // from 0 to 1
  35699. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  35700. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  35701. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  35702. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  35703. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  35704. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  35705. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  35706. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  35707. * }
  35708. * Note: if an effect parameter is unset, effect is disabled
  35709. *
  35710. * @param {string} name - The rendering pipeline name
  35711. * @param {object} parameters - An object containing all parameters (see above)
  35712. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  35713. * @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)
  35714. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  35715. */
  35716. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  35717. var _this = this;
  35718. if (ratio === void 0) { ratio = 1.0; }
  35719. _super.call(this, scene.getEngine(), name);
  35720. // Lens effects can be of the following:
  35721. // - chromatic aberration (slight shift of RGB colors)
  35722. // - blur on the edge of the lens
  35723. // - lens distortion
  35724. // - depth-of-field blur & highlights enhancing
  35725. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  35726. // - grain effect (noise or custom texture)
  35727. // Two additional texture samplers are needed:
  35728. // - depth map (for depth-of-field)
  35729. // - grain texture
  35730. /**
  35731. * The chromatic aberration PostProcess id in the pipeline
  35732. * @type {string}
  35733. */
  35734. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  35735. /**
  35736. * The highlights enhancing PostProcess id in the pipeline
  35737. * @type {string}
  35738. */
  35739. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  35740. /**
  35741. * The depth-of-field PostProcess id in the pipeline
  35742. * @type {string}
  35743. */
  35744. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  35745. this._scene = scene;
  35746. // Fetch texture samplers
  35747. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  35748. if (parameters.grain_texture) {
  35749. this._grainTexture = parameters.grain_texture;
  35750. }
  35751. else {
  35752. this._createGrainTexture();
  35753. }
  35754. // save parameters
  35755. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  35756. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  35757. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  35758. this._distortion = parameters.distortion ? parameters.distortion : 0;
  35759. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  35760. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  35761. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  35762. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  35763. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  35764. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  35765. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  35766. // Create effects
  35767. this._createChromaticAberrationPostProcess(ratio);
  35768. this._createHighlightsPostProcess(ratio);
  35769. this._createDepthOfFieldPostProcess(ratio / 4);
  35770. // Set up pipeline
  35771. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  35772. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  35773. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  35774. if (this._highlightsGain === -1) {
  35775. this._disableEffect(this.HighlightsEnhancingEffect, null);
  35776. }
  35777. // Finish
  35778. scene.postProcessRenderPipelineManager.addPipeline(this);
  35779. if (cameras) {
  35780. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  35781. }
  35782. }
  35783. // public methods (self explanatory)
  35784. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  35785. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  35786. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  35787. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  35788. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  35789. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  35790. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  35791. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  35792. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  35793. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  35794. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  35795. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  35796. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  35797. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  35798. };
  35799. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  35800. this._highlightsPostProcess.updateEffect();
  35801. };
  35802. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  35803. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  35804. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  35805. this._highlightsGain = amount;
  35806. };
  35807. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  35808. if (this._highlightsGain === -1) {
  35809. this._highlightsGain = 1.0;
  35810. }
  35811. this._highlightsThreshold = amount;
  35812. };
  35813. LensRenderingPipeline.prototype.disableHighlights = function () {
  35814. this._highlightsGain = -1;
  35815. };
  35816. /**
  35817. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  35818. */
  35819. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  35820. if (disableDepthRender === void 0) { disableDepthRender = false; }
  35821. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  35822. this._chromaticAberrationPostProcess = undefined;
  35823. this._highlightsPostProcess = undefined;
  35824. this._depthOfFieldPostProcess = undefined;
  35825. this._grainTexture.dispose();
  35826. if (disableDepthRender)
  35827. this._scene.disableDepthRenderer();
  35828. };
  35829. // colors shifting and distortion
  35830. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  35831. var _this = this;
  35832. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  35833. [], // samplers
  35834. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  35835. this._chromaticAberrationPostProcess.onApply = function (effect) {
  35836. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  35837. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  35838. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  35839. };
  35840. };
  35841. // highlights enhancing
  35842. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  35843. var _this = this;
  35844. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  35845. [], // samplers
  35846. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  35847. this._highlightsPostProcess.onApply = function (effect) {
  35848. effect.setFloat('gain', _this._highlightsGain);
  35849. effect.setFloat('threshold', _this._highlightsThreshold);
  35850. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  35851. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  35852. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  35853. };
  35854. };
  35855. // colors shifting and distortion
  35856. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  35857. var _this = this;
  35858. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  35859. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  35860. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  35861. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  35862. this._depthOfFieldPostProcess.onApply = function (effect) {
  35863. effect.setTexture("depthSampler", _this._depthTexture);
  35864. effect.setTexture("grainSampler", _this._grainTexture);
  35865. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  35866. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  35867. effect.setFloat('grain_amount', _this._grainAmount);
  35868. effect.setBool('blur_noise', _this._blurNoise);
  35869. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  35870. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  35871. effect.setFloat('distortion', _this._distortion);
  35872. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  35873. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  35874. effect.setFloat('aperture', _this._dofAperture);
  35875. effect.setFloat('darken', _this._dofDarken);
  35876. effect.setFloat('edge_blur', _this._edgeBlur);
  35877. effect.setBool('highlights', (_this._highlightsGain !== -1));
  35878. effect.setFloat('near', _this._scene.activeCamera.minZ);
  35879. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  35880. };
  35881. };
  35882. // creates a black and white random noise texture, 512x512
  35883. LensRenderingPipeline.prototype._createGrainTexture = function () {
  35884. var size = 512;
  35885. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  35886. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  35887. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  35888. var context = this._grainTexture.getContext();
  35889. var rand = function (min, max) {
  35890. return Math.random() * (max - min) + min;
  35891. };
  35892. var value;
  35893. for (var x = 0; x < size; x++) {
  35894. for (var y = 0; y < size; y++) {
  35895. value = Math.floor(rand(0.42, 0.58) * 255);
  35896. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  35897. context.fillRect(x, y, 1, 1);
  35898. }
  35899. }
  35900. this._grainTexture.update(false);
  35901. };
  35902. return LensRenderingPipeline;
  35903. })(BABYLON.PostProcessRenderPipeline);
  35904. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  35905. })(BABYLON || (BABYLON = {}));
  35906. //
  35907. // This post-process allows the modification of rendered colors by using
  35908. // a 'look-up table' (LUT). This effect is also called Color Grading.
  35909. //
  35910. // The object needs to be provided an url to a texture containing the color
  35911. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  35912. // Use an image editing software to tweak the LUT to match your needs.
  35913. //
  35914. // For an example of a color LUT, see here:
  35915. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  35916. // For explanations on color grading, see here:
  35917. // http://udn.epicgames.com/Three/ColorGrading.html
  35918. //
  35919. var BABYLON;
  35920. (function (BABYLON) {
  35921. var ColorCorrectionPostProcess = (function (_super) {
  35922. __extends(ColorCorrectionPostProcess, _super);
  35923. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  35924. var _this = this;
  35925. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  35926. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  35927. this._colorTableTexture.anisotropicFilteringLevel = 1;
  35928. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35929. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35930. this.onApply = function (effect) {
  35931. effect.setTexture("colorTable", _this._colorTableTexture);
  35932. };
  35933. }
  35934. return ColorCorrectionPostProcess;
  35935. })(BABYLON.PostProcess);
  35936. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  35937. })(BABYLON || (BABYLON = {}));
  35938. var BABYLON;
  35939. (function (BABYLON) {
  35940. var HDRRenderingPipeline = (function (_super) {
  35941. __extends(HDRRenderingPipeline, _super);
  35942. /**
  35943. * @constructor
  35944. * @param {string} name - The rendering pipeline name
  35945. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  35946. * @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)
  35947. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  35948. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  35949. */
  35950. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  35951. var _this = this;
  35952. if (originalPostProcess === void 0) { originalPostProcess = null; }
  35953. _super.call(this, scene.getEngine(), name);
  35954. /**
  35955. * Public members
  35956. */
  35957. // Gaussian Blur
  35958. /**
  35959. * Gaussian blur coefficient
  35960. * @type {number}
  35961. */
  35962. this.gaussCoeff = 0.3;
  35963. /**
  35964. * Gaussian blur mean
  35965. * @type {number}
  35966. */
  35967. this.gaussMean = 1.0;
  35968. /**
  35969. * Gaussian blur standard deviation
  35970. * @type {number}
  35971. */
  35972. this.gaussStandDev = 0.8;
  35973. /**
  35974. * Gaussian blur multiplier. Multiplies the blur effect
  35975. * @type {number}
  35976. */
  35977. this.gaussMultiplier = 4.0;
  35978. // HDR
  35979. /**
  35980. * Exposure, controls the overall intensity of the pipeline
  35981. * @type {number}
  35982. */
  35983. this.exposure = 1.0;
  35984. /**
  35985. * Minimum luminance that the post-process can output. Luminance is >= 0
  35986. * @type {number}
  35987. */
  35988. this.minimumLuminance = 1.0;
  35989. /**
  35990. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  35991. * @type {number}
  35992. */
  35993. this.maximumLuminance = 1e20;
  35994. /**
  35995. * Increase rate for luminance: eye adaptation speed to dark
  35996. * @type {number}
  35997. */
  35998. this.luminanceIncreaserate = 0.5;
  35999. /**
  36000. * Decrease rate for luminance: eye adaptation speed to bright
  36001. * @type {number}
  36002. */
  36003. this.luminanceDecreaseRate = 0.5;
  36004. // Bright pass
  36005. /**
  36006. * Minimum luminance needed to compute HDR
  36007. * @type {number}
  36008. */
  36009. this.brightThreshold = 0.8;
  36010. this._needUpdate = true;
  36011. this._scene = scene;
  36012. // Bright pass
  36013. this._createBrightPassPostProcess(scene, ratio);
  36014. // Down sample X4
  36015. this._createDownSampleX4PostProcess(scene, ratio);
  36016. // Create gaussian blur post-processes
  36017. this._createGaussianBlurPostProcess(scene, ratio);
  36018. // Texture adder
  36019. this._createTextureAdderPostProcess(scene, ratio);
  36020. // Luminance generator
  36021. this._createLuminanceGeneratorPostProcess(scene);
  36022. // HDR
  36023. this._createHDRPostProcess(scene, ratio);
  36024. // Pass postprocess
  36025. if (originalPostProcess === null) {
  36026. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  36027. }
  36028. else {
  36029. this._originalPostProcess = originalPostProcess;
  36030. }
  36031. // Configure pipeline
  36032. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  36033. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  36034. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  36035. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  36036. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  36037. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  36038. var addDownSamplerPostProcess = function (id) {
  36039. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  36040. };
  36041. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  36042. addDownSamplerPostProcess(i);
  36043. }
  36044. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  36045. // Finish
  36046. scene.postProcessRenderPipelineManager.addPipeline(this);
  36047. if (cameras !== null) {
  36048. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  36049. }
  36050. this.update();
  36051. }
  36052. /**
  36053. * Tells the pipeline to update its post-processes
  36054. */
  36055. HDRRenderingPipeline.prototype.update = function () {
  36056. this._needUpdate = true;
  36057. };
  36058. /**
  36059. * Returns the current calculated luminance
  36060. */
  36061. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  36062. return this._hdrCurrentLuminance;
  36063. };
  36064. /**
  36065. * Returns the currently drawn luminance
  36066. */
  36067. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  36068. return this._hdrOutputLuminance;
  36069. };
  36070. /**
  36071. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  36072. */
  36073. HDRRenderingPipeline.prototype.dispose = function () {
  36074. this._originalPostProcess = undefined;
  36075. this._brightPassPostProcess = undefined;
  36076. this._downSampleX4PostProcess = undefined;
  36077. this._guassianBlurHPostProcess = undefined;
  36078. this._guassianBlurVPostProcess = undefined;
  36079. this._textureAdderPostProcess = undefined;
  36080. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  36081. this._downSamplePostProcesses[i] = undefined;
  36082. }
  36083. this._hdrPostProcess = undefined;
  36084. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  36085. };
  36086. /**
  36087. * Creates the HDR post-process and computes the luminance adaptation
  36088. */
  36089. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  36090. var _this = this;
  36091. var hdrLastLuminance = 0.0;
  36092. this._hdrOutputLuminance = -1.0;
  36093. this._hdrCurrentLuminance = 1.0;
  36094. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  36095. this._hdrPostProcess.onApply = function (effect) {
  36096. if (_this._hdrOutputLuminance < 0.0) {
  36097. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  36098. }
  36099. else {
  36100. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  36101. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  36102. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  36103. }
  36104. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  36105. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  36106. }
  36107. else {
  36108. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  36109. }
  36110. }
  36111. _this._hdrOutputLuminance = BABYLON.Tools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  36112. hdrLastLuminance += scene.getEngine().getDeltaTime();
  36113. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  36114. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  36115. effect.setFloat("exposure", _this.exposure);
  36116. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  36117. _this._needUpdate = false;
  36118. };
  36119. };
  36120. /**
  36121. * Texture Adder post-process
  36122. */
  36123. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  36124. var _this = this;
  36125. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  36126. this._textureAdderPostProcess.onApply = function (effect) {
  36127. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  36128. };
  36129. };
  36130. /**
  36131. * Down sample X4 post-process
  36132. */
  36133. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  36134. var _this = this;
  36135. var downSampleX4Offsets = new Array(32);
  36136. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  36137. this._downSampleX4PostProcess.onApply = function (effect) {
  36138. if (_this._needUpdate) {
  36139. var id = 0;
  36140. for (var i = -2; i < 2; i++) {
  36141. for (var j = -2; j < 2; j++) {
  36142. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  36143. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  36144. id += 2;
  36145. }
  36146. }
  36147. }
  36148. effect.setArray2("dsOffsets", downSampleX4Offsets);
  36149. };
  36150. };
  36151. /**
  36152. * Bright pass post-process
  36153. */
  36154. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  36155. var _this = this;
  36156. var brightOffsets = new Array(8);
  36157. var brightPassCallback = function (effect) {
  36158. if (_this._needUpdate) {
  36159. var sU = (1.0 / _this._brightPassPostProcess.width);
  36160. var sV = (1.0 / _this._brightPassPostProcess.height);
  36161. brightOffsets[0] = -0.5 * sU;
  36162. brightOffsets[1] = 0.5 * sV;
  36163. brightOffsets[2] = 0.5 * sU;
  36164. brightOffsets[3] = 0.5 * sV;
  36165. brightOffsets[4] = -0.5 * sU;
  36166. brightOffsets[5] = -0.5 * sV;
  36167. brightOffsets[6] = 0.5 * sU;
  36168. brightOffsets[7] = -0.5 * sV;
  36169. }
  36170. effect.setArray2("dsOffsets", brightOffsets);
  36171. effect.setFloat("brightThreshold", _this.brightThreshold);
  36172. };
  36173. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  36174. this._brightPassPostProcess.onApply = brightPassCallback;
  36175. };
  36176. /**
  36177. * Luminance generator. Creates the luminance post-process and down sample post-processes
  36178. */
  36179. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  36180. var _this = this;
  36181. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  36182. var luminanceOffsets = new Array(8);
  36183. var downSampleOffsets = new Array(18);
  36184. var halfDestPixelSize;
  36185. this._downSamplePostProcesses = new Array(lumSteps);
  36186. // Utils for luminance
  36187. var luminanceUpdateSourceOffsets = function (width, height) {
  36188. var sU = (1.0 / width);
  36189. var sV = (1.0 / height);
  36190. luminanceOffsets[0] = -0.5 * sU;
  36191. luminanceOffsets[1] = 0.5 * sV;
  36192. luminanceOffsets[2] = 0.5 * sU;
  36193. luminanceOffsets[3] = 0.5 * sV;
  36194. luminanceOffsets[4] = -0.5 * sU;
  36195. luminanceOffsets[5] = -0.5 * sV;
  36196. luminanceOffsets[6] = 0.5 * sU;
  36197. luminanceOffsets[7] = -0.5 * sV;
  36198. };
  36199. var luminanceUpdateDestOffsets = function (width, height) {
  36200. var id = 0;
  36201. for (var x = -1; x < 2; x++) {
  36202. for (var y = -1; y < 2; y++) {
  36203. downSampleOffsets[id] = (x) / width;
  36204. downSampleOffsets[id + 1] = (y) / height;
  36205. id += 2;
  36206. }
  36207. }
  36208. };
  36209. // Luminance callback
  36210. var luminanceCallback = function (effect) {
  36211. if (_this._needUpdate) {
  36212. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  36213. }
  36214. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  36215. effect.setArray2("lumOffsets", luminanceOffsets);
  36216. };
  36217. // Down sample callbacks
  36218. var downSampleCallback = function (indice) {
  36219. var i = indice;
  36220. return function (effect) {
  36221. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  36222. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  36223. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  36224. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  36225. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  36226. effect.setArray2("dsOffsets", downSampleOffsets);
  36227. };
  36228. };
  36229. var downSampleAfterRenderCallback = function (effect) {
  36230. // Unpack result
  36231. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  36232. 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);
  36233. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  36234. };
  36235. // Create luminance post-process
  36236. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  36237. 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);
  36238. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  36239. // Create down sample post-processes
  36240. for (var i = lumSteps - 2; i >= 0; i--) {
  36241. var length = Math.pow(3, i);
  36242. ratio = { width: length, height: length };
  36243. var defines = "#define DOWN_SAMPLE\n";
  36244. if (i === 0) {
  36245. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  36246. }
  36247. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  36248. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  36249. if (i === 0) {
  36250. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  36251. }
  36252. }
  36253. };
  36254. /**
  36255. * Gaussian blur post-processes. Horizontal and Vertical
  36256. */
  36257. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  36258. var _this = this;
  36259. var blurOffsetsW = new Array(9);
  36260. var blurOffsetsH = new Array(9);
  36261. var blurWeights = new Array(9);
  36262. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  36263. // Utils for gaussian blur
  36264. var calculateBlurOffsets = function (height) {
  36265. var lastOutputDimensions = {
  36266. width: scene.getEngine().getRenderWidth(),
  36267. height: scene.getEngine().getRenderHeight()
  36268. };
  36269. for (var i = 0; i < 9; i++) {
  36270. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  36271. if (height) {
  36272. blurOffsetsH[i] = value;
  36273. }
  36274. else {
  36275. blurOffsetsW[i] = value;
  36276. }
  36277. }
  36278. };
  36279. var calculateWeights = function () {
  36280. var x = 0.0;
  36281. for (var i = 0; i < 9; i++) {
  36282. x = (i - 4.0) / 4.0;
  36283. 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));
  36284. }
  36285. };
  36286. // Callback
  36287. var gaussianBlurCallback = function (height) {
  36288. return function (effect) {
  36289. if (_this._needUpdate) {
  36290. calculateWeights();
  36291. calculateBlurOffsets(height);
  36292. }
  36293. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  36294. effect.setArray("blurWeights", blurWeights);
  36295. effect.setFloat("multiplier", _this.gaussMultiplier);
  36296. };
  36297. };
  36298. // Create horizontal gaussian blur post-processes
  36299. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  36300. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  36301. // Create vertical gaussian blur post-process
  36302. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  36303. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  36304. };
  36305. // Luminance generator
  36306. HDRRenderingPipeline.LUM_STEPS = 6;
  36307. return HDRRenderingPipeline;
  36308. })(BABYLON.PostProcessRenderPipeline);
  36309. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  36310. })(BABYLON || (BABYLON = {}));
  36311. var BABYLON;
  36312. (function (BABYLON) {
  36313. var FaceAdjacencies = (function () {
  36314. function FaceAdjacencies() {
  36315. this.edges = new Array();
  36316. this.edgesConnectedCount = 0;
  36317. }
  36318. return FaceAdjacencies;
  36319. })();
  36320. var EdgesRenderer = (function () {
  36321. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  36322. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  36323. if (epsilon === void 0) { epsilon = 0.95; }
  36324. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  36325. this.edgesWidthScalerForOrthographic = 1000.0;
  36326. this.edgesWidthScalerForPerspective = 50.0;
  36327. this._linesPositions = new Array();
  36328. this._linesNormals = new Array();
  36329. this._linesIndices = new Array();
  36330. this._buffers = new Array();
  36331. this._checkVerticesInsteadOfIndices = false;
  36332. this._source = source;
  36333. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  36334. this._epsilon = epsilon;
  36335. this._prepareRessources();
  36336. this._generateEdgesLines();
  36337. }
  36338. EdgesRenderer.prototype._prepareRessources = function () {
  36339. if (this._lineShader) {
  36340. return;
  36341. }
  36342. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  36343. attributes: ["position", "normal"],
  36344. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  36345. });
  36346. this._lineShader.disableDepthWrite = true;
  36347. this._lineShader.backFaceCulling = false;
  36348. };
  36349. EdgesRenderer.prototype.dispose = function () {
  36350. this._vb0.dispose();
  36351. this._vb1.dispose();
  36352. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  36353. this._lineShader.dispose();
  36354. };
  36355. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  36356. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  36357. return 0;
  36358. }
  36359. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  36360. return 1;
  36361. }
  36362. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  36363. return 2;
  36364. }
  36365. return -1;
  36366. };
  36367. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  36368. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  36369. return 0;
  36370. }
  36371. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  36372. return 1;
  36373. }
  36374. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  36375. return 2;
  36376. }
  36377. return -1;
  36378. };
  36379. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  36380. var needToCreateLine;
  36381. if (edge === undefined) {
  36382. needToCreateLine = true;
  36383. }
  36384. else {
  36385. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  36386. needToCreateLine = dotProduct < this._epsilon;
  36387. }
  36388. if (needToCreateLine) {
  36389. var offset = this._linesPositions.length / 3;
  36390. var normal = p0.subtract(p1);
  36391. normal.normalize();
  36392. // Positions
  36393. this._linesPositions.push(p0.x);
  36394. this._linesPositions.push(p0.y);
  36395. this._linesPositions.push(p0.z);
  36396. this._linesPositions.push(p0.x);
  36397. this._linesPositions.push(p0.y);
  36398. this._linesPositions.push(p0.z);
  36399. this._linesPositions.push(p1.x);
  36400. this._linesPositions.push(p1.y);
  36401. this._linesPositions.push(p1.z);
  36402. this._linesPositions.push(p1.x);
  36403. this._linesPositions.push(p1.y);
  36404. this._linesPositions.push(p1.z);
  36405. // Normals
  36406. this._linesNormals.push(p1.x);
  36407. this._linesNormals.push(p1.y);
  36408. this._linesNormals.push(p1.z);
  36409. this._linesNormals.push(-1);
  36410. this._linesNormals.push(p1.x);
  36411. this._linesNormals.push(p1.y);
  36412. this._linesNormals.push(p1.z);
  36413. this._linesNormals.push(1);
  36414. this._linesNormals.push(p0.x);
  36415. this._linesNormals.push(p0.y);
  36416. this._linesNormals.push(p0.z);
  36417. this._linesNormals.push(-1);
  36418. this._linesNormals.push(p0.x);
  36419. this._linesNormals.push(p0.y);
  36420. this._linesNormals.push(p0.z);
  36421. this._linesNormals.push(1);
  36422. // Indices
  36423. this._linesIndices.push(offset);
  36424. this._linesIndices.push(offset + 1);
  36425. this._linesIndices.push(offset + 2);
  36426. this._linesIndices.push(offset);
  36427. this._linesIndices.push(offset + 2);
  36428. this._linesIndices.push(offset + 3);
  36429. }
  36430. };
  36431. EdgesRenderer.prototype._generateEdgesLines = function () {
  36432. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  36433. var indices = this._source.getIndices();
  36434. // First let's find adjacencies
  36435. var adjacencies = new Array();
  36436. var faceNormals = new Array();
  36437. var index;
  36438. var faceAdjacencies;
  36439. // Prepare faces
  36440. for (index = 0; index < indices.length; index += 3) {
  36441. faceAdjacencies = new FaceAdjacencies();
  36442. var p0Index = indices[index];
  36443. var p1Index = indices[index + 1];
  36444. var p2Index = indices[index + 2];
  36445. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  36446. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  36447. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  36448. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  36449. faceNormal.normalize();
  36450. faceNormals.push(faceNormal);
  36451. adjacencies.push(faceAdjacencies);
  36452. }
  36453. // Scan
  36454. for (index = 0; index < adjacencies.length; index++) {
  36455. faceAdjacencies = adjacencies[index];
  36456. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  36457. var otherFaceAdjacencies = adjacencies[otherIndex];
  36458. if (faceAdjacencies.edgesConnectedCount === 3) {
  36459. break;
  36460. }
  36461. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  36462. continue;
  36463. }
  36464. var otherP0 = indices[otherIndex * 3];
  36465. var otherP1 = indices[otherIndex * 3 + 1];
  36466. var otherP2 = indices[otherIndex * 3 + 2];
  36467. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  36468. var otherEdgeIndex;
  36469. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  36470. continue;
  36471. }
  36472. switch (edgeIndex) {
  36473. case 0:
  36474. if (this._checkVerticesInsteadOfIndices) {
  36475. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  36476. }
  36477. else {
  36478. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  36479. }
  36480. break;
  36481. case 1:
  36482. if (this._checkVerticesInsteadOfIndices) {
  36483. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  36484. }
  36485. else {
  36486. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  36487. }
  36488. break;
  36489. case 2:
  36490. if (this._checkVerticesInsteadOfIndices) {
  36491. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  36492. }
  36493. else {
  36494. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  36495. }
  36496. break;
  36497. }
  36498. if (otherEdgeIndex === -1) {
  36499. continue;
  36500. }
  36501. faceAdjacencies.edges[edgeIndex] = otherIndex;
  36502. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  36503. faceAdjacencies.edgesConnectedCount++;
  36504. otherFaceAdjacencies.edgesConnectedCount++;
  36505. if (faceAdjacencies.edgesConnectedCount === 3) {
  36506. break;
  36507. }
  36508. }
  36509. }
  36510. }
  36511. // Create lines
  36512. for (index = 0; index < adjacencies.length; index++) {
  36513. // 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
  36514. var current = adjacencies[index];
  36515. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  36516. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  36517. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  36518. }
  36519. // Merge into a single mesh
  36520. var engine = this._source.getScene().getEngine();
  36521. this._vb0 = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  36522. this._vb1 = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  36523. this._buffers[BABYLON.VertexBuffer.PositionKind] = this._vb0;
  36524. this._buffers[BABYLON.VertexBuffer.NormalKind] = this._vb1;
  36525. this._ib = engine.createIndexBuffer(this._linesIndices);
  36526. this._indicesCount = this._linesIndices.length;
  36527. };
  36528. EdgesRenderer.prototype.render = function () {
  36529. if (!this._lineShader.isReady()) {
  36530. return;
  36531. }
  36532. var scene = this._source.getScene();
  36533. var engine = scene.getEngine();
  36534. this._lineShader._preBind();
  36535. // VBOs
  36536. engine.bindMultiBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  36537. scene.resetCachedMaterial();
  36538. this._lineShader.setColor4("color", this._source.edgesColor);
  36539. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  36540. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  36541. }
  36542. else {
  36543. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  36544. }
  36545. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  36546. this._lineShader.bind(this._source.getWorldMatrix());
  36547. // Draw order
  36548. engine.draw(true, 0, this._indicesCount);
  36549. this._lineShader.unbind();
  36550. engine.setDepthWrite(true);
  36551. };
  36552. return EdgesRenderer;
  36553. })();
  36554. BABYLON.EdgesRenderer = EdgesRenderer;
  36555. })(BABYLON || (BABYLON = {}));
  36556. var BABYLON;
  36557. (function (BABYLON) {
  36558. (function (TonemappingOperator) {
  36559. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  36560. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  36561. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  36562. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  36563. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  36564. var TonemappingOperator = BABYLON.TonemappingOperator;
  36565. ;
  36566. var TonemapPostProcess = (function (_super) {
  36567. __extends(TonemapPostProcess, _super);
  36568. function TonemapPostProcess(name, operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  36569. var _this = this;
  36570. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  36571. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  36572. this._operator = operator;
  36573. this.exposureAdjustment = exposureAdjustment;
  36574. var params = ["_ExposureAdjustment"];
  36575. var defines = "#define ";
  36576. if (operator === TonemappingOperator.Hable)
  36577. defines += "HABLE_TONEMAPPING";
  36578. else if (operator === TonemappingOperator.Reinhard)
  36579. defines += "REINHARD_TONEMAPPING";
  36580. else if (operator === TonemappingOperator.HejiDawson)
  36581. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  36582. else if (operator === TonemappingOperator.Photographic)
  36583. defines += "PHOTOGRAPHIC_TONEMAPPING";
  36584. _super.call(this, name, "tonemap", params, null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  36585. this.onApply = function (effect) {
  36586. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  36587. };
  36588. }
  36589. return TonemapPostProcess;
  36590. })(BABYLON.PostProcess);
  36591. BABYLON.TonemapPostProcess = TonemapPostProcess;
  36592. })(BABYLON || (BABYLON = {}));
  36593. var BABYLON;
  36594. (function (BABYLON) {
  36595. var ReflectionProbe = (function () {
  36596. function ReflectionProbe(name, size, scene, generateMipMaps) {
  36597. var _this = this;
  36598. if (generateMipMaps === void 0) { generateMipMaps = true; }
  36599. this.name = name;
  36600. this._viewMatrix = BABYLON.Matrix.Identity();
  36601. this._target = BABYLON.Vector3.Zero();
  36602. this._add = BABYLON.Vector3.Zero();
  36603. this.position = BABYLON.Vector3.Zero();
  36604. this._scene = scene;
  36605. this._scene.reflectionProbes.push(this);
  36606. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  36607. this._renderTargetTexture.onBeforeRender = function (faceIndex) {
  36608. switch (faceIndex) {
  36609. case 0:
  36610. _this._add.copyFromFloats(1, 0, 0);
  36611. break;
  36612. case 1:
  36613. _this._add.copyFromFloats(-1, 0, 0);
  36614. break;
  36615. case 2:
  36616. _this._add.copyFromFloats(0, -1, 0);
  36617. break;
  36618. case 3:
  36619. _this._add.copyFromFloats(0, 1, 0);
  36620. break;
  36621. case 4:
  36622. _this._add.copyFromFloats(0, 0, 1);
  36623. break;
  36624. case 5:
  36625. _this._add.copyFromFloats(0, 0, -1);
  36626. break;
  36627. }
  36628. if (_this._attachedMesh) {
  36629. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  36630. }
  36631. _this.position.addToRef(_this._add, _this._target);
  36632. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  36633. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  36634. };
  36635. this._renderTargetTexture.onAfterUnbind = function () {
  36636. scene.updateTransformMatrix(true);
  36637. };
  36638. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  36639. }
  36640. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  36641. get: function () {
  36642. return this._renderTargetTexture.refreshRate;
  36643. },
  36644. set: function (value) {
  36645. this._renderTargetTexture.refreshRate = value;
  36646. },
  36647. enumerable: true,
  36648. configurable: true
  36649. });
  36650. ReflectionProbe.prototype.getScene = function () {
  36651. return this._scene;
  36652. };
  36653. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  36654. get: function () {
  36655. return this._renderTargetTexture;
  36656. },
  36657. enumerable: true,
  36658. configurable: true
  36659. });
  36660. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  36661. get: function () {
  36662. return this._renderTargetTexture.renderList;
  36663. },
  36664. enumerable: true,
  36665. configurable: true
  36666. });
  36667. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  36668. this._attachedMesh = mesh;
  36669. };
  36670. ReflectionProbe.prototype.dispose = function () {
  36671. var index = this._scene.reflectionProbes.indexOf(this);
  36672. if (index !== -1) {
  36673. // Remove from the scene if found
  36674. this._scene.reflectionProbes.splice(index, 1);
  36675. }
  36676. if (this._renderTargetTexture) {
  36677. this._renderTargetTexture.dispose();
  36678. this._renderTargetTexture = null;
  36679. }
  36680. };
  36681. return ReflectionProbe;
  36682. })();
  36683. BABYLON.ReflectionProbe = ReflectionProbe;
  36684. })(BABYLON || (BABYLON = {}));
  36685. var BABYLON;
  36686. (function (BABYLON) {
  36687. var SolidParticle = (function () {
  36688. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape) {
  36689. this.color = new BABYLON.Color4(1, 1, 1, 1); // color
  36690. this.position = BABYLON.Vector3.Zero(); // position
  36691. this.rotation = BABYLON.Vector3.Zero(); // rotation
  36692. this.scale = new BABYLON.Vector3(1, 1, 1); // scale
  36693. this.uvs = new BABYLON.Vector4(0, 0, 1, 1); // uvs
  36694. this.velocity = BABYLON.Vector3.Zero(); // velocity
  36695. this.alive = true; // alive
  36696. this.idx = particleIndex;
  36697. this._pos = positionIndex;
  36698. this._model = model;
  36699. this.shapeId = shapeId;
  36700. this.idxInShape = idxInShape;
  36701. }
  36702. return SolidParticle;
  36703. })();
  36704. BABYLON.SolidParticle = SolidParticle;
  36705. var ModelShape = (function () {
  36706. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  36707. this.shapeID = id;
  36708. this._shape = shape;
  36709. this._shapeUV = shapeUV;
  36710. this._positionFunction = posFunction;
  36711. this._vertexFunction = vtxFunction;
  36712. }
  36713. return ModelShape;
  36714. })();
  36715. BABYLON.ModelShape = ModelShape;
  36716. })(BABYLON || (BABYLON = {}));
  36717. var BABYLON;
  36718. (function (BABYLON) {
  36719. /**
  36720. * Full documentation here : http://doc.babylonjs.com/tutorials/Solid_Particle_System
  36721. */
  36722. var SolidParticleSystem = (function () {
  36723. /**
  36724. * Creates a SPS (Solid Particle System) object.
  36725. * @param name the SPS name, this will be the underlying mesh name
  36726. * @param scene the scene in which the SPS is added
  36727. * @param options "updatable" (default true) : if the SPS must be updatable or immutable, "isPickable" (default false) : if the solid particles must be pickable
  36728. */
  36729. function SolidParticleSystem(name, scene, options) {
  36730. // public members
  36731. /**
  36732. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  36733. * Example : var p = SPS.particles[i];
  36734. */
  36735. this.particles = new Array();
  36736. /**
  36737. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  36738. */
  36739. this.nbParticles = 0;
  36740. /**
  36741. * If the particles must ever face the camera (default false). Useful for planar particles.
  36742. */
  36743. this.billboard = false;
  36744. /**
  36745. * This a counter ofr your own usage. It's not set by any SPS functions.
  36746. */
  36747. this.counter = 0;
  36748. /**
  36749. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  36750. * Please read : http://doc.babylonjs.com/tutorials/Solid_Particle_System#garbage-collector-concerns
  36751. */
  36752. this.vars = {};
  36753. this._positions = new Array();
  36754. this._indices = new Array();
  36755. this._normals = new Array();
  36756. this._colors = new Array();
  36757. this._uvs = new Array();
  36758. this._index = 0; // indices index
  36759. this._updatable = true;
  36760. this._pickable = false;
  36761. this._isVisibilityBoxLocked = false;
  36762. this._alwaysVisible = false;
  36763. this._shapeCounter = 0;
  36764. this._copy = new BABYLON.SolidParticle(null, null, null, null, null);
  36765. this._color = new BABYLON.Color4(0, 0, 0, 0);
  36766. this._computeParticleColor = true;
  36767. this._computeParticleTexture = true;
  36768. this._computeParticleRotation = true;
  36769. this._computeParticleVertex = false;
  36770. this._computeBoundingBox = false;
  36771. this._cam_axisZ = BABYLON.Vector3.Zero();
  36772. this._cam_axisY = BABYLON.Vector3.Zero();
  36773. this._cam_axisX = BABYLON.Vector3.Zero();
  36774. this._axisX = BABYLON.Axis.X;
  36775. this._axisY = BABYLON.Axis.Y;
  36776. this._axisZ = BABYLON.Axis.Z;
  36777. this._fakeCamPos = BABYLON.Vector3.Zero();
  36778. this._rotMatrix = new BABYLON.Matrix();
  36779. this._invertMatrix = new BABYLON.Matrix();
  36780. this._rotated = BABYLON.Vector3.Zero();
  36781. this._quaternion = new BABYLON.Quaternion();
  36782. this._vertex = BABYLON.Vector3.Zero();
  36783. this._normal = BABYLON.Vector3.Zero();
  36784. this._yaw = 0.0;
  36785. this._pitch = 0.0;
  36786. this._roll = 0.0;
  36787. this._halfroll = 0.0;
  36788. this._halfpitch = 0.0;
  36789. this._halfyaw = 0.0;
  36790. this._sinRoll = 0.0;
  36791. this._cosRoll = 0.0;
  36792. this._sinPitch = 0.0;
  36793. this._cosPitch = 0.0;
  36794. this._sinYaw = 0.0;
  36795. this._cosYaw = 0.0;
  36796. this._w = 0.0;
  36797. this._minimum = BABYLON.Tmp.Vector3[0];
  36798. this._maximum = BABYLON.Tmp.Vector3[1];
  36799. this.name = name;
  36800. this._scene = scene;
  36801. this._camera = scene.activeCamera;
  36802. this._pickable = options ? options.isPickable : false;
  36803. if (options && options.updatable) {
  36804. this._updatable = options.updatable;
  36805. }
  36806. else {
  36807. this._updatable = true;
  36808. }
  36809. if (this._pickable) {
  36810. this.pickedParticles = [];
  36811. }
  36812. }
  36813. /**
  36814. * Builds the SPS underlying mesh. Returns a standard Mesh.
  36815. * If no model shape was added to the SPS, the return mesh is only a single triangular plane.
  36816. */
  36817. SolidParticleSystem.prototype.buildMesh = function () {
  36818. if (this.nbParticles === 0) {
  36819. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  36820. this.addShape(triangle, 1);
  36821. triangle.dispose();
  36822. }
  36823. this._positions32 = new Float32Array(this._positions);
  36824. this._uvs32 = new Float32Array(this._uvs);
  36825. this._colors32 = new Float32Array(this._colors);
  36826. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  36827. this._normals32 = new Float32Array(this._normals);
  36828. this._fixedNormal32 = new Float32Array(this._normals);
  36829. var vertexData = new BABYLON.VertexData();
  36830. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  36831. vertexData.indices = this._indices;
  36832. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  36833. if (this._uvs32) {
  36834. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  36835. ;
  36836. }
  36837. if (this._colors32) {
  36838. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  36839. }
  36840. var mesh = new BABYLON.Mesh(this.name, this._scene);
  36841. vertexData.applyToMesh(mesh, this._updatable);
  36842. this.mesh = mesh;
  36843. this.mesh.isPickable = this._pickable;
  36844. // free memory
  36845. this._positions = null;
  36846. this._normals = null;
  36847. this._uvs = null;
  36848. this._colors = null;
  36849. if (!this._updatable) {
  36850. this.particles.length = 0;
  36851. }
  36852. return mesh;
  36853. };
  36854. /**
  36855. * Digests the mesh and generates as many solid particles in the system as wanted.
  36856. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  36857. * Thus the particles generated from digest() have their property "positiion" yet set.
  36858. * @param mesh the mesh to be digested
  36859. * @param facetNb the number of mesh facets per particle (optional, default 1), this parameter is overriden by the parameter "number" if any
  36860. * @param number the wanted number of particles : each particle is built with mesh_total_facets / number facets (optional)
  36861. */
  36862. SolidParticleSystem.prototype.digest = function (mesh, options) {
  36863. var size = (options && options.facetNb) || 1;
  36864. var number = (options && options.number);
  36865. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  36866. var meshInd = mesh.getIndices();
  36867. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  36868. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  36869. var f = 0; // facet counter
  36870. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  36871. // compute size from number
  36872. if (number) {
  36873. number = (number > totalFacets) ? totalFacets : number;
  36874. size = Math.round(totalFacets / number);
  36875. }
  36876. else {
  36877. size = (size > totalFacets) ? totalFacets : size;
  36878. }
  36879. var facetPos = []; // submesh positions
  36880. var facetInd = []; // submesh indices
  36881. var facetUV = []; // submesh UV
  36882. var facetCol = []; // submesh colors
  36883. var barycenter = BABYLON.Tmp.Vector3[0];
  36884. while (f < totalFacets) {
  36885. if (f > totalFacets - size) {
  36886. size = totalFacets - f;
  36887. }
  36888. // reset temp arrays
  36889. facetPos.length = 0;
  36890. facetInd.length = 0;
  36891. facetUV.length = 0;
  36892. facetCol.length = 0;
  36893. // iterate over "size" facets
  36894. var fi = 0;
  36895. for (var j = f * 3; j < (f + size) * 3; j++) {
  36896. facetInd.push(fi);
  36897. var i = meshInd[j];
  36898. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  36899. if (meshUV) {
  36900. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  36901. }
  36902. if (meshCol) {
  36903. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  36904. }
  36905. fi++;
  36906. }
  36907. // create a model shape for each single particle
  36908. var idx = this.nbParticles;
  36909. var shape = this._posToShape(facetPos);
  36910. var shapeUV = this._uvsToShapeUV(facetUV);
  36911. // compute the barycenter of the shape
  36912. var v;
  36913. for (v = 0; v < shape.length; v++) {
  36914. barycenter.addInPlace(shape[v]);
  36915. }
  36916. barycenter.scaleInPlace(1 / shape.length);
  36917. // shift the shape from its barycenter to the origin
  36918. for (v = 0; v < shape.length; v++) {
  36919. shape[v].subtractInPlace(barycenter);
  36920. }
  36921. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  36922. // add the particle in the SPS
  36923. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, idx, 0, null);
  36924. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, 0);
  36925. // initialize the particle position
  36926. this.particles[this.nbParticles].position.addInPlace(barycenter);
  36927. this._index += shape.length;
  36928. idx++;
  36929. this.nbParticles++;
  36930. this._shapeCounter++;
  36931. f += size;
  36932. }
  36933. };
  36934. //reset copy
  36935. SolidParticleSystem.prototype._resetCopy = function () {
  36936. this._copy.position.x = 0;
  36937. this._copy.position.y = 0;
  36938. this._copy.position.z = 0;
  36939. this._copy.rotation.x = 0;
  36940. this._copy.rotation.y = 0;
  36941. this._copy.rotation.z = 0;
  36942. this._copy.quaternion = null;
  36943. this._copy.scale.x = 1;
  36944. this._copy.scale.y = 1;
  36945. this._copy.scale.z = 1;
  36946. this._copy.uvs.x = 0;
  36947. this._copy.uvs.y = 0;
  36948. this._copy.uvs.z = 1;
  36949. this._copy.uvs.w = 1;
  36950. this._copy.color = null;
  36951. };
  36952. // _meshBuilder : inserts the shape model in the global SPS mesh
  36953. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, idx, idxInShape, options) {
  36954. var i;
  36955. var u = 0;
  36956. var c = 0;
  36957. this._resetCopy();
  36958. if (options && options.positionFunction) {
  36959. options.positionFunction(this._copy, idx, idxInShape);
  36960. }
  36961. if (this._copy.quaternion) {
  36962. this._quaternion.x = this._copy.quaternion.x;
  36963. this._quaternion.y = this._copy.quaternion.y;
  36964. this._quaternion.z = this._copy.quaternion.z;
  36965. this._quaternion.w = this._copy.quaternion.w;
  36966. }
  36967. else {
  36968. this._yaw = this._copy.rotation.y;
  36969. this._pitch = this._copy.rotation.x;
  36970. this._roll = this._copy.rotation.z;
  36971. this._quaternionRotationYPR();
  36972. }
  36973. this._quaternionToRotationMatrix();
  36974. for (i = 0; i < shape.length; i++) {
  36975. this._vertex.x = shape[i].x;
  36976. this._vertex.y = shape[i].y;
  36977. this._vertex.z = shape[i].z;
  36978. if (options && options.vertexFunction) {
  36979. options.vertexFunction(this._copy, this._vertex, i);
  36980. }
  36981. this._vertex.x *= this._copy.scale.x;
  36982. this._vertex.y *= this._copy.scale.y;
  36983. this._vertex.z *= this._copy.scale.z;
  36984. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  36985. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  36986. if (meshUV) {
  36987. 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);
  36988. u += 2;
  36989. }
  36990. if (this._copy.color) {
  36991. this._color = this._copy.color;
  36992. }
  36993. else if (meshCol && meshCol[c]) {
  36994. this._color.r = meshCol[c];
  36995. this._color.g = meshCol[c + 1];
  36996. this._color.b = meshCol[c + 2];
  36997. this._color.a = meshCol[c + 3];
  36998. }
  36999. else {
  37000. this._color.r = 1;
  37001. this._color.g = 1;
  37002. this._color.b = 1;
  37003. this._color.a = 1;
  37004. }
  37005. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  37006. c += 4;
  37007. }
  37008. for (i = 0; i < meshInd.length; i++) {
  37009. indices.push(p + meshInd[i]);
  37010. }
  37011. if (this._pickable) {
  37012. var nbfaces = meshInd.length / 3;
  37013. for (i = 0; i < nbfaces; i++) {
  37014. this.pickedParticles.push({ idx: idx, faceId: i });
  37015. }
  37016. }
  37017. };
  37018. // returns a shape array from positions array
  37019. SolidParticleSystem.prototype._posToShape = function (positions) {
  37020. var shape = [];
  37021. for (var i = 0; i < positions.length; i += 3) {
  37022. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  37023. }
  37024. return shape;
  37025. };
  37026. // returns a shapeUV array from a Vector4 uvs
  37027. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  37028. var shapeUV = [];
  37029. if (uvs) {
  37030. for (var i = 0; i < uvs.length; i++)
  37031. shapeUV.push(uvs[i]);
  37032. }
  37033. return shapeUV;
  37034. };
  37035. // adds a new particle object in the particles array
  37036. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape) {
  37037. this.particles.push(new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape));
  37038. };
  37039. /**
  37040. * Adds some particles to the SPS from the model shape.
  37041. * Please read the doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#create-an-immutable-sps
  37042. * @param mesh any Mesh object that will be used as a model for the solid particles.
  37043. * @param nb the number of particles to be created from this model
  37044. * @param options positionFunction is an optional javascript function to called for each particle on SPS creation. vertexFunction an optional javascript function to called for each vertex of each particle on SPS creation
  37045. */
  37046. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  37047. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37048. var meshInd = mesh.getIndices();
  37049. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37050. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  37051. var shape = this._posToShape(meshPos);
  37052. var shapeUV = this._uvsToShapeUV(meshUV);
  37053. var posfunc = options ? options.positionFunction : null;
  37054. var vtxfunc = options ? options.vertexFunction : null;
  37055. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  37056. // particles
  37057. var idx = this.nbParticles;
  37058. for (var i = 0; i < nb; i++) {
  37059. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, idx, i, options);
  37060. if (this._updatable) {
  37061. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, i);
  37062. }
  37063. this._index += shape.length;
  37064. idx++;
  37065. }
  37066. this.nbParticles += nb;
  37067. this._shapeCounter++;
  37068. return this._shapeCounter - 1;
  37069. };
  37070. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  37071. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  37072. this._resetCopy();
  37073. if (particle._model._positionFunction) {
  37074. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  37075. }
  37076. if (this._copy.quaternion) {
  37077. this._quaternion.x = this._copy.quaternion.x;
  37078. this._quaternion.y = this._copy.quaternion.y;
  37079. this._quaternion.z = this._copy.quaternion.z;
  37080. this._quaternion.w = this._copy.quaternion.w;
  37081. }
  37082. else {
  37083. this._yaw = this._copy.rotation.y;
  37084. this._pitch = this._copy.rotation.x;
  37085. this._roll = this._copy.rotation.z;
  37086. this._quaternionRotationYPR();
  37087. }
  37088. this._quaternionToRotationMatrix();
  37089. this._shape = particle._model._shape;
  37090. for (var pt = 0; pt < this._shape.length; pt++) {
  37091. this._vertex.x = this._shape[pt].x;
  37092. this._vertex.y = this._shape[pt].y;
  37093. this._vertex.z = this._shape[pt].z;
  37094. if (particle._model._vertexFunction) {
  37095. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  37096. }
  37097. this._vertex.x *= this._copy.scale.x;
  37098. this._vertex.y *= this._copy.scale.y;
  37099. this._vertex.z *= this._copy.scale.z;
  37100. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  37101. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  37102. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  37103. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  37104. }
  37105. particle.position.x = 0;
  37106. particle.position.y = 0;
  37107. particle.position.z = 0;
  37108. particle.rotation.x = 0;
  37109. particle.rotation.y = 0;
  37110. particle.rotation.z = 0;
  37111. particle.quaternion = null;
  37112. particle.scale.x = 1;
  37113. particle.scale.y = 1;
  37114. particle.scale.z = 1;
  37115. };
  37116. /**
  37117. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  37118. */
  37119. SolidParticleSystem.prototype.rebuildMesh = function () {
  37120. for (var p = 0; p < this.particles.length; p++) {
  37121. this._rebuildParticle(this.particles[p]);
  37122. }
  37123. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  37124. };
  37125. /**
  37126. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  37127. * This method calls updateParticle() for each particles of the SPS.
  37128. * For an animated SPS, it is usually called within the render loop.
  37129. * @param start (default 0) the particle index in the particle array where to start to compute the particle property values
  37130. * @param end (default nbParticle - 1) the particle index in the particle array where to stop to compute the particle property values
  37131. * @param update (default true) if the mesh must be finally updated on this call after all the particle computations.
  37132. */
  37133. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  37134. if (start === void 0) { start = 0; }
  37135. if (end === void 0) { end = this.nbParticles - 1; }
  37136. if (update === void 0) { update = true; }
  37137. if (!this._updatable) {
  37138. return;
  37139. }
  37140. // custom beforeUpdate
  37141. this.beforeUpdateParticles(start, end, update);
  37142. this._cam_axisX.x = 1;
  37143. this._cam_axisX.y = 0;
  37144. this._cam_axisX.z = 0;
  37145. this._cam_axisY.x = 0;
  37146. this._cam_axisY.y = 1;
  37147. this._cam_axisY.z = 0;
  37148. this._cam_axisZ.x = 0;
  37149. this._cam_axisZ.y = 0;
  37150. this._cam_axisZ.z = 1;
  37151. // if the particles will always face the camera
  37152. if (this.billboard) {
  37153. // compute a fake camera position : un-rotate the camera position by the current mesh rotation
  37154. this._yaw = this.mesh.rotation.y;
  37155. this._pitch = this.mesh.rotation.x;
  37156. this._roll = this.mesh.rotation.z;
  37157. this._quaternionRotationYPR();
  37158. this._quaternionToRotationMatrix();
  37159. this._rotMatrix.invertToRef(this._invertMatrix);
  37160. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._fakeCamPos);
  37161. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the cam-mesh axis (_cam_axisZ)
  37162. (this._fakeCamPos).subtractToRef(this.mesh.position, this._cam_axisZ);
  37163. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  37164. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._cam_axisY, this._cam_axisX);
  37165. this._cam_axisY.normalize();
  37166. this._cam_axisX.normalize();
  37167. this._cam_axisZ.normalize();
  37168. }
  37169. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  37170. var idx = 0;
  37171. var index = 0;
  37172. var colidx = 0;
  37173. var colorIndex = 0;
  37174. var uvidx = 0;
  37175. var uvIndex = 0;
  37176. if (this._computeBoundingBox) {
  37177. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  37178. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  37179. }
  37180. // particle loop
  37181. end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
  37182. for (var p = start; p <= end; p++) {
  37183. this._particle = this.particles[p];
  37184. this._shape = this._particle._model._shape;
  37185. this._shapeUV = this._particle._model._shapeUV;
  37186. // call to custom user function to update the particle properties
  37187. this.updateParticle(this._particle);
  37188. // particle rotation matrix
  37189. if (this.billboard) {
  37190. this._particle.rotation.x = 0.0;
  37191. this._particle.rotation.y = 0.0;
  37192. }
  37193. if (this._computeParticleRotation) {
  37194. if (this._particle.quaternion) {
  37195. this._quaternion.x = this._particle.quaternion.x;
  37196. this._quaternion.y = this._particle.quaternion.y;
  37197. this._quaternion.z = this._particle.quaternion.z;
  37198. this._quaternion.w = this._particle.quaternion.w;
  37199. }
  37200. else {
  37201. this._yaw = this._particle.rotation.y;
  37202. this._pitch = this._particle.rotation.x;
  37203. this._roll = this._particle.rotation.z;
  37204. this._quaternionRotationYPR();
  37205. }
  37206. this._quaternionToRotationMatrix();
  37207. }
  37208. for (var pt = 0; pt < this._shape.length; pt++) {
  37209. idx = index + pt * 3;
  37210. colidx = colorIndex + pt * 4;
  37211. uvidx = uvIndex + pt * 2;
  37212. this._vertex.x = this._shape[pt].x;
  37213. this._vertex.y = this._shape[pt].y;
  37214. this._vertex.z = this._shape[pt].z;
  37215. if (this._computeParticleVertex) {
  37216. this.updateParticleVertex(this._particle, this._vertex, pt);
  37217. }
  37218. // positions
  37219. this._vertex.x *= this._particle.scale.x;
  37220. this._vertex.y *= this._particle.scale.y;
  37221. this._vertex.z *= this._particle.scale.z;
  37222. this._w = (this._vertex.x * this._rotMatrix.m[3]) + (this._vertex.y * this._rotMatrix.m[7]) + (this._vertex.z * this._rotMatrix.m[11]) + this._rotMatrix.m[15];
  37223. this._rotated.x = ((this._vertex.x * this._rotMatrix.m[0]) + (this._vertex.y * this._rotMatrix.m[4]) + (this._vertex.z * this._rotMatrix.m[8]) + this._rotMatrix.m[12]) / this._w;
  37224. this._rotated.y = ((this._vertex.x * this._rotMatrix.m[1]) + (this._vertex.y * this._rotMatrix.m[5]) + (this._vertex.z * this._rotMatrix.m[9]) + this._rotMatrix.m[13]) / this._w;
  37225. this._rotated.z = ((this._vertex.x * this._rotMatrix.m[2]) + (this._vertex.y * this._rotMatrix.m[6]) + (this._vertex.z * this._rotMatrix.m[10]) + this._rotMatrix.m[14]) / this._w;
  37226. 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;
  37227. 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;
  37228. 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;
  37229. if (this._computeBoundingBox) {
  37230. if (this._positions32[idx] < this._minimum.x) {
  37231. this._minimum.x = this._positions32[idx];
  37232. }
  37233. if (this._positions32[idx] > this._maximum.x) {
  37234. this._maximum.x = this._positions32[idx];
  37235. }
  37236. if (this._positions32[idx + 1] < this._minimum.y) {
  37237. this._minimum.y = this._positions32[idx + 1];
  37238. }
  37239. if (this._positions32[idx + 1] > this._maximum.y) {
  37240. this._maximum.y = this._positions32[idx + 1];
  37241. }
  37242. if (this._positions32[idx + 2] < this._minimum.z) {
  37243. this._minimum.z = this._positions32[idx + 2];
  37244. }
  37245. if (this._positions32[idx + 2] > this._maximum.z) {
  37246. this._maximum.z = this._positions32[idx + 2];
  37247. }
  37248. }
  37249. // normals : if the particles can't be morphed then just rotate the normals
  37250. if (!this._computeParticleVertex && !this.billboard) {
  37251. this._normal.x = this._fixedNormal32[idx];
  37252. this._normal.y = this._fixedNormal32[idx + 1];
  37253. this._normal.z = this._fixedNormal32[idx + 2];
  37254. this._w = (this._normal.x * this._rotMatrix.m[3]) + (this._normal.y * this._rotMatrix.m[7]) + (this._normal.z * this._rotMatrix.m[11]) + this._rotMatrix.m[15];
  37255. this._rotated.x = ((this._normal.x * this._rotMatrix.m[0]) + (this._normal.y * this._rotMatrix.m[4]) + (this._normal.z * this._rotMatrix.m[8]) + this._rotMatrix.m[12]) / this._w;
  37256. this._rotated.y = ((this._normal.x * this._rotMatrix.m[1]) + (this._normal.y * this._rotMatrix.m[5]) + (this._normal.z * this._rotMatrix.m[9]) + this._rotMatrix.m[13]) / this._w;
  37257. this._rotated.z = ((this._normal.x * this._rotMatrix.m[2]) + (this._normal.y * this._rotMatrix.m[6]) + (this._normal.z * this._rotMatrix.m[10]) + this._rotMatrix.m[14]) / this._w;
  37258. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  37259. this._normals32[idx + 1] = this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
  37260. this._normals32[idx + 2] = this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
  37261. }
  37262. if (this._computeParticleColor) {
  37263. this._colors32[colidx] = this._particle.color.r;
  37264. this._colors32[colidx + 1] = this._particle.color.g;
  37265. this._colors32[colidx + 2] = this._particle.color.b;
  37266. this._colors32[colidx + 3] = this._particle.color.a;
  37267. }
  37268. if (this._computeParticleTexture) {
  37269. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  37270. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  37271. }
  37272. }
  37273. index = idx + 3;
  37274. colorIndex = colidx + 4;
  37275. uvIndex = uvidx + 2;
  37276. }
  37277. if (update) {
  37278. if (this._computeParticleColor) {
  37279. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  37280. }
  37281. if (this._computeParticleTexture) {
  37282. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  37283. }
  37284. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  37285. if (!this.mesh.areNormalsFrozen) {
  37286. if (this._computeParticleVertex || this.billboard) {
  37287. // recompute the normals only if the particles can be morphed, update then the normal reference array
  37288. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32);
  37289. for (var i = 0; i < this._normals32.length; i++) {
  37290. this._fixedNormal32[i] = this._normals32[i];
  37291. }
  37292. }
  37293. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  37294. }
  37295. }
  37296. if (this._computeBoundingBox) {
  37297. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  37298. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  37299. }
  37300. this.afterUpdateParticles(start, end, update);
  37301. };
  37302. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  37303. this._halfroll = this._roll * 0.5;
  37304. this._halfpitch = this._pitch * 0.5;
  37305. this._halfyaw = this._yaw * 0.5;
  37306. this._sinRoll = Math.sin(this._halfroll);
  37307. this._cosRoll = Math.cos(this._halfroll);
  37308. this._sinPitch = Math.sin(this._halfpitch);
  37309. this._cosPitch = Math.cos(this._halfpitch);
  37310. this._sinYaw = Math.sin(this._halfyaw);
  37311. this._cosYaw = Math.cos(this._halfyaw);
  37312. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  37313. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  37314. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  37315. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  37316. };
  37317. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  37318. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  37319. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  37320. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  37321. this._rotMatrix.m[3] = 0;
  37322. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  37323. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  37324. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  37325. this._rotMatrix.m[7] = 0;
  37326. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  37327. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  37328. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  37329. this._rotMatrix.m[11] = 0;
  37330. this._rotMatrix.m[12] = 0;
  37331. this._rotMatrix.m[13] = 0;
  37332. this._rotMatrix.m[14] = 0;
  37333. this._rotMatrix.m[15] = 1.0;
  37334. };
  37335. /**
  37336. * Disposes the SPS
  37337. */
  37338. SolidParticleSystem.prototype.dispose = function () {
  37339. this.mesh.dispose();
  37340. this.vars = null;
  37341. // drop references to internal big arrays for the GC
  37342. this._positions = null;
  37343. this._indices = null;
  37344. this._normals = null;
  37345. this._uvs = null;
  37346. this._colors = null;
  37347. this._positions32 = null;
  37348. this._normals32 = null;
  37349. this._fixedNormal32 = null;
  37350. this._uvs32 = null;
  37351. this._colors32 = null;
  37352. this.pickedParticles = null;
  37353. };
  37354. /**
  37355. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  37356. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  37357. */
  37358. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  37359. if (!this._isVisibilityBoxLocked) {
  37360. this.mesh.refreshBoundingInfo();
  37361. }
  37362. };
  37363. /** Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  37364. * @param size the size (float) of the visibility box
  37365. * note : this doesn't lock the SPS mesh bounding box.
  37366. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  37367. */
  37368. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  37369. var vis = size / 2;
  37370. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  37371. };
  37372. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  37373. // getter and setter
  37374. /**
  37375. * True if the SPS is set as always visible
  37376. */
  37377. get: function () {
  37378. return this._alwaysVisible;
  37379. },
  37380. /**
  37381. * Sets the SPS as always visible or not
  37382. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  37383. */
  37384. set: function (val) {
  37385. this._alwaysVisible = val;
  37386. this.mesh.alwaysSelectAsActiveMesh = val;
  37387. },
  37388. enumerable: true,
  37389. configurable: true
  37390. });
  37391. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  37392. /**
  37393. * True if the SPS visibility box is locked. The underlying mesh bounding box is then not updatable any more.
  37394. */
  37395. get: function () {
  37396. return this._isVisibilityBoxLocked;
  37397. },
  37398. /**
  37399. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  37400. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  37401. */
  37402. set: function (val) {
  37403. this._isVisibilityBoxLocked = val;
  37404. this.mesh.getBoundingInfo().isLocked = val;
  37405. },
  37406. enumerable: true,
  37407. configurable: true
  37408. });
  37409. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  37410. // getters
  37411. get: function () {
  37412. return this._computeParticleRotation;
  37413. },
  37414. // Optimizer setters
  37415. /**
  37416. * Tells to setParticles() to compute the particle rotations or not.
  37417. * Default value : true. The SPS is faster when it's set to false.
  37418. * Note : the particle rotations aren't stored values, so setting computeParticleRotation to false will prevents the particle to rotate.
  37419. */
  37420. set: function (val) {
  37421. this._computeParticleRotation = val;
  37422. },
  37423. enumerable: true,
  37424. configurable: true
  37425. });
  37426. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  37427. get: function () {
  37428. return this._computeParticleColor;
  37429. },
  37430. /**
  37431. * Tells to setParticles() to compute the particle colors or not.
  37432. * Default value : true. The SPS is faster when it's set to false.
  37433. * Note : the particle colors are stored values, so setting computeParticleColor to false will keep yet the last colors set.
  37434. */
  37435. set: function (val) {
  37436. this._computeParticleColor = val;
  37437. },
  37438. enumerable: true,
  37439. configurable: true
  37440. });
  37441. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  37442. get: function () {
  37443. return this._computeParticleTexture;
  37444. },
  37445. /**
  37446. * Tells to setParticles() to compute the particle textures or not.
  37447. * Default value : true. The SPS is faster when it's set to false.
  37448. * Note : the particle textures are stored values, so setting computeParticleTexture to false will keep yet the last colors set.
  37449. */
  37450. set: function (val) {
  37451. this._computeParticleTexture = val;
  37452. },
  37453. enumerable: true,
  37454. configurable: true
  37455. });
  37456. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  37457. get: function () {
  37458. return this._computeParticleVertex;
  37459. },
  37460. /**
  37461. * Tells to setParticles() to call the vertex function for each vertex of each particle, or not.
  37462. * Default value : false. The SPS is faster when it's set to false.
  37463. * Note : the particle custom vertex positions aren't stored values.
  37464. */
  37465. set: function (val) {
  37466. this._computeParticleVertex = val;
  37467. },
  37468. enumerable: true,
  37469. configurable: true
  37470. });
  37471. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  37472. get: function () {
  37473. return this._computeBoundingBox;
  37474. },
  37475. /**
  37476. * Tells to setParticles() to compute or not the mesh bounding box when computing the particle positions.
  37477. */
  37478. set: function (val) {
  37479. this._computeBoundingBox = val;
  37480. },
  37481. enumerable: true,
  37482. configurable: true
  37483. });
  37484. // =======================================================================
  37485. // Particle behavior logic
  37486. // these following methods may be overwritten by the user to fit his needs
  37487. /**
  37488. * This function does nothing. It may be overwritten to set all the particles first values.
  37489. * The SPS doesn't call this function, you may have to call it by your own.
  37490. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  37491. */
  37492. SolidParticleSystem.prototype.initParticles = function () {
  37493. };
  37494. /**
  37495. * This function does nothing. It may be overwritten to recycle a particle.
  37496. * The SPS doesn't call this function, you may have to call it by your own.
  37497. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  37498. */
  37499. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  37500. return particle;
  37501. };
  37502. /**
  37503. * Updates a particle : this function should be overwritten by the user.
  37504. * It is called on each particle by setParticles(). This is the place to code each particle behavior.
  37505. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  37506. * ex : just set a particle position or velocity and recycle conditions
  37507. */
  37508. SolidParticleSystem.prototype.updateParticle = function (particle) {
  37509. return particle;
  37510. };
  37511. /**
  37512. * Updates a vertex of a particle : it can be overwritten by the user.
  37513. * This will be called on each vertex particle by setParticles() if computeParticleVertex is set to true only.
  37514. * @param particle the current particle
  37515. * @param vertex the current index of the current particle
  37516. * @param pt the index of the current vertex in the particle shape
  37517. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#update-each-particle-shape
  37518. * ex : just set a vertex particle position
  37519. */
  37520. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  37521. return vertex;
  37522. };
  37523. /**
  37524. * This will be called before any other treatment by setParticles() and will be passed three parameters.
  37525. * This does nothing and may be overwritten by the user.
  37526. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  37527. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  37528. * @param update the boolean update value actually passed to setParticles()
  37529. */
  37530. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  37531. };
  37532. /**
  37533. * This will be called by setParticles() after all the other treatments and just before the actual mesh update.
  37534. * This will be passed three parameters.
  37535. * This does nothing and may be overwritten by the user.
  37536. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  37537. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  37538. * @param update the boolean update value actually passed to setParticles()
  37539. */
  37540. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  37541. };
  37542. return SolidParticleSystem;
  37543. })();
  37544. BABYLON.SolidParticleSystem = SolidParticleSystem;
  37545. })(BABYLON || (BABYLON = {}));
  37546. var BABYLON;
  37547. (function (BABYLON) {
  37548. // We're mainly based on the logic defined into the FreeCamera code
  37549. var UniversalCamera = (function (_super) {
  37550. __extends(UniversalCamera, _super);
  37551. function UniversalCamera(name, position, scene) {
  37552. var _this = this;
  37553. _super.call(this, name, position, scene);
  37554. this.gamepadAngularSensibility = 200;
  37555. this.gamepadMoveSensibility = 40;
  37556. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  37557. }
  37558. UniversalCamera.prototype._onNewGameConnected = function (gamepad) {
  37559. // Only the first gamepad can control the camera
  37560. if (gamepad.index === 0) {
  37561. this.gamepad = gamepad;
  37562. }
  37563. };
  37564. UniversalCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  37565. _super.prototype.attachControl.call(this, canvas, false);
  37566. };
  37567. UniversalCamera.prototype.detachControl = function (canvas) {
  37568. _super.prototype.detachControl.call(this, canvas);
  37569. };
  37570. UniversalCamera.prototype._checkInputs = function () {
  37571. if (this.gamepad) {
  37572. var LSValues = this.gamepad.leftStick;
  37573. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  37574. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  37575. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  37576. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  37577. var RSValues = this.gamepad.rightStick;
  37578. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  37579. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  37580. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  37581. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  37582. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  37583. var speed = this._computeLocalCameraSpeed() * 50.0;
  37584. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  37585. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  37586. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  37587. }
  37588. _super.prototype._checkInputs.call(this);
  37589. };
  37590. UniversalCamera.prototype.dispose = function () {
  37591. this._gamepads.dispose();
  37592. _super.prototype.dispose.call(this);
  37593. };
  37594. return UniversalCamera;
  37595. })(BABYLON.TouchCamera);
  37596. BABYLON.UniversalCamera = UniversalCamera;
  37597. })(BABYLON || (BABYLON = {}));
  37598. var BABYLON;
  37599. (function (BABYLON) {
  37600. var Gamepads = (function () {
  37601. function Gamepads(ongamedpadconnected) {
  37602. var _this = this;
  37603. this.babylonGamepads = [];
  37604. this.oneGamepadConnected = false;
  37605. this.isMonitoring = false;
  37606. this.gamepadEventSupported = 'GamepadEvent' in window;
  37607. this.gamepadSupportAvailable = (navigator.getGamepads ||
  37608. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  37609. this._callbackGamepadConnected = ongamedpadconnected;
  37610. if (this.gamepadSupportAvailable) {
  37611. // Checking if the gamepad connected event is supported (like in Firefox)
  37612. if (this.gamepadEventSupported) {
  37613. window.addEventListener('gamepadconnected', function (evt) {
  37614. _this._onGamepadConnected(evt);
  37615. }, false);
  37616. window.addEventListener('gamepaddisconnected', function (evt) {
  37617. _this._onGamepadDisconnected(evt);
  37618. }, false);
  37619. }
  37620. else {
  37621. this._startMonitoringGamepads();
  37622. }
  37623. }
  37624. }
  37625. Gamepads.prototype.dispose = function () {
  37626. if (Gamepads.gamepadDOMInfo) {
  37627. document.body.removeChild(Gamepads.gamepadDOMInfo);
  37628. }
  37629. };
  37630. Gamepads.prototype._onGamepadConnected = function (evt) {
  37631. var newGamepad = this._addNewGamepad(evt.gamepad);
  37632. if (this._callbackGamepadConnected)
  37633. this._callbackGamepadConnected(newGamepad);
  37634. this._startMonitoringGamepads();
  37635. };
  37636. Gamepads.prototype._addNewGamepad = function (gamepad) {
  37637. if (!this.oneGamepadConnected) {
  37638. this.oneGamepadConnected = true;
  37639. if (Gamepads.gamepadDOMInfo) {
  37640. document.body.removeChild(Gamepads.gamepadDOMInfo);
  37641. Gamepads.gamepadDOMInfo = null;
  37642. }
  37643. }
  37644. var newGamepad;
  37645. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  37646. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  37647. }
  37648. else {
  37649. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  37650. }
  37651. this.babylonGamepads.push(newGamepad);
  37652. return newGamepad;
  37653. };
  37654. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  37655. // Remove the gamepad from the list of gamepads to monitor.
  37656. for (var i in this.babylonGamepads) {
  37657. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  37658. this.babylonGamepads.splice(i, 1);
  37659. break;
  37660. }
  37661. }
  37662. // If no gamepads are left, stop the polling loop.
  37663. if (this.babylonGamepads.length == 0) {
  37664. this._stopMonitoringGamepads();
  37665. }
  37666. };
  37667. Gamepads.prototype._startMonitoringGamepads = function () {
  37668. if (!this.isMonitoring) {
  37669. this.isMonitoring = true;
  37670. this._checkGamepadsStatus();
  37671. }
  37672. };
  37673. Gamepads.prototype._stopMonitoringGamepads = function () {
  37674. this.isMonitoring = false;
  37675. };
  37676. Gamepads.prototype._checkGamepadsStatus = function () {
  37677. var _this = this;
  37678. // updating gamepad objects
  37679. this._updateGamepadObjects();
  37680. for (var i in this.babylonGamepads) {
  37681. this.babylonGamepads[i].update();
  37682. }
  37683. if (this.isMonitoring) {
  37684. if (window.requestAnimationFrame) {
  37685. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  37686. }
  37687. else if (window.mozRequestAnimationFrame) {
  37688. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  37689. }
  37690. else if (window.webkitRequestAnimationFrame) {
  37691. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  37692. }
  37693. }
  37694. };
  37695. // This function is called only on Chrome, which does not yet support
  37696. // connection/disconnection events, but requires you to monitor
  37697. // an array for changes.
  37698. Gamepads.prototype._updateGamepadObjects = function () {
  37699. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  37700. for (var i = 0; i < gamepads.length; i++) {
  37701. if (gamepads[i]) {
  37702. if (!(gamepads[i].index in this.babylonGamepads)) {
  37703. var newGamepad = this._addNewGamepad(gamepads[i]);
  37704. if (this._callbackGamepadConnected) {
  37705. this._callbackGamepadConnected(newGamepad);
  37706. }
  37707. }
  37708. else {
  37709. this.babylonGamepads[i].browserGamepad = gamepads[i];
  37710. }
  37711. }
  37712. }
  37713. };
  37714. return Gamepads;
  37715. })();
  37716. BABYLON.Gamepads = Gamepads;
  37717. var StickValues = (function () {
  37718. function StickValues(x, y) {
  37719. this.x = x;
  37720. this.y = y;
  37721. }
  37722. return StickValues;
  37723. })();
  37724. BABYLON.StickValues = StickValues;
  37725. var Gamepad = (function () {
  37726. function Gamepad(id, index, browserGamepad) {
  37727. this.id = id;
  37728. this.index = index;
  37729. this.browserGamepad = browserGamepad;
  37730. if (this.browserGamepad.axes.length >= 2) {
  37731. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  37732. }
  37733. if (this.browserGamepad.axes.length >= 4) {
  37734. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  37735. }
  37736. }
  37737. Gamepad.prototype.onleftstickchanged = function (callback) {
  37738. this._onleftstickchanged = callback;
  37739. };
  37740. Gamepad.prototype.onrightstickchanged = function (callback) {
  37741. this._onrightstickchanged = callback;
  37742. };
  37743. Object.defineProperty(Gamepad.prototype, "leftStick", {
  37744. get: function () {
  37745. return this._leftStick;
  37746. },
  37747. set: function (newValues) {
  37748. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  37749. this._onleftstickchanged(newValues);
  37750. }
  37751. this._leftStick = newValues;
  37752. },
  37753. enumerable: true,
  37754. configurable: true
  37755. });
  37756. Object.defineProperty(Gamepad.prototype, "rightStick", {
  37757. get: function () {
  37758. return this._rightStick;
  37759. },
  37760. set: function (newValues) {
  37761. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  37762. this._onrightstickchanged(newValues);
  37763. }
  37764. this._rightStick = newValues;
  37765. },
  37766. enumerable: true,
  37767. configurable: true
  37768. });
  37769. Gamepad.prototype.update = function () {
  37770. if (this._leftStick) {
  37771. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  37772. }
  37773. if (this._rightStick) {
  37774. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  37775. }
  37776. };
  37777. return Gamepad;
  37778. })();
  37779. BABYLON.Gamepad = Gamepad;
  37780. var GenericPad = (function (_super) {
  37781. __extends(GenericPad, _super);
  37782. function GenericPad(id, index, gamepad) {
  37783. _super.call(this, id, index, gamepad);
  37784. this.id = id;
  37785. this.index = index;
  37786. this.gamepad = gamepad;
  37787. this._buttons = new Array(gamepad.buttons.length);
  37788. }
  37789. GenericPad.prototype.onbuttondown = function (callback) {
  37790. this._onbuttondown = callback;
  37791. };
  37792. GenericPad.prototype.onbuttonup = function (callback) {
  37793. this._onbuttonup = callback;
  37794. };
  37795. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  37796. if (newValue !== currentValue) {
  37797. if (this._onbuttondown && newValue === 1) {
  37798. this._onbuttondown(buttonIndex);
  37799. }
  37800. if (this._onbuttonup && newValue === 0) {
  37801. this._onbuttonup(buttonIndex);
  37802. }
  37803. }
  37804. return newValue;
  37805. };
  37806. GenericPad.prototype.update = function () {
  37807. _super.prototype.update.call(this);
  37808. for (var index = 0; index < this._buttons.length; index++) {
  37809. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  37810. }
  37811. };
  37812. return GenericPad;
  37813. })(Gamepad);
  37814. BABYLON.GenericPad = GenericPad;
  37815. (function (Xbox360Button) {
  37816. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  37817. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  37818. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  37819. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  37820. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  37821. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  37822. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  37823. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  37824. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  37825. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  37826. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  37827. var Xbox360Button = BABYLON.Xbox360Button;
  37828. (function (Xbox360Dpad) {
  37829. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  37830. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  37831. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  37832. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  37833. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  37834. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  37835. var Xbox360Pad = (function (_super) {
  37836. __extends(Xbox360Pad, _super);
  37837. function Xbox360Pad() {
  37838. _super.apply(this, arguments);
  37839. this._leftTrigger = 0;
  37840. this._rightTrigger = 0;
  37841. this._buttonA = 0;
  37842. this._buttonB = 0;
  37843. this._buttonX = 0;
  37844. this._buttonY = 0;
  37845. this._buttonBack = 0;
  37846. this._buttonStart = 0;
  37847. this._buttonLB = 0;
  37848. this._buttonRB = 0;
  37849. this._buttonLeftStick = 0;
  37850. this._buttonRightStick = 0;
  37851. this._dPadUp = 0;
  37852. this._dPadDown = 0;
  37853. this._dPadLeft = 0;
  37854. this._dPadRight = 0;
  37855. }
  37856. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  37857. this._onlefttriggerchanged = callback;
  37858. };
  37859. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  37860. this._onrighttriggerchanged = callback;
  37861. };
  37862. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  37863. get: function () {
  37864. return this._leftTrigger;
  37865. },
  37866. set: function (newValue) {
  37867. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  37868. this._onlefttriggerchanged(newValue);
  37869. }
  37870. this._leftTrigger = newValue;
  37871. },
  37872. enumerable: true,
  37873. configurable: true
  37874. });
  37875. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  37876. get: function () {
  37877. return this._rightTrigger;
  37878. },
  37879. set: function (newValue) {
  37880. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  37881. this._onrighttriggerchanged(newValue);
  37882. }
  37883. this._rightTrigger = newValue;
  37884. },
  37885. enumerable: true,
  37886. configurable: true
  37887. });
  37888. Xbox360Pad.prototype.onbuttondown = function (callback) {
  37889. this._onbuttondown = callback;
  37890. };
  37891. Xbox360Pad.prototype.onbuttonup = function (callback) {
  37892. this._onbuttonup = callback;
  37893. };
  37894. Xbox360Pad.prototype.ondpaddown = function (callback) {
  37895. this._ondpaddown = callback;
  37896. };
  37897. Xbox360Pad.prototype.ondpadup = function (callback) {
  37898. this._ondpadup = callback;
  37899. };
  37900. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  37901. if (newValue !== currentValue) {
  37902. if (this._onbuttondown && newValue === 1) {
  37903. this._onbuttondown(buttonType);
  37904. }
  37905. if (this._onbuttonup && newValue === 0) {
  37906. this._onbuttonup(buttonType);
  37907. }
  37908. }
  37909. return newValue;
  37910. };
  37911. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  37912. if (newValue !== currentValue) {
  37913. if (this._ondpaddown && newValue === 1) {
  37914. this._ondpaddown(buttonType);
  37915. }
  37916. if (this._ondpadup && newValue === 0) {
  37917. this._ondpadup(buttonType);
  37918. }
  37919. }
  37920. return newValue;
  37921. };
  37922. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  37923. get: function () {
  37924. return this._buttonA;
  37925. },
  37926. set: function (value) {
  37927. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  37928. },
  37929. enumerable: true,
  37930. configurable: true
  37931. });
  37932. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  37933. get: function () {
  37934. return this._buttonB;
  37935. },
  37936. set: function (value) {
  37937. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  37938. },
  37939. enumerable: true,
  37940. configurable: true
  37941. });
  37942. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  37943. get: function () {
  37944. return this._buttonX;
  37945. },
  37946. set: function (value) {
  37947. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  37948. },
  37949. enumerable: true,
  37950. configurable: true
  37951. });
  37952. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  37953. get: function () {
  37954. return this._buttonY;
  37955. },
  37956. set: function (value) {
  37957. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  37958. },
  37959. enumerable: true,
  37960. configurable: true
  37961. });
  37962. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  37963. get: function () {
  37964. return this._buttonStart;
  37965. },
  37966. set: function (value) {
  37967. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  37968. },
  37969. enumerable: true,
  37970. configurable: true
  37971. });
  37972. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  37973. get: function () {
  37974. return this._buttonBack;
  37975. },
  37976. set: function (value) {
  37977. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  37978. },
  37979. enumerable: true,
  37980. configurable: true
  37981. });
  37982. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  37983. get: function () {
  37984. return this._buttonLB;
  37985. },
  37986. set: function (value) {
  37987. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  37988. },
  37989. enumerable: true,
  37990. configurable: true
  37991. });
  37992. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  37993. get: function () {
  37994. return this._buttonRB;
  37995. },
  37996. set: function (value) {
  37997. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  37998. },
  37999. enumerable: true,
  38000. configurable: true
  38001. });
  38002. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  38003. get: function () {
  38004. return this._buttonLeftStick;
  38005. },
  38006. set: function (value) {
  38007. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  38008. },
  38009. enumerable: true,
  38010. configurable: true
  38011. });
  38012. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  38013. get: function () {
  38014. return this._buttonRightStick;
  38015. },
  38016. set: function (value) {
  38017. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  38018. },
  38019. enumerable: true,
  38020. configurable: true
  38021. });
  38022. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  38023. get: function () {
  38024. return this._dPadUp;
  38025. },
  38026. set: function (value) {
  38027. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  38028. },
  38029. enumerable: true,
  38030. configurable: true
  38031. });
  38032. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  38033. get: function () {
  38034. return this._dPadDown;
  38035. },
  38036. set: function (value) {
  38037. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  38038. },
  38039. enumerable: true,
  38040. configurable: true
  38041. });
  38042. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  38043. get: function () {
  38044. return this._dPadLeft;
  38045. },
  38046. set: function (value) {
  38047. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  38048. },
  38049. enumerable: true,
  38050. configurable: true
  38051. });
  38052. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  38053. get: function () {
  38054. return this._dPadRight;
  38055. },
  38056. set: function (value) {
  38057. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  38058. },
  38059. enumerable: true,
  38060. configurable: true
  38061. });
  38062. Xbox360Pad.prototype.update = function () {
  38063. _super.prototype.update.call(this);
  38064. this.buttonA = this.browserGamepad.buttons[0].value;
  38065. this.buttonB = this.browserGamepad.buttons[1].value;
  38066. this.buttonX = this.browserGamepad.buttons[2].value;
  38067. this.buttonY = this.browserGamepad.buttons[3].value;
  38068. this.buttonLB = this.browserGamepad.buttons[4].value;
  38069. this.buttonRB = this.browserGamepad.buttons[5].value;
  38070. this.leftTrigger = this.browserGamepad.buttons[6].value;
  38071. this.rightTrigger = this.browserGamepad.buttons[7].value;
  38072. this.buttonBack = this.browserGamepad.buttons[8].value;
  38073. this.buttonStart = this.browserGamepad.buttons[9].value;
  38074. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  38075. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  38076. this.dPadUp = this.browserGamepad.buttons[12].value;
  38077. this.dPadDown = this.browserGamepad.buttons[13].value;
  38078. this.dPadLeft = this.browserGamepad.buttons[14].value;
  38079. this.dPadRight = this.browserGamepad.buttons[15].value;
  38080. };
  38081. return Xbox360Pad;
  38082. })(Gamepad);
  38083. BABYLON.Xbox360Pad = Xbox360Pad;
  38084. })(BABYLON || (BABYLON = {}));
  38085. var BABYLON;
  38086. (function (BABYLON) {
  38087. // We're mainly based on the logic defined into the FreeCamera code
  38088. var GamepadCamera = (function (_super) {
  38089. __extends(GamepadCamera, _super);
  38090. function GamepadCamera(name, position, scene) {
  38091. BABYLON.Tools.Warn("Deprecated. Please use Universal Camera instead.");
  38092. _super.call(this, name, position, scene);
  38093. }
  38094. return GamepadCamera;
  38095. })(BABYLON.UniversalCamera);
  38096. BABYLON.GamepadCamera = GamepadCamera;
  38097. })(BABYLON || (BABYLON = {}));
  38098. var BABYLON;
  38099. (function (BABYLON) {
  38100. var AnaglyphFreeCamera = (function (_super) {
  38101. __extends(AnaglyphFreeCamera, _super);
  38102. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  38103. _super.call(this, name, position, scene);
  38104. this.interaxialDistance = interaxialDistance;
  38105. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  38106. }
  38107. return AnaglyphFreeCamera;
  38108. })(BABYLON.FreeCamera);
  38109. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  38110. var AnaglyphArcRotateCamera = (function (_super) {
  38111. __extends(AnaglyphArcRotateCamera, _super);
  38112. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  38113. _super.call(this, name, alpha, beta, radius, target, scene);
  38114. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  38115. }
  38116. return AnaglyphArcRotateCamera;
  38117. })(BABYLON.ArcRotateCamera);
  38118. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  38119. var AnaglyphGamepadCamera = (function (_super) {
  38120. __extends(AnaglyphGamepadCamera, _super);
  38121. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  38122. _super.call(this, name, position, scene);
  38123. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  38124. }
  38125. return AnaglyphGamepadCamera;
  38126. })(BABYLON.GamepadCamera);
  38127. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  38128. var StereoscopicFreeCamera = (function (_super) {
  38129. __extends(StereoscopicFreeCamera, _super);
  38130. function StereoscopicFreeCamera(name, position, interaxialDistance, isSideBySide, scene) {
  38131. _super.call(this, name, position, scene);
  38132. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  38133. }
  38134. return StereoscopicFreeCamera;
  38135. })(BABYLON.FreeCamera);
  38136. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  38137. var StereoscopicArcRotateCamera = (function (_super) {
  38138. __extends(StereoscopicArcRotateCamera, _super);
  38139. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isSideBySide, scene) {
  38140. _super.call(this, name, alpha, beta, radius, target, scene);
  38141. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  38142. }
  38143. return StereoscopicArcRotateCamera;
  38144. })(BABYLON.ArcRotateCamera);
  38145. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  38146. var StereoscopicGamepadCamera = (function (_super) {
  38147. __extends(StereoscopicGamepadCamera, _super);
  38148. function StereoscopicGamepadCamera(name, position, interaxialDistance, isSideBySide, scene) {
  38149. _super.call(this, name, position, scene);
  38150. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  38151. }
  38152. return StereoscopicGamepadCamera;
  38153. })(BABYLON.GamepadCamera);
  38154. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  38155. })(BABYLON || (BABYLON = {}));
  38156. var BABYLON;
  38157. (function (BABYLON) {
  38158. var Internals;
  38159. (function (Internals) {
  38160. var FileFaceOrientation = (function () {
  38161. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  38162. this.name = name;
  38163. this.worldAxisForNormal = worldAxisForNormal;
  38164. this.worldAxisForFileX = worldAxisForFileX;
  38165. this.worldAxisForFileY = worldAxisForFileY;
  38166. }
  38167. return FileFaceOrientation;
  38168. })();
  38169. ;
  38170. var CubeMapToSphericalPolynomialTools = (function () {
  38171. function CubeMapToSphericalPolynomialTools() {
  38172. }
  38173. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  38174. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  38175. var totalSolidAngle = 0.0;
  38176. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  38177. var du = 2.0 / cubeInfo.size;
  38178. var dv = du;
  38179. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  38180. var minUV = du * 0.5 - 1.0;
  38181. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  38182. var fileFace = this.FileFaces[faceIndex];
  38183. var dataArray = cubeInfo[fileFace.name];
  38184. var v = minUV;
  38185. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  38186. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  38187. // Because SP is still linear, so summation is fine in that basis.
  38188. for (var y = 0; y < cubeInfo.size; y++) {
  38189. var u = minUV;
  38190. for (var x = 0; x < cubeInfo.size; x++) {
  38191. // World direction (not normalised)
  38192. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  38193. worldDirection.normalize();
  38194. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  38195. if (1) {
  38196. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  38197. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  38198. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  38199. var color = new BABYLON.Color3(r, g, b);
  38200. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  38201. }
  38202. else {
  38203. if (faceIndex == 0) {
  38204. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  38205. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  38206. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  38207. }
  38208. else if (faceIndex == 1) {
  38209. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  38210. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  38211. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  38212. }
  38213. else if (faceIndex == 2) {
  38214. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  38215. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  38216. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  38217. }
  38218. else if (faceIndex == 3) {
  38219. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  38220. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  38221. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  38222. }
  38223. else if (faceIndex == 4) {
  38224. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  38225. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  38226. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  38227. }
  38228. else if (faceIndex == 5) {
  38229. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  38230. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  38231. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  38232. }
  38233. var color = new BABYLON.Color3(dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0], dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1], dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2]);
  38234. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  38235. }
  38236. totalSolidAngle += deltaSolidAngle;
  38237. u += du;
  38238. }
  38239. v += dv;
  38240. }
  38241. }
  38242. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  38243. var correction = correctSolidAngle / totalSolidAngle;
  38244. sphericalHarmonics.scale(correction);
  38245. // Additionally scale by pi -- audit needed
  38246. sphericalHarmonics.scale(1.0 / Math.PI);
  38247. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  38248. };
  38249. CubeMapToSphericalPolynomialTools.FileFaces = [
  38250. new FileFaceOrientation("left", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  38251. new FileFaceOrientation("right", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  38252. new FileFaceOrientation("down", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  38253. new FileFaceOrientation("up", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  38254. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  38255. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  38256. ];
  38257. return CubeMapToSphericalPolynomialTools;
  38258. })();
  38259. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  38260. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  38261. })(BABYLON || (BABYLON = {}));
  38262. var BABYLON;
  38263. (function (BABYLON) {
  38264. var Internals;
  38265. (function (Internals) {
  38266. var PanoramaToCubeMapTools = (function () {
  38267. function PanoramaToCubeMapTools() {
  38268. }
  38269. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  38270. if (!float32Array) {
  38271. throw "ConvertPanoramaToCubemap: input cannot be null";
  38272. }
  38273. if (float32Array.length != inputWidth * inputHeight * 3) {
  38274. throw "ConvertPanoramaToCubemap: input size is wrong";
  38275. }
  38276. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  38277. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  38278. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  38279. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  38280. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  38281. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  38282. return {
  38283. front: textureFront,
  38284. back: textureBack,
  38285. left: textureLeft,
  38286. right: textureRight,
  38287. up: textureUp,
  38288. down: textureDown,
  38289. size: size
  38290. };
  38291. };
  38292. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  38293. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  38294. var textureArray = new Float32Array(buffer);
  38295. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  38296. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  38297. var dy = 1 / texSize;
  38298. var fy = 0;
  38299. for (var y = 0; y < texSize; y++) {
  38300. var xv1 = faceData[0];
  38301. var xv2 = faceData[2];
  38302. for (var x = 0; x < texSize; x++) {
  38303. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  38304. v.normalize();
  38305. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  38306. // 3 channels per pixels
  38307. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  38308. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  38309. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  38310. xv1 = xv1.add(rotDX1);
  38311. xv2 = xv2.add(rotDX2);
  38312. }
  38313. fy += dy;
  38314. }
  38315. return textureArray;
  38316. };
  38317. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  38318. var theta = Math.atan2(vDir.z, vDir.x);
  38319. var phi = Math.acos(vDir.y);
  38320. while (theta < -Math.PI)
  38321. theta += 2 * Math.PI;
  38322. while (theta > Math.PI)
  38323. theta -= 2 * Math.PI;
  38324. var dx = theta / Math.PI;
  38325. var dy = phi / Math.PI;
  38326. // recenter.
  38327. dx = dx * 0.5 + 0.5;
  38328. var px = Math.round(dx * inputWidth);
  38329. if (px < 0)
  38330. px = 0;
  38331. else if (px >= inputWidth)
  38332. px = inputWidth - 1;
  38333. var py = Math.round(dy * inputHeight);
  38334. if (py < 0)
  38335. py = 0;
  38336. else if (py >= inputHeight)
  38337. py = inputHeight - 1;
  38338. var inputY = (inputHeight - py - 1);
  38339. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  38340. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  38341. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  38342. return {
  38343. r: r,
  38344. g: g,
  38345. b: b
  38346. };
  38347. };
  38348. PanoramaToCubeMapTools.FACE_FRONT = [
  38349. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  38350. new BABYLON.Vector3(1.0, -1.0, -1.0),
  38351. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  38352. new BABYLON.Vector3(1.0, 1.0, -1.0)
  38353. ];
  38354. PanoramaToCubeMapTools.FACE_BACK = [
  38355. new BABYLON.Vector3(1.0, -1.0, 1.0),
  38356. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  38357. new BABYLON.Vector3(1.0, 1.0, 1.0),
  38358. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  38359. ];
  38360. PanoramaToCubeMapTools.FACE_LEFT = [
  38361. new BABYLON.Vector3(1.0, -1.0, -1.0),
  38362. new BABYLON.Vector3(1.0, -1.0, 1.0),
  38363. new BABYLON.Vector3(1.0, 1.0, -1.0),
  38364. new BABYLON.Vector3(1.0, 1.0, 1.0)
  38365. ];
  38366. PanoramaToCubeMapTools.FACE_RIGHT = [
  38367. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  38368. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  38369. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  38370. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  38371. ];
  38372. PanoramaToCubeMapTools.FACE_UP = [
  38373. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  38374. new BABYLON.Vector3(1.0, 1.0, -1.0),
  38375. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  38376. new BABYLON.Vector3(1.0, 1.0, 1.0)
  38377. ];
  38378. PanoramaToCubeMapTools.FACE_DOWN = [
  38379. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  38380. new BABYLON.Vector3(1.0, -1.0, 1.0),
  38381. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  38382. new BABYLON.Vector3(1.0, -1.0, -1.0)
  38383. ];
  38384. return PanoramaToCubeMapTools;
  38385. })();
  38386. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  38387. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  38388. })(BABYLON || (BABYLON = {}));
  38389. var BABYLON;
  38390. (function (BABYLON) {
  38391. var Internals;
  38392. (function (Internals) {
  38393. ;
  38394. var HDRTools = (function () {
  38395. function HDRTools() {
  38396. }
  38397. HDRTools.Ldexp = function (mantissa, exponent) {
  38398. if (exponent > 1023) {
  38399. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  38400. }
  38401. if (exponent < -1074) {
  38402. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  38403. }
  38404. return mantissa * Math.pow(2, exponent);
  38405. };
  38406. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  38407. if (exponent > 0) {
  38408. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  38409. float32array[index + 0] = red * exponent;
  38410. float32array[index + 1] = green * exponent;
  38411. float32array[index + 2] = blue * exponent;
  38412. }
  38413. else {
  38414. float32array[index + 0] = 0;
  38415. float32array[index + 1] = 0;
  38416. float32array[index + 2] = 0;
  38417. }
  38418. };
  38419. HDRTools.readStringLine = function (uint8array, startIndex) {
  38420. var line = "";
  38421. var character = "";
  38422. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  38423. character = String.fromCharCode(uint8array[i]);
  38424. if (character == "\n") {
  38425. break;
  38426. }
  38427. line += character;
  38428. }
  38429. return line;
  38430. };
  38431. /* minimal header reading. modify if you want to parse more information */
  38432. HDRTools.RGBE_ReadHeader = function (uint8array) {
  38433. var height = 0;
  38434. var width = 0;
  38435. var line = this.readStringLine(uint8array, 0);
  38436. if (line[0] != '#' || line[1] != '?') {
  38437. throw "Bad HDR Format.";
  38438. }
  38439. var endOfHeader = false;
  38440. var findFormat = false;
  38441. var lineIndex = 0;
  38442. do {
  38443. lineIndex += (line.length + 1);
  38444. line = this.readStringLine(uint8array, lineIndex);
  38445. if (line == "FORMAT=32-bit_rle_rgbe") {
  38446. findFormat = true;
  38447. }
  38448. else if (line.length == 0) {
  38449. endOfHeader = true;
  38450. }
  38451. } while (!endOfHeader);
  38452. if (!findFormat) {
  38453. throw "HDR Bad header format, unsupported FORMAT";
  38454. }
  38455. lineIndex += (line.length + 1);
  38456. line = this.readStringLine(uint8array, lineIndex);
  38457. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  38458. var match = sizeRegexp.exec(line);
  38459. // TODO. Support +Y and -X if needed.
  38460. if (match.length < 3) {
  38461. throw "HDR Bad header format, no size";
  38462. }
  38463. width = parseInt(match[2]);
  38464. height = parseInt(match[1]);
  38465. if (width < 8 || width > 0x7fff) {
  38466. throw "HDR Bad header format, unsupported size";
  38467. }
  38468. lineIndex += (line.length + 1);
  38469. return {
  38470. height: height,
  38471. width: width,
  38472. dataPosition: lineIndex
  38473. };
  38474. };
  38475. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  38476. var uint8array = new Uint8Array(buffer);
  38477. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  38478. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  38479. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  38480. return cubeMapData;
  38481. };
  38482. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  38483. // Keep for multi format supports.
  38484. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  38485. };
  38486. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  38487. var num_scanlines = hdrInfo.height;
  38488. var scanline_width = hdrInfo.width;
  38489. var a, b, c, d, count;
  38490. var dataIndex = hdrInfo.dataPosition;
  38491. var index = 0, endIndex = 0, i = 0;
  38492. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  38493. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  38494. // 3 channels of 4 bytes per pixel in float.
  38495. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  38496. var resultArray = new Float32Array(resultBuffer);
  38497. // read in each successive scanline
  38498. while (num_scanlines > 0) {
  38499. a = uint8array[dataIndex++];
  38500. b = uint8array[dataIndex++];
  38501. c = uint8array[dataIndex++];
  38502. d = uint8array[dataIndex++];
  38503. if (a != 2 || b != 2 || (c & 0x80)) {
  38504. // this file is not run length encoded
  38505. throw "HDR Bad header format, not RLE";
  38506. }
  38507. if (((c << 8) | d) != scanline_width) {
  38508. throw "HDR Bad header format, wrong scan line width";
  38509. }
  38510. index = 0;
  38511. // read each of the four channels for the scanline into the buffer
  38512. for (i = 0; i < 4; i++) {
  38513. endIndex = (i + 1) * scanline_width;
  38514. while (index < endIndex) {
  38515. a = uint8array[dataIndex++];
  38516. b = uint8array[dataIndex++];
  38517. if (a > 128) {
  38518. // a run of the same value
  38519. count = a - 128;
  38520. if ((count == 0) || (count > endIndex - index)) {
  38521. throw "HDR Bad Format, bad scanline data (run)";
  38522. }
  38523. while (count-- > 0) {
  38524. scanLineArray[index++] = b;
  38525. }
  38526. }
  38527. else {
  38528. // a non-run
  38529. count = a;
  38530. if ((count == 0) || (count > endIndex - index)) {
  38531. throw "HDR Bad Format, bad scanline data (non-run)";
  38532. }
  38533. scanLineArray[index++] = b;
  38534. if (--count > 0) {
  38535. for (var j = 0; j < count; j++) {
  38536. scanLineArray[index++] = uint8array[dataIndex++];
  38537. }
  38538. }
  38539. }
  38540. }
  38541. }
  38542. // now convert data from buffer into floats
  38543. for (i = 0; i < scanline_width; i++) {
  38544. a = scanLineArray[i];
  38545. b = scanLineArray[i + scanline_width];
  38546. c = scanLineArray[i + 2 * scanline_width];
  38547. d = scanLineArray[i + 3 * scanline_width];
  38548. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  38549. }
  38550. num_scanlines--;
  38551. }
  38552. return resultArray;
  38553. };
  38554. return HDRTools;
  38555. })();
  38556. Internals.HDRTools = HDRTools;
  38557. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  38558. })(BABYLON || (BABYLON = {}));
  38559. var BABYLON;
  38560. (function (BABYLON) {
  38561. var HDRCubeTexture = (function (_super) {
  38562. __extends(HDRCubeTexture, _super);
  38563. function HDRCubeTexture(url, scene, size, noMipmap) {
  38564. _super.call(this, scene);
  38565. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  38566. this.sphericalPolynomial = null;
  38567. this.name = url;
  38568. this.url = url;
  38569. this._noMipmap = noMipmap;
  38570. this.hasAlpha = false;
  38571. this._size = size;
  38572. if (!url) {
  38573. return;
  38574. }
  38575. this._texture = this._getFromCache(url, noMipmap);
  38576. if (!this._texture) {
  38577. if (!scene.useDelayedTextureLoading) {
  38578. this.loadTexture();
  38579. }
  38580. else {
  38581. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  38582. }
  38583. }
  38584. this.isCube = true;
  38585. this._textureMatrix = BABYLON.Matrix.Identity();
  38586. }
  38587. HDRCubeTexture.prototype.loadTexture = function () {
  38588. var _this = this;
  38589. var callback = function (buffer) {
  38590. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  38591. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  38592. var mapping = [
  38593. "left",
  38594. "down",
  38595. "front",
  38596. "right",
  38597. "up",
  38598. "back"
  38599. ];
  38600. var results = [];
  38601. for (var j = 0; j < 6; j++) {
  38602. var dataFace = data[mapping[j]];
  38603. // TODO. Support Int Textures...
  38604. // // 3 channels of 1 bytes per pixel in bytes.
  38605. // var byteBuffer = new ArrayBuffer(this._size * this._size * 3);
  38606. // var byteArray = new Uint8Array(byteBuffer);
  38607. //
  38608. // /* now convert data from buffer into bytes */
  38609. // for(var i = 0; i < this._size * this._size; i++) {
  38610. // byteArray[(i * 3) + 0] = dataFace[(i * 3) + 0] * 255;
  38611. // byteArray[(i * 3) + 1] = dataFace[(i * 3) + 1] * 255;
  38612. // byteArray[(i * 3) + 2] = dataFace[(i * 3) + 2] * 255;
  38613. // }
  38614. results.push(dataFace);
  38615. }
  38616. return results;
  38617. };
  38618. this._texture = this.getScene().getEngine().createRawCubeTexture(this.url, this.getScene(), this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, BABYLON.Engine.TEXTURETYPE_FLOAT, this._noMipmap, callback);
  38619. };
  38620. HDRCubeTexture.prototype.clone = function () {
  38621. var newTexture = new HDRCubeTexture(this.url, this.getScene(), this._size, this._noMipmap);
  38622. // Base texture
  38623. newTexture.level = this.level;
  38624. newTexture.wrapU = this.wrapU;
  38625. newTexture.wrapV = this.wrapV;
  38626. newTexture.coordinatesIndex = this.coordinatesIndex;
  38627. newTexture.coordinatesMode = this.coordinatesMode;
  38628. return newTexture;
  38629. };
  38630. // Methods
  38631. HDRCubeTexture.prototype.delayLoad = function () {
  38632. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  38633. return;
  38634. }
  38635. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  38636. this._texture = this._getFromCache(this.url, this._noMipmap);
  38637. if (!this._texture) {
  38638. this.loadTexture();
  38639. }
  38640. };
  38641. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  38642. return this._textureMatrix;
  38643. };
  38644. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  38645. var texture = null;
  38646. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  38647. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size);
  38648. texture.name = parsedTexture.name;
  38649. texture.hasAlpha = parsedTexture.hasAlpha;
  38650. texture.level = parsedTexture.level;
  38651. texture.coordinatesMode = parsedTexture.coordinatesMode;
  38652. }
  38653. return texture;
  38654. };
  38655. HDRCubeTexture.prototype.serialize = function () {
  38656. if (!this.name) {
  38657. return null;
  38658. }
  38659. var serializationObject = {};
  38660. serializationObject.name = this.name;
  38661. serializationObject.hasAlpha = this.hasAlpha;
  38662. serializationObject.isCube = true;
  38663. serializationObject.level = this.level;
  38664. serializationObject.size = this._size;
  38665. serializationObject.coordinatesMode = this.coordinatesMode;
  38666. return serializationObject;
  38667. };
  38668. return HDRCubeTexture;
  38669. })(BABYLON.BaseTexture);
  38670. BABYLON.HDRCubeTexture = HDRCubeTexture;
  38671. })(BABYLON || (BABYLON = {}));
  38672. BABYLON.Effect.ShadersStore={"anaglyphPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D leftSampler;\r\n\r\nvoid main(void)\r\n{\r\n vec4 leftFrag = texture2D(leftSampler, vUV);\r\n leftFrag = vec4(1.0, leftFrag.g, leftFrag.b, 1.0);\r\n\r\n\tvec4 rightFrag = texture2D(textureSampler, vUV);\r\n rightFrag = vec4(rightFrag.r, 1.0, 1.0, 1.0);\r\n\r\n gl_FragColor = vec4(rightFrag.rgb * leftFrag.rgb, 1.0);\r\n}","blackAndWhitePixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nvoid main(void) \r\n{\r\n\tfloat luminance = dot(texture2D(textureSampler, vUV).rgb, vec3(0.3, 0.59, 0.11));\r\n\tgl_FragColor = vec4(luminance, luminance, luminance, 1.0);\r\n}","blurPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Parameters\r\nuniform vec2 screenSize;\r\nuniform vec2 direction;\r\nuniform float blurWidth;\r\n\r\nvoid main(void)\r\n{\r\n\tfloat weights[7];\r\n\tweights[0] = 0.05;\r\n\tweights[1] = 0.1;\r\n\tweights[2] = 0.2;\r\n\tweights[3] = 0.3;\r\n\tweights[4] = 0.2;\r\n\tweights[5] = 0.1;\r\n\tweights[6] = 0.05;\r\n\r\n\tvec2 texelSize = vec2(1.0 / screenSize.x, 1.0 / screenSize.y);\r\n\tvec2 texelStep = texelSize * direction * blurWidth;\r\n\tvec2 start = vUV - 3.0 * texelStep;\r\n\r\n\tvec4 baseColor = vec4(0., 0., 0., 0.);\r\n\tvec2 texelOffset = vec2(0., 0.);\r\n\r\n\tfor (int i = 0; i < 7; i++)\r\n\t{\r\n\t\tbaseColor += texture2D(textureSampler, start + texelOffset) * weights[i];\r\n\t\ttexelOffset += texelStep;\r\n\t}\r\n\r\n\tgl_FragColor = baseColor;\r\n}","chromaticAberrationPixelShader":"precision highp float;\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\t// original color\r\n\r\n// uniforms\r\nuniform float chromatic_aberration;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 centered_screen_pos = vec2(vUV.x - 0.5, vUV.y - 0.5);\r\n\tfloat radius2 = centered_screen_pos.x*centered_screen_pos.x\r\n\t\t+ centered_screen_pos.y*centered_screen_pos.y;\r\n\tfloat radius = sqrt(radius2);\r\n\r\n\tvec4 original = texture2D(textureSampler, vUV);\r\n\r\n\tif (chromatic_aberration > 0.0) {\r\n\t\t//index of refraction of each color channel, causing chromatic dispersion\r\n\t\tvec3 ref_indices = vec3(-0.3, 0.0, 0.3);\r\n\t\tfloat ref_shiftX = chromatic_aberration * radius * 17.0 / screen_width;\r\n\t\tfloat ref_shiftY = chromatic_aberration * radius * 17.0 / screen_height;\r\n\r\n\t\t// shifts for red, green & blue\r\n\t\tvec2 ref_coords_r = vec2(vUV.x + ref_indices.r*ref_shiftX, vUV.y + ref_indices.r*ref_shiftY*0.5);\r\n\t\tvec2 ref_coords_g = vec2(vUV.x + ref_indices.g*ref_shiftX, vUV.y + ref_indices.g*ref_shiftY*0.5);\r\n\t\tvec2 ref_coords_b = vec2(vUV.x + ref_indices.b*ref_shiftX, vUV.y + ref_indices.b*ref_shiftY*0.5);\r\n\r\n\t\toriginal.r = texture2D(textureSampler, ref_coords_r).r;\r\n\t\toriginal.g = texture2D(textureSampler, ref_coords_g).g;\r\n\t\toriginal.b = texture2D(textureSampler, ref_coords_b).b;\r\n\t}\r\n\r\n\tgl_FragColor = original;\r\n}","colorPixelShader":"precision highp float;\r\n\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tgl_FragColor = color;\r\n}","colorVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\n\r\n// Uniforms\r\nuniform mat4 worldViewProjection;\r\n\r\nvoid main(void) {\r\n\tgl_Position = worldViewProjection * vec4(position, 1.0);\r\n}","colorCorrectionPixelShader":"precision highp float;\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\t// screen render\r\nuniform sampler2D colorTable;\t\t// color table with modified colors\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// constants\r\nconst float SLICE_COUNT = 16.0;\t\t// how many slices in the color cube; 1 slice = 1 pixel\r\n// it means the image is 256x16 pixels\r\n\r\nvec4 sampleAs3DTexture(sampler2D texture, vec3 uv, float width) {\r\n\tfloat sliceSize = 1.0 / width; // space of 1 slice\r\n\tfloat slicePixelSize = sliceSize / width; // space of 1 pixel\r\n\tfloat sliceInnerSize = slicePixelSize * (width - 1.0); // space of width pixels\r\n\tfloat zSlice0 = min(floor(uv.z * width), width - 1.0);\r\n\tfloat zSlice1 = min(zSlice0 + 1.0, width - 1.0);\r\n\tfloat xOffset = slicePixelSize * 0.5 + uv.x * sliceInnerSize;\r\n\tfloat s0 = xOffset + (zSlice0 * sliceSize);\r\n\tfloat s1 = xOffset + (zSlice1 * sliceSize);\r\n\tvec4 slice0Color = texture2D(texture, vec2(s0, uv.y));\r\n\tvec4 slice1Color = texture2D(texture, vec2(s1, uv.y));\r\n\tfloat zOffset = mod(uv.z * width, 1.0);\r\n\tvec4 result = mix(slice0Color, slice1Color, zOffset);\r\n\treturn result;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 screen_color = texture2D(textureSampler, vUV);\r\n\tgl_FragColor = sampleAs3DTexture(colorTable, screen_color.rgb, SLICE_COUNT);\r\n\r\n}","convolutionPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nuniform vec2 screenSize;\r\nuniform float kernel[9];\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 onePixel = vec2(1.0, 1.0) / screenSize;\r\n\tvec4 colorSum =\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, -1)) * kernel[0] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, -1)) * kernel[1] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, -1)) * kernel[2] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, 0)) * kernel[3] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, 0)) * kernel[4] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, 0)) * kernel[5] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, 1)) * kernel[6] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, 1)) * kernel[7] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, 1)) * kernel[8];\r\n\r\n\tfloat kernelWeight =\r\n\t\tkernel[0] +\r\n\t\tkernel[1] +\r\n\t\tkernel[2] +\r\n\t\tkernel[3] +\r\n\t\tkernel[4] +\r\n\t\tkernel[5] +\r\n\t\tkernel[6] +\r\n\t\tkernel[7] +\r\n\t\tkernel[8];\r\n\r\n\tif (kernelWeight <= 0.0) {\r\n\t\tkernelWeight = 1.0;\r\n\t}\r\n\r\n\tgl_FragColor = vec4((colorSum / kernelWeight).rgb, 1);\r\n}","defaultPixelShader":"#ifdef BUMP\r\n#extension GL_OES_standard_derivatives : enable\r\n#endif\r\n\r\n#ifdef LOGARITHMICDEPTH\r\n#extension GL_EXT_frag_depth : enable\r\n#endif\r\n\r\nprecision highp float;\r\n\r\n// Constants\r\n#define RECIPROCAL_PI2 0.15915494\r\n\r\nuniform vec3 vEyePosition;\r\nuniform vec3 vAmbientColor;\r\nuniform vec4 vDiffuseColor;\r\n#ifdef SPECULARTERM\r\nuniform vec4 vSpecularColor;\r\n#endif\r\nuniform vec3 vEmissiveColor;\r\n\r\n// Input\r\nvarying vec3 vPositionW;\r\n\r\n#ifdef NORMAL\r\nvarying vec3 vNormalW;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n// Lights\r\n#include<light0FragmentDeclaration>\r\n#include<light1FragmentDeclaration>\r\n#include<light2FragmentDeclaration>\r\n#include<light3FragmentDeclaration>\r\n\r\n#include<lightsFragmentFunctions>\r\n#include<shadowsFragmentFunctions>\r\n\r\n// Samplers\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform sampler2D diffuseSampler;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform sampler2D ambientSampler;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\t\r\nvarying vec2 vOpacityUV;\r\nuniform sampler2D opacitySampler;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform sampler2D emissiveSampler;\r\n#endif\r\n\r\n#ifdef LIGHTMAP\r\nvarying vec2 vLightmapUV;\r\nuniform vec2 vLightmapInfos;\r\nuniform sampler2D lightmapSampler;\r\n#endif\r\n\r\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\r\nuniform mat4 view;\r\n#endif\r\n\r\n#ifdef REFRACTION\r\nuniform vec4 vRefractionInfos;\r\n\r\n#ifdef REFRACTIONMAP_3D\r\nuniform samplerCube refractionCubeSampler;\r\n#else\r\nuniform sampler2D refraction2DSampler;\r\nuniform mat4 refractionMatrix;\r\n#endif\r\n\r\n#ifdef REFRACTIONFRESNEL\r\nuniform vec4 refractionLeftColor;\r\nuniform vec4 refractionRightColor;\r\n#endif\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform sampler2D specularSampler;\r\n#endif\r\n\r\n// Fresnel\r\n#ifdef FRESNEL\r\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\r\n{\r\n\tfloat fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\r\n\treturn clamp(fresnelTerm, 0., 1.);\r\n}\r\n#endif\r\n\r\n#ifdef DIFFUSEFRESNEL\r\nuniform vec4 diffuseLeftColor;\r\nuniform vec4 diffuseRightColor;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\nuniform vec4 opacityParts;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\nuniform vec4 emissiveLeftColor;\r\nuniform vec4 emissiveRightColor;\r\n#endif\r\n\r\n// Reflection\r\n#ifdef REFLECTION\r\nuniform vec2 vReflectionInfos;\r\n\r\n#ifdef REFLECTIONMAP_3D\r\nuniform samplerCube reflectionCubeSampler;\r\n#else\r\nuniform sampler2D reflection2DSampler;\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_SKYBOX\r\nvarying vec3 vPositionUVW;\r\n#else\r\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\r\nvarying vec3 vDirectionW;\r\n#endif\r\n\r\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\r\nuniform mat4 reflectionMatrix;\r\n#endif\r\n#endif\r\n\r\nvec3 computeReflectionCoords(vec4 worldPos, vec3 worldNormal)\r\n{\r\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\r\n\tvec3 direction = normalize(vDirectionW);\r\n\r\n\tfloat t = clamp(direction.y * -0.5 + 0.5, 0., 1.0);\r\n\tfloat s = atan(direction.z, direction.x) * RECIPROCAL_PI2 + 0.5;\r\n\r\n\treturn vec3(s, t, 0);\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\r\n\r\n\tvec3 cameraToVertex = normalize(worldPos.xyz - vEyePosition);\r\n\tvec3 r = reflect(cameraToVertex, worldNormal);\r\n\tfloat t = clamp(r.y * -0.5 + 0.5, 0., 1.0);\r\n\tfloat s = atan(r.z, r.x) * RECIPROCAL_PI2 + 0.5;\r\n\r\n\treturn vec3(s, t, 0);\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_SPHERICAL\r\n\tvec3 viewDir = normalize(vec3(view * worldPos));\r\n\tvec3 viewNormal = normalize(vec3(view * vec4(worldNormal, 0.0)));\r\n\r\n\tvec3 r = reflect(viewDir, viewNormal);\r\n\tr.z = r.z - 1.0;\r\n\r\n\tfloat m = 2.0 * length(r);\r\n\r\n\treturn vec3(r.x / m + 0.5, 1.0 - r.y / m - 0.5, 0);\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_PLANAR\r\n\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\tvec3 coords = normalize(reflect(viewDir, worldNormal));\r\n\r\n\treturn vec3(reflectionMatrix * vec4(coords, 1));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_CUBIC\r\n\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\tvec3 coords = reflect(viewDir, worldNormal);\r\n#ifdef INVERTCUBICMAP\r\n\tcoords.y = 1.0 - coords.y;\r\n#endif\r\n\treturn vec3(reflectionMatrix * vec4(coords, 0));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_PROJECTION\r\n\treturn vec3(reflectionMatrix * (view * worldPos));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_SKYBOX\r\n\treturn vPositionUVW;\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_EXPLICIT\r\n\treturn vec3(0, 0, 0);\r\n#endif\r\n}\r\n\r\n#ifdef REFLECTIONFRESNEL\r\nuniform vec4 reflectionLeftColor;\r\nuniform vec4 reflectionRightColor;\r\n#endif\r\n\r\n#endif\r\n\r\n// Bump\r\n#ifdef BUMP\r\nvarying vec2 vBumpUV;\r\nuniform vec2 vBumpInfos;\r\nuniform sampler2D bumpSampler;\r\n\r\n// Thanks to http://www.thetenthplanet.de/archives/1180\r\nmat3 cotangent_frame(vec3 normal, vec3 p, vec2 uv)\r\n{\r\n\t// get edge vectors of the pixel triangle\r\n\tvec3 dp1 = dFdx(p);\r\n\tvec3 dp2 = dFdy(p);\r\n\tvec2 duv1 = dFdx(uv);\r\n\tvec2 duv2 = dFdy(uv);\r\n\r\n\t// solve the linear system\r\n\tvec3 dp2perp = cross(dp2, normal);\r\n\tvec3 dp1perp = cross(normal, dp1);\r\n\tvec3 tangent = dp2perp * duv1.x + dp1perp * duv2.x;\r\n\tvec3 binormal = dp2perp * duv1.y + dp1perp * duv2.y;\r\n\r\n\t// construct a scale-invariant frame \r\n\tfloat invmax = inversesqrt(max(dot(tangent, tangent), dot(binormal, binormal)));\r\n\treturn mat3(tangent * invmax, binormal * invmax, normal);\r\n}\r\n\r\nvec3 perturbNormal(vec3 viewDir)\r\n{\r\n\tvec3 map = texture2D(bumpSampler, vBumpUV).xyz;\r\n\tmap = map * 255. / 127. - 128. / 127.;\r\n\tmat3 TBN = cotangent_frame(vNormalW * vBumpInfos.y, -viewDir, vBumpUV);\r\n\treturn normalize(TBN * map);\r\n}\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n#ifdef LOGARITHMICDEPTH\r\nuniform float logarithmicDepthConstant;\r\nvarying float vFragmentDepth;\r\n#endif\r\n\r\n#include<fogFragmentDeclaration>\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\t// Specular map\r\n#ifdef SPECULARTERM\r\n\tfloat glossiness = vSpecularColor.a;\r\n\tvec3 specularColor = vSpecularColor.rgb;\r\n\r\n#ifdef SPECULAR\r\n\tvec4 specularMapColor = texture2D(specularSampler, vSpecularUV);\r\n\tspecularColor = specularMapColor.rgb;\r\n#ifdef GLOSSINESS\r\n\tglossiness = glossiness * specularMapColor.a;\r\n#endif\r\n#endif\r\n#else\r\n\tfloat glossiness = 0.;\r\n#endif\r\n\r\n\t// Lighting\r\n\tvec3 diffuseBase = vec3(0., 0., 0.);\r\n#ifdef SPECULARTERM\r\n\tvec3 specularBase = vec3(0., 0., 0.);\r\n#endif\r\n\tfloat shadow = 1.;\r\n\r\n#include<light0Fragment>\r\n#include<light1Fragment>\r\n#include<light2Fragment>\r\n#include<light3Fragment>\r\n\r\n\t// Refraction\r\n\tvec3 refractionColor = vec3(0., 0., 0.);\r\n\r\n#ifdef REFRACTION\r\n\tvec3 refractionVector = normalize(refract(-viewDirectionW, normalW, vRefractionInfos.y));\r\n#ifdef REFRACTIONMAP_3D\r\n\r\n\trefractionVector.y = refractionVector.y * vRefractionInfos.w;\r\n\r\n\tif (dot(refractionVector, viewDirectionW) < 1.0)\r\n\t{\r\n\t\trefractionColor = textureCube(refractionCubeSampler, refractionVector).rgb * vRefractionInfos.x;\r\n\t}\r\n#else\r\n\tvec3 vRefractionUVW = vec3(refractionMatrix * (view * vec4(vPositionW + refractionVector * vRefractionInfos.z, 1.0)));\r\n\r\n\tvec2 refractionCoords = vRefractionUVW.xy / vRefractionUVW.z;\r\n\r\n\trefractionCoords.y = 1.0 - refractionCoords.y;\r\n\r\n\trefractionColor = texture2D(refraction2DSampler, refractionCoords).rgb * vRefractionInfos.x;\r\n#endif\r\n#endif\r\n\r\n\t// Reflection\r\n\tvec3 reflectionColor = vec3(0., 0., 0.);\r\n\r\n#ifdef REFLECTION\r\n\tvec3 vReflectionUVW = computeReflectionCoords(vec4(vPositionW, 1.0), normalW);\r\n\r\n#ifdef REFLECTIONMAP_3D\r\n#ifdef ROUGHNESS\r\n\t float bias = vReflectionInfos.y;\r\n\r\n\t#ifdef SPECULARTERM\r\n\t#ifdef SPECULAR\r\n\t#ifdef GLOSSINESS\r\n\t\tbias *= (1.0 - specularMapColor.a);\r\n\t#endif\r\n\t#endif\r\n\t#endif\r\n\r\n\treflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW, bias).rgb * vReflectionInfos.x;\r\n#else\r\n\treflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.x;\r\n#endif\r\n\r\n#else\r\n\tvec2 coords = vReflectionUVW.xy;\r\n\r\n#ifdef REFLECTIONMAP_PROJECTION\r\n\tcoords /= vReflectionUVW.z;\r\n#endif\r\n\r\n\tcoords.y = 1.0 - coords.y;\r\n\r\n\treflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.x;\r\n#endif\r\n\r\n#ifdef REFLECTIONFRESNEL\r\n\tfloat reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\r\n\r\n#ifdef REFLECTIONFRESNELFROMSPECULAR\r\n#ifdef SPECULARTERM\r\n\treflectionColor *= specularColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#else\r\n\treflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#endif\r\n#else\r\n\treflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#endif\r\n#endif\r\n#endif\r\n\r\n#ifdef REFRACTIONFRESNEL\r\n\tfloat refractionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, refractionRightColor.a, refractionLeftColor.a);\r\n\r\n\trefractionColor *= refractionLeftColor.rgb * (1.0 - refractionFresnelTerm) + refractionFresnelTerm * refractionRightColor.rgb;\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\r\n\r\n#ifdef OPACITYRGB\r\n\topacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\r\n#else\r\n\talpha *= opacityMap.a * vOpacityInfos.y;\r\n#endif\r\n\r\n#endif\r\n\r\n#ifdef VERTEXALPHA\r\n\talpha *= vColor.a;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\n\tfloat opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\r\n\r\n\talpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\r\n#endif\r\n\r\n\t// Emissive\r\n\tvec3 emissiveColor = vEmissiveColor;\r\n#ifdef EMISSIVE\r\n\temissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\n\tfloat emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\r\n\r\n\temissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\r\n#endif\r\n\r\n\t// Fresnel\r\n#ifdef DIFFUSEFRESNEL\r\n\tfloat diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\r\n\r\n\tdiffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\r\n#endif\r\n\r\n\t// Composition\r\n#ifdef EMISSIVEASILLUMINATION\r\n\tvec3 finalDiffuse = clamp(diffuseBase * diffuseColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n#else\r\n#ifdef LINKEMISSIVEWITHDIFFUSE\r\n\tvec3 finalDiffuse = clamp((diffuseBase + emissiveColor) * diffuseColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n#else\r\n\tvec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n#endif\r\n#endif\r\n\r\n#ifdef SPECULARTERM\r\n\tvec3 finalSpecular = specularBase * specularColor;\r\n#else\r\n\tvec3 finalSpecular = vec3(0.0);\r\n#endif\r\n\r\n#ifdef SPECULAROVERALPHA\r\n\talpha = clamp(alpha + dot(finalSpecular, vec3(0.3, 0.59, 0.11)), 0., 1.);\r\n#endif\r\n\r\n\t// Composition\r\n#ifdef EMISSIVEASILLUMINATION\r\n\tvec4 color = vec4(clamp(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor + emissiveColor + refractionColor, 0.0, 1.0), alpha);\r\n#else\r\n\tvec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor + refractionColor, alpha);\r\n#endif\r\n\r\n#ifdef LIGHTMAP\r\n\tvec3 lightmapColor = texture2D(lightmapSampler, vLightmapUV).rgb * vLightmapInfos.y;\r\n\r\n#ifdef USELIGHTMAPASSHADOWMAP\r\n\tcolor.rgb *= lightmapColor;\r\n#else\r\n\tcolor.rgb += lightmapColor;\r\n#endif\r\n#endif\r\n\r\n#ifdef LOGARITHMICDEPTH\r\n\tgl_FragDepthEXT = log2(vFragmentDepth) * logarithmicDepthConstant * 0.5;\r\n#endif\r\n\r\n#include<fogFragment>\r\n\r\n\tgl_FragColor = color;\r\n}","defaultVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\n#ifdef NORMAL\r\nattribute vec3 normal;\r\n#endif\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#ifdef VERTEXCOLOR\r\nattribute vec4 color;\r\n#endif\r\n\r\n#include<bonesDeclaration>\r\n\r\n// Uniforms\r\n#include<instancesDeclaration>\r\n\r\nuniform mat4 view;\r\nuniform mat4 viewProjection;\r\n\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform mat4 diffuseMatrix;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform mat4 ambientMatrix;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\r\nvarying vec2 vOpacityUV;\r\nuniform mat4 opacityMatrix;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform mat4 emissiveMatrix;\r\n#endif\r\n\r\n#ifdef LIGHTMAP\r\nvarying vec2 vLightmapUV;\r\nuniform vec2 vLightmapInfos;\r\nuniform mat4 lightmapMatrix;\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform mat4 specularMatrix;\r\n#endif\r\n\r\n#ifdef BUMP\r\nvarying vec2 vBumpUV;\r\nuniform vec2 vBumpInfos;\r\nuniform mat4 bumpMatrix;\r\n#endif\r\n\r\n#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#include<fogVertexDeclaration>\r\n#include<shadowsVertexDeclaration>\r\n\r\n#ifdef REFLECTIONMAP_SKYBOX\r\nvarying vec3 vPositionUVW;\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\r\nvarying vec3 vDirectionW;\r\n#endif\r\n\r\n#ifdef LOGARITHMICDEPTH\r\nuniform float logarithmicDepthConstant;\r\nvarying float vFragmentDepth;\r\n#endif\r\n\r\nvoid main(void) {\r\n#ifdef REFLECTIONMAP_SKYBOX\r\n\tvPositionUVW = position;\r\n#endif \r\n\r\n#include<instancesVertex>\r\n#include<bonesVertex>\r\n\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n\r\n\tvec4 worldPos = finalWorld * vec4(position, 1.0);\r\n\tvPositionW = vec3(worldPos);\r\n\r\n#ifdef NORMAL\r\n\tvNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\r\n\tvDirectionW = normalize(vec3(finalWorld * vec4(position, 0.0)));\r\n#endif\r\n\r\n\t// Texture coordinates\r\n#ifndef UV1\r\n\tvec2 uv = vec2(0., 0.);\r\n#endif\r\n#ifndef UV2\r\n\tvec2 uv2 = vec2(0., 0.);\r\n#endif\r\n\r\n#ifdef DIFFUSE\r\n\tif (vDiffuseInfos.x == 0.)\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef AMBIENT\r\n\tif (vAmbientInfos.x == 0.)\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tif (vOpacityInfos.x == 0.)\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\n\tif (vEmissiveInfos.x == 0.)\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef LIGHTMAP\r\n\tif (vLightmapInfos.x == 0.)\r\n\t{\r\n\t\tvLightmapUV = vec2(lightmapMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvLightmapUV = vec2(lightmapMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\n\tif (vSpecularInfos.x == 0.)\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef BUMP\r\n\tif (vBumpInfos.x == 0.)\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n\r\n#include<fogVertex>\r\n#include<shadowsVertex>\r\n\r\n\t// Vertex color\r\n#ifdef VERTEXCOLOR\r\n\tvColor = color;\r\n#endif\r\n\r\n\t// Point size\r\n#ifdef POINTSIZE\r\n\tgl_PointSize = pointSize;\r\n#endif\r\n\r\n\t// Log. depth\r\n#ifdef LOGARITHMICDEPTH\r\n\tvFragmentDepth = 1.0 + gl_Position.w;\r\n\tgl_Position.z = log2(max(0.000001, vFragmentDepth)) * logarithmicDepthConstant;\r\n#endif\r\n}","depthPixelShader":"precision highp float;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\nuniform float far;\r\n\r\nvoid main(void)\r\n{\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tfloat depth = (gl_FragCoord.z / gl_FragCoord.w) / far;\r\n\tgl_FragColor = vec4(depth, depth * depth, 0.0, 1.0);\r\n}","depthVertexShader":"precision highp float;\r\n\r\n// Attribute\r\nattribute vec3 position;\r\n#include<bonesDeclaration>\r\n\r\n// Uniform\r\n#include<instancesDeclaration>\r\n\r\nuniform mat4 viewProjection;\r\n\r\n#if defined(ALPHATEST) || defined(NEED_UV)\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#include<instancesVertex>\r\n\r\n#include<bonesVertex>\r\n\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}","depthBoxBlurPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Parameters\r\nuniform vec2 screenSize;\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 colorDepth = vec4(0.0);\r\n\r\n\tfor (int x = -OFFSET; x <= OFFSET; x++)\r\n\t\tfor (int y = -OFFSET; y <= OFFSET; y++)\r\n\t\t\tcolorDepth += texture2D(textureSampler, vUV + vec2(x, y) / screenSize);\r\n\r\n\tgl_FragColor = (colorDepth / float((OFFSET * 2 + 1) * (OFFSET * 2 + 1)));\r\n}","depthOfFieldPixelShader":"// BABYLON.JS Depth-of-field GLSL Shader\r\n// Author: Olivier Guyot\r\n// Does depth-of-field blur, edge blur\r\n// Inspired by Francois Tarlier & Martins Upitis\r\n\r\nprecision highp float;\r\n\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D highlightsSampler;\r\nuniform sampler2D depthSampler;\r\nuniform sampler2D grainSampler;\r\n\r\n// uniforms\r\nuniform float grain_amount;\r\nuniform bool blur_noise;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\nuniform float distortion;\r\nuniform bool dof_enabled;\r\n//uniform float focus_distance;\t\t// not needed; already used to compute screen distance\r\nuniform float screen_distance;\t\t// precomputed screen distance from lens center; based on focal length & desired focus distance\r\nuniform float aperture;\r\nuniform float darken;\r\nuniform float edge_blur;\r\nuniform bool highlights;\r\n\r\n// preconputed uniforms (not effect parameters)\r\nuniform float near;\r\nuniform float far;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// constants\r\n#define PI \t\t3.14159265\r\n#define TWOPI \t6.28318530\r\n#define inverse_focal_length 0.1\t// a property of the lens used\r\n\r\n// common calculations\r\nvec2 centered_screen_pos;\r\nvec2 distorted_coords;\r\nfloat radius2;\r\nfloat radius;\r\n\r\n\r\n// on-the-fly constant noise\r\nvec2 rand(vec2 co)\r\n{\r\n\tfloat noise1 = (fract(sin(dot(co, vec2(12.9898, 78.233))) * 43758.5453));\r\n\tfloat noise2 = (fract(sin(dot(co, vec2(12.9898, 78.233)*2.0)) * 43758.5453));\r\n\treturn clamp(vec2(noise1, noise2), 0.0, 1.0);\r\n}\r\n\r\n// applies edge distortion on texture coords\r\nvec2 getDistortedCoords(vec2 coords) {\r\n\r\n\tif (distortion == 0.0) { return coords; }\r\n\r\n\tvec2 direction = 1.0 * normalize(centered_screen_pos);\r\n\tvec2 dist_coords = vec2(0.5, 0.5);\r\n\tdist_coords.x = 0.5 + direction.x * radius2 * 1.0;\r\n\tdist_coords.y = 0.5 + direction.y * radius2 * 1.0;\r\n\tfloat dist_amount = clamp(distortion*0.23, 0.0, 1.0);\r\n\r\n\tdist_coords = mix(coords, dist_coords, dist_amount);\r\n\r\n\treturn dist_coords;\r\n}\r\n\r\n// sample screen with an offset (randomize offset angle for better smothness), returns partial sample weight\r\nfloat sampleScreen(inout vec4 color, const in vec2 offset, const in float weight) {\r\n\r\n\t// compute coords with offset (a random angle is added)\r\n\tvec2 coords = distorted_coords;\r\n\tfloat angle = rand(coords * 100.0).x * TWOPI;\r\n\tcoords += vec2(offset.x * cos(angle) - offset.y * sin(angle), offset.x * sin(angle) + offset.y * cos(angle));\r\n\r\n\tcolor += texture2D(textureSampler, coords)*weight;\r\n\r\n\treturn weight;\r\n}\r\n\r\n// returns blur level according to blur size required\r\nfloat getBlurLevel(float size) {\r\n\treturn min(3.0, ceil(size / 1.0));\r\n}\r\n\r\n// returns original screen color after blur\r\nvec4 getBlurColor(float size) {\r\n\r\n\tvec4 col = texture2D(textureSampler, distorted_coords);\r\n\tif (size == 0.0) { return col; }\r\n\r\n\t// there are max. 30 samples; the number of samples chosen is dependant on the blur size\r\n\t// there can be 10, 20 or 30 samples chosen; levels of blur are then 1, 2 or 3\r\n\tfloat blur_level = getBlurLevel(size);\r\n\r\n\tfloat w = (size / screen_width);\r\n\tfloat h = (size / screen_height);\r\n\tfloat total_weight = 1.0;\r\n\tvec2 sample_coords;\r\n\r\n\ttotal_weight += sampleScreen(col, vec2(-0.50*w, 0.24*h), 0.93);\r\n\ttotal_weight += sampleScreen(col, vec2(0.30*w, -0.75*h), 0.90);\r\n\ttotal_weight += sampleScreen(col, vec2(0.36*w, 0.96*h), 0.87);\r\n\ttotal_weight += sampleScreen(col, vec2(-1.08*w, -0.55*h), 0.85);\r\n\ttotal_weight += sampleScreen(col, vec2(1.33*w, -0.37*h), 0.83);\r\n\ttotal_weight += sampleScreen(col, vec2(-0.82*w, 1.31*h), 0.80);\r\n\ttotal_weight += sampleScreen(col, vec2(-0.31*w, -1.67*h), 0.78);\r\n\ttotal_weight += sampleScreen(col, vec2(1.47*w, 1.11*h), 0.76);\r\n\ttotal_weight += sampleScreen(col, vec2(-1.97*w, 0.19*h), 0.74);\r\n\ttotal_weight += sampleScreen(col, vec2(1.42*w, -1.57*h), 0.72);\r\n\r\n\tif (blur_level > 1.0) {\r\n\t\ttotal_weight += sampleScreen(col, vec2(0.01*w, 2.25*h), 0.70);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-1.62*w, -1.74*h), 0.67);\r\n\t\ttotal_weight += sampleScreen(col, vec2(2.49*w, 0.20*h), 0.65);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-2.07*w, 1.61*h), 0.63);\r\n\t\ttotal_weight += sampleScreen(col, vec2(0.46*w, -2.70*h), 0.61);\r\n\t\ttotal_weight += sampleScreen(col, vec2(1.55*w, 2.40*h), 0.59);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-2.88*w, -0.75*h), 0.56);\r\n\t\ttotal_weight += sampleScreen(col, vec2(2.73*w, -1.44*h), 0.54);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-1.08*w, 3.02*h), 0.52);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-1.28*w, -3.05*h), 0.49);\r\n\t}\r\n\r\n\tif (blur_level > 2.0) {\r\n\t\ttotal_weight += sampleScreen(col, vec2(3.11*w, 1.43*h), 0.46);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-3.36*w, 1.08*h), 0.44);\r\n\t\ttotal_weight += sampleScreen(col, vec2(1.80*w, -3.16*h), 0.41);\r\n\t\ttotal_weight += sampleScreen(col, vec2(0.83*w, 3.65*h), 0.38);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-3.16*w, -2.19*h), 0.34);\r\n\t\ttotal_weight += sampleScreen(col, vec2(3.92*w, -0.53*h), 0.31);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-2.59*w, 3.12*h), 0.26);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-0.20*w, -4.15*h), 0.22);\r\n\t\ttotal_weight += sampleScreen(col, vec2(3.02*w, 3.00*h), 0.15);\r\n\t}\r\n\r\n\tcol /= total_weight;\t\t// scales color according to weights\r\n\r\n\t\t\t\t\t\t\t\t// darken if out of focus\r\n\tif (darken > 0.0) {\r\n\t\tcol.rgb *= clamp(0.3, 1.0, 1.05 - size*0.5*darken);\r\n\t}\r\n\r\n\t// blur levels debug\r\n\t// if(blur_level == 1.0) { col.b *= 0.5; }\r\n\t// if(blur_level == 2.0) { col.r *= 0.5; }\r\n\t// if(blur_level == 3.0) { col.g *= 0.5; }\r\n\r\n\treturn col;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\r\n\t// Common calc: position relative to screen center, screen radius, distorted coords, position in texel space\r\n\tcentered_screen_pos = vec2(vUV.x - 0.5, vUV.y - 0.5);\r\n\tradius2 = centered_screen_pos.x*centered_screen_pos.x + centered_screen_pos.y*centered_screen_pos.y;\r\n\tradius = sqrt(radius2);\r\n\tdistorted_coords = getDistortedCoords(vUV);\t\t// we distort the screen coordinates (lens \"magnifying\" effect)\r\n\tvec2 texels_coords = vec2(vUV.x * screen_width, vUV.y * screen_height);\t// varies from 0 to SCREEN_WIDTH or _HEIGHT\r\n\r\n\tfloat depth = texture2D(depthSampler, distorted_coords).r;\t// depth value from DepthRenderer: 0 to 1\r\n\tfloat distance = near + (far - near)*depth;\t\t// actual distance from the lens\r\n\tvec4 color = texture2D(textureSampler, vUV);\t// original raster\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t// compute the circle of confusion size (CoC), i.e. blur radius depending on depth\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t// screen_distance is precomputed in code\r\n\tfloat coc = abs(aperture * (screen_distance * (inverse_focal_length - 1.0 / distance) - 1.0));\r\n\r\n\t// disable blur\r\n\tif (dof_enabled == false || coc < 0.07) { coc = 0.0; }\r\n\r\n\t// blur from edge blur effect\r\n\tfloat edge_blur_amount = 0.0;\r\n\tif (edge_blur > 0.0) {\r\n\t\tedge_blur_amount = clamp((radius*2.0 - 1.0 + 0.15*edge_blur) * 1.5, 0.0, 1.0) * 1.3;\r\n\t}\r\n\r\n\t// total blur amount\r\n\tfloat blur_amount = max(edge_blur_amount, coc);\r\n\r\n\t// apply blur if necessary\r\n\tif (blur_amount == 0.0) {\r\n\t\tgl_FragColor = texture2D(textureSampler, distorted_coords);\r\n\t}\r\n\telse {\r\n\r\n\t\t// add blurred color\r\n\t\tgl_FragColor = getBlurColor(blur_amount * 1.7);\r\n\r\n\t\t// if we have computed highlights: enhance highlights\r\n\t\tif (highlights) {\r\n\t\t\tgl_FragColor.rgb += clamp(coc, 0.0, 1.0)*texture2D(highlightsSampler, distorted_coords).rgb;\r\n\t\t}\r\n\r\n\t\tif (blur_noise) {\r\n\t\t\t// we put a slight amount of noise in the blurred color\r\n\t\t\tvec2 noise = rand(distorted_coords) * 0.01 * blur_amount;\r\n\t\t\tvec2 blurred_coord = vec2(distorted_coords.x + noise.x, distorted_coords.y + noise.y);\r\n\t\t\tgl_FragColor = 0.04 * texture2D(textureSampler, blurred_coord) + 0.96 * gl_FragColor;\r\n\t\t}\r\n\t}\r\n\r\n\r\n\t// apply grain\r\n\tif (grain_amount > 0.0) {\r\n\t\tvec4 grain_color = texture2D(grainSampler, texels_coords*0.003);\r\n\t\tgl_FragColor.rgb += (-0.5 + grain_color.rgb) * 0.30 * grain_amount;\r\n\t}\r\n\r\n}\r\n","displayPassPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D passSampler;\r\n\r\nvoid main(void)\r\n{\r\n gl_FragColor = texture2D(passSampler, vUV);\r\n}","filterPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nuniform mat4 kernelMatrix;\r\n\r\nvoid main(void)\r\n{\r\n\tvec3 baseColor = texture2D(textureSampler, vUV).rgb;\r\n\tvec3 updatedColor = (kernelMatrix * vec4(baseColor, 1.0)).rgb;\r\n\r\n\tgl_FragColor = vec4(updatedColor, 1.0);\r\n}","fxaaPixelShader":"precision highp float;\r\n\r\n#define FXAA_REDUCE_MIN (1.0/128.0)\r\n#define FXAA_REDUCE_MUL (1.0/8.0)\r\n#define FXAA_SPAN_MAX 8.0\r\n\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 texelSize;\r\n\r\nvoid main(){\r\n\tvec2 localTexelSize = texelSize;\r\n\tvec4 rgbNW = texture2D(textureSampler, (vUV + vec2(-1.0, -1.0) * localTexelSize));\r\n\tvec4 rgbNE = texture2D(textureSampler, (vUV + vec2(1.0, -1.0) * localTexelSize));\r\n\tvec4 rgbSW = texture2D(textureSampler, (vUV + vec2(-1.0, 1.0) * localTexelSize));\r\n\tvec4 rgbSE = texture2D(textureSampler, (vUV + vec2(1.0, 1.0) * localTexelSize));\r\n\tvec4 rgbM = texture2D(textureSampler, vUV);\r\n\tvec4 luma = vec4(0.299, 0.587, 0.114, 1.0);\r\n\tfloat lumaNW = dot(rgbNW, luma);\r\n\tfloat lumaNE = dot(rgbNE, luma);\r\n\tfloat lumaSW = dot(rgbSW, luma);\r\n\tfloat lumaSE = dot(rgbSE, luma);\r\n\tfloat lumaM = dot(rgbM, luma);\r\n\tfloat lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\r\n\tfloat lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\r\n\r\n\tvec2 dir = vec2(-((lumaNW + lumaNE) - (lumaSW + lumaSE)), ((lumaNW + lumaSW) - (lumaNE + lumaSE)));\r\n\r\n\tfloat dirReduce = max(\r\n\t\t(lumaNW + lumaNE + lumaSW + lumaSE) * (0.25 * FXAA_REDUCE_MUL),\r\n\t\tFXAA_REDUCE_MIN);\r\n\r\n\tfloat rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\r\n\tdir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),\r\n\t\tmax(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),\r\n\t\tdir * rcpDirMin)) * localTexelSize;\r\n\r\n\tvec4 rgbA = 0.5 * (\r\n\t\ttexture2D(textureSampler, vUV + dir * (1.0 / 3.0 - 0.5)) +\r\n\t\ttexture2D(textureSampler, vUV + dir * (2.0 / 3.0 - 0.5)));\r\n\r\n\tvec4 rgbB = rgbA * 0.5 + 0.25 * (\r\n\t\ttexture2D(textureSampler, vUV + dir * -0.5) +\r\n\t\ttexture2D(textureSampler, vUV + dir * 0.5));\r\n\tfloat lumaB = dot(rgbB, luma);\r\n\tif ((lumaB < lumaMin) || (lumaB > lumaMax)) {\r\n\t\tgl_FragColor = rgbA;\r\n\t}\r\n\telse {\r\n\t\tgl_FragColor = rgbB;\r\n\t}\r\n}","hdrPixelShader":"precision highp float;\r\n\r\nuniform sampler2D textureSampler;\r\nvarying vec2 vUV;\r\n\r\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\r\nuniform float blurOffsets[9];\r\nuniform float blurWeights[9];\r\nuniform float multiplier;\r\n\r\nvoid main(void) {\r\n\tvec4 color = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\tfor (int i = 0; i < 9; i++) {\r\n\t\t#ifdef GAUSSIAN_BLUR_H\r\n\t\tcolor += (texture2D(textureSampler, vUV + vec2(blurOffsets[i] * multiplier, 0.0)) * blurWeights[i]);\r\n\t\t#else\r\n\t\tcolor += (texture2D(textureSampler, vUV + vec2(0.0, blurOffsets[i] * multiplier)) * blurWeights[i]);\r\n\t\t#endif\r\n\t}\r\n\r\n\tcolor.a = 1.0;\r\n\tgl_FragColor = color;\r\n}\r\n#endif\r\n\r\n#if defined(TEXTURE_ADDER)\r\nuniform sampler2D otherSampler;\r\n\r\nvoid main() {\r\n\tvec4 sum = texture2D(textureSampler, vUV) + texture2D(otherSampler, vUV);\r\n\tsum.a = clamp(sum.a, 0.0, 1.0);\r\n\r\n\tgl_FragColor = sum;\r\n}\r\n#endif\r\n\r\n#if defined(LUMINANCE_GENERATOR)\r\nuniform vec2 lumOffsets[4];\r\n\r\nvoid main() {\r\n\tfloat average = 0.0;\r\n\tvec4 color = vec4(0.0, 0.0, 0.0, 0.0);\r\n\tfloat maximum = -1e20;\r\n\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\tcolor = texture2D(textureSampler, vUV + lumOffsets[i]);\r\n\r\n\t\tfloat GreyValue = length(color.rgb);\r\n\r\n\t\tmaximum = max(maximum, GreyValue);\r\n\t\taverage += (0.25 * log(1e-5 + GreyValue));\r\n\t}\r\n\r\n\taverage = exp(average);\r\n\r\n\tgl_FragColor = vec4(average, maximum, 0.0, 1.0);\r\n\r\n}\r\n#endif\r\n\r\n#if defined(DOWN_SAMPLE)\r\nuniform vec2 dsOffsets[9];\r\nuniform float halfDestPixelSize;\r\n\r\n#ifdef FINAL_DOWN_SAMPLE\r\nvec4 pack(float value) {\r\n\tconst vec4 bit_shift = vec4(255.0 * 255.0 * 255.0, 255.0 * 255.0, 255.0, 1.0);\r\n\tconst vec4 bit_mask = vec4(0.0, 1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0);\r\n\r\n\tvec4 res = fract(value * bit_shift);\r\n\tres -= res.xxyz * bit_mask;\r\n\r\n\treturn res;\r\n}\r\n#endif\r\n\r\nvoid main() {\r\n\tvec4 color = vec4(0.0, 0.0, 0.0, 0.0);\r\n\tfloat average = 0.0;\r\n\r\n\tfor (int i = 0; i < 9; i++) {\r\n\t\tcolor = texture2D(textureSampler, vUV + vec2(halfDestPixelSize, halfDestPixelSize) + dsOffsets[i]);\r\n\t\taverage += color.r;\r\n\t}\r\n\r\n\taverage /= 9.0;\r\n\r\n\t#ifndef FINAL_DOWN_SAMPLE\r\n\tgl_FragColor = vec4(average, average, 0.0, 1.0);\r\n\t#else\r\n\tgl_FragColor = pack(average);\r\n\t#endif\r\n}\r\n#endif\r\n\r\n#if defined(BRIGHT_PASS)\r\nuniform vec2 dsOffsets[4];\r\nuniform float brightThreshold;\r\n\r\nvoid main() {\r\n\tvec4 average = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\taverage = texture2D(textureSampler, vUV + vec2(dsOffsets[0].x, dsOffsets[0].y));\r\n\taverage += texture2D(textureSampler, vUV + vec2(dsOffsets[1].x, dsOffsets[1].y));\r\n\taverage += texture2D(textureSampler, vUV + vec2(dsOffsets[2].x, dsOffsets[2].y));\r\n\taverage += texture2D(textureSampler, vUV + vec2(dsOffsets[3].x, dsOffsets[3].y));\r\n\r\n\taverage *= 0.25;\r\n\r\n\tfloat luminance = length(average.rgb);\r\n\r\n\tif (luminance < brightThreshold) {\r\n\t\taverage = vec4(0.0, 0.0, 0.0, 1.0);\r\n\t}\r\n\r\n\tgl_FragColor = average;\r\n}\r\n#endif\r\n\r\n#if defined(DOWN_SAMPLE_X4)\r\nuniform vec2 dsOffsets[16];\r\n\r\nvoid main() {\r\n\tvec4 average = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\taverage = texture2D(textureSampler, vUV + dsOffsets[0]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[1]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[2]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[3]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[4]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[5]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[6]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[7]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[8]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[9]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[10]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[11]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[12]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[13]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[14]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[15]);\r\n\r\n\taverage /= 16.0;\r\n\r\n\tgl_FragColor = average;\r\n}\r\n#endif\r\n\r\n#if defined(HDR)\r\nuniform sampler2D otherSampler;\r\n\r\nuniform float exposure;\r\nuniform float avgLuminance;\r\n\r\nvoid main() {\r\n\tvec4 color = texture2D(textureSampler, vUV) + texture2D(otherSampler, vUV);\r\n\tvec4 adjustedColor = color / avgLuminance * exposure;\r\n\r\n\tcolor = adjustedColor;\r\n\tcolor.a = 1.0;\r\n\r\n\tgl_FragColor = color;\r\n}\r\n#endif\r\n","layerPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Color\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(textureSampler, vUV);\r\n\r\n\tgl_FragColor = baseColor * color;\r\n}","layerVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Uniforms\r\nuniform vec2 scale;\r\nuniform vec2 offset;\r\nuniform mat4 textureMatrix;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\tvec2 shiftedPosition = position * scale + offset;\r\n\tvUV = vec2(textureMatrix * vec4(shiftedPosition * madd + madd, 1.0, 0.0));\r\n\tgl_Position = vec4(shiftedPosition, 0.0, 1.0);\r\n}","legacydefaultPixelShader":"precision highp float;\r\n\r\n#define MAP_PROJECTION\t4.\r\n\r\n// Constants\r\nuniform vec3 vEyePosition;\r\nuniform vec3 vAmbientColor;\r\nuniform vec4 vDiffuseColor;\r\n#ifdef SPECULARTERM\r\nuniform vec4 vSpecularColor;\r\n#endif\r\nuniform vec3 vEmissiveColor;\r\n\r\n// Input\r\nvarying vec3 vPositionW;\r\nvarying vec3 vNormalW;\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n// Lights\r\n#include<light0FragmentDeclaration>\r\n#include<light1FragmentDeclaration>\r\n#include<light2FragmentDeclaration>\r\n#include<light3FragmentDeclaration>\r\n\r\n#include<lightsFragmentFunctions>\r\n#include<shadowsFragmentFunctions>\r\n\r\n// Samplers\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform sampler2D diffuseSampler;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform sampler2D ambientSampler;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\t\r\nvarying vec2 vOpacityUV;\r\nuniform sampler2D opacitySampler;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef REFLECTION\r\nvarying vec3 vReflectionUVW;\r\n#ifdef REFLECTIONMAP_3D\r\nuniform samplerCube reflectionCubeSampler;\r\n#else\r\nuniform sampler2D reflection2DSampler;\r\n#endif\r\nuniform vec2 vReflectionInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform sampler2D emissiveSampler;\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform sampler2D specularSampler;\r\n#endif\r\n\r\n// Fresnel\r\n#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\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n// Fog\r\n#include<fogFragmentDeclaration>\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\tfloat glossiness = 0.;\r\n#ifdef SPECULARTERM\r\n\tvec3 specularBase = vec3(0., 0., 0.);\r\n\tglossiness = vSpecularColor.a;\r\n#endif\r\n\tfloat shadow = 1.;\r\n\r\n#include<light0Fragment>\r\n#include<light1Fragment>\r\n#include<light2Fragment>\r\n#include<light3Fragment>\r\n\r\n\t// Reflection\r\n\tvec3 reflectionColor = vec3(0., 0., 0.);\r\n\r\n#ifdef REFLECTION\r\n#ifdef REFLECTIONMAP_3D\r\n\t\treflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.x;\r\n#else\r\n\t\tvec2 coords = vReflectionUVW.xy;\r\n\r\n#ifdef REFLECTIONMAP_PROJECTION\r\n\t\tcoords /= vReflectionUVW.z;\r\n#endif\r\n\r\n\t\tcoords.y = 1.0 - coords.y;\r\n\r\n\t\treflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.x;\r\n#endif\r\n\r\n#ifdef REFLECTIONFRESNEL\r\n\tfloat reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\r\n\r\n\treflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#endif\r\n#endif\r\n\r\n\t// Alpha\r\n\tfloat alpha = vDiffuseColor.a;\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\r\n#ifdef OPACITYRGB\r\n\topacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\r\n#else\r\n\talpha *= opacityMap.a * vOpacityInfos.y;\r\n#endif\r\n#endif\r\n\r\n#ifdef VERTEXALPHA\r\n\talpha *= vColor.a;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\n\tfloat opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\r\n\r\n\talpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\r\n#endif\r\n\r\n\t// Emissive\r\n\tvec3 emissiveColor = vEmissiveColor;\r\n#ifdef EMISSIVE\r\n\temissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\n\tfloat emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\r\n\r\n\temissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\r\n#endif\r\n\r\n\t// Specular map\r\n#ifdef SPECULARTERM\r\n\tvec3 specularColor = vSpecularColor.rgb;\r\n#ifdef SPECULAR\r\n\tspecularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\r\n#endif\r\n#endif\r\n\r\n\t// Fresnel\r\n#ifdef DIFFUSEFRESNEL\r\n\tfloat diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\r\n\r\n\tdiffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\r\n#endif\r\n\r\n\t// Composition\r\n\tvec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n#ifdef SPECULARTERM\r\n\tvec3 finalSpecular = specularBase * specularColor;\r\n#else\r\n\tvec3 finalSpecular = vec3(0.0);\r\n#endif\r\n\r\n\tvec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\r\n\r\n#include<fogFragment>\r\n\r\n\tgl_FragColor = color;\r\n}","legacydefaultVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\nattribute vec3 normal;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#ifdef VERTEXCOLOR\r\nattribute vec4 color;\r\n#endif\r\n#include<bonesDeclaration>\r\n\r\n// Uniforms\r\nuniform mat4 world;\r\nuniform mat4 view;\r\nuniform mat4 viewProjection;\r\n\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform mat4 diffuseMatrix;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform mat4 ambientMatrix;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\r\nvarying vec2 vOpacityUV;\r\nuniform mat4 opacityMatrix;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform mat4 emissiveMatrix;\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform mat4 specularMatrix;\r\n#endif\r\n\r\n#ifdef BUMP\r\nvarying vec2 vBumpUV;\r\nuniform vec2 vBumpInfos;\r\nuniform mat4 bumpMatrix;\r\n#endif\r\n\r\n// Output\r\nvarying vec3 vPositionW;\r\nvarying vec3 vNormalW;\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n#include<fogVertexDeclaration>\r\n#include<shadowsVertexDeclaration>\r\n\r\n#ifdef REFLECTION\r\nuniform vec3 vEyePosition;\r\nvarying vec3 vReflectionUVW;\r\nuniform mat4 reflectionMatrix;\r\n\r\nvec3 computeReflectionCoords(vec4 worldPos, vec3 worldNormal)\r\n{\r\n#ifdef REFLECTIONMAP_SPHERICAL\r\n\tvec3 coords = vec3(view * vec4(worldNormal, 0.0));\r\n\r\n\treturn vec3(reflectionMatrix * vec4(coords, 1.0));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_PLANAR\r\n\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\tvec3 coords = normalize(reflect(viewDir, worldNormal));\r\n\r\n\treturn vec3(reflectionMatrix * vec4(coords, 1));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_CUBIC\r\n\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\tvec3 coords = reflect(viewDir, worldNormal);\r\n#ifdef INVERTCUBICMAP\r\n\tcoords.y = 1.0 - coords.y;\r\n#endif\r\n\treturn vec3(reflectionMatrix * vec4(coords, 0));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_PROJECTION\r\n\treturn vec3(reflectionMatrix * (view * worldPos));\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_SKYBOX\r\n\treturn position;\r\n#endif\r\n\r\n#ifdef REFLECTIONMAP_EXPLICIT\r\n\treturn vec3(0, 0, 0);\r\n#endif\r\n}\r\n#endif\r\n\r\nvoid main(void) {\r\n\tmat4 finalWorld = world;\r\n\r\n#include<bonesVertex>\r\n\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n\r\n\tvec4 worldPos = finalWorld * vec4(position, 1.0);\r\n\tvPositionW = vec3(worldPos);\r\n\tvNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\r\n\r\n\t// Texture coordinates\r\n#ifndef UV1\r\n\tvec2 uv = vec2(0., 0.);\r\n#endif\r\n#ifndef UV2\r\n\tvec2 uv2 = vec2(0., 0.);\r\n#endif\r\n\r\n#ifdef DIFFUSE\r\n\tif (vDiffuseInfos.x == 0.)\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef AMBIENT\r\n\tif (vAmbientInfos.x == 0.)\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tif (vOpacityInfos.x == 0.)\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\t\r\n#ifdef REFLECTION\r\n\tvReflectionUVW = computeReflectionCoords(vec4(vPositionW, 1.0), vNormalW);\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\n\tif (vEmissiveInfos.x == 0.)\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\n\tif (vSpecularInfos.x == 0.)\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef BUMP\r\n\tif (vBumpInfos.x == 0.)\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n\r\n#include<fogVertex>\r\n#include<shadowsVertex>\r\n\r\n\t// Vertex color\r\n#ifdef VERTEXCOLOR\r\n\tvColor = color;\r\n#endif\r\n}","lensFlarePixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Color\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(textureSampler, vUV);\r\n\r\n\tgl_FragColor = baseColor * color;\r\n}","lensFlareVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Uniforms\r\nuniform mat4 viewportMatrix;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = viewportMatrix * vec4(position, 0.0, 1.0);\r\n}","lensHighlightsPixelShader":"precision highp float;\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\t// original color\r\n\r\n// uniforms\r\nuniform float gain;\r\nuniform float threshold;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// apply luminance filter\r\nvec4 highlightColor(vec4 color) {\r\n\tvec4 highlight = color;\r\n\tfloat luminance = dot(highlight.rgb, vec3(0.2125, 0.7154, 0.0721));\r\n\tfloat lum_threshold;\r\n\tif (threshold > 1.0) { lum_threshold = 0.94 + 0.01 * threshold; }\r\n\telse { lum_threshold = 0.5 + 0.44 * threshold; }\r\n\r\n\tluminance = clamp((luminance - lum_threshold) * (1.0 / (1.0 - lum_threshold)), 0.0, 1.0);\r\n\r\n\thighlight *= luminance * gain;\r\n\thighlight.a = 1.0;\r\n\r\n\treturn highlight;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 original = texture2D(textureSampler, vUV);\r\n\r\n\t// quick exit if no highlight computing\r\n\tif (gain == -1.0) {\r\n\t\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\t\treturn;\r\n\t}\r\n\r\n\tfloat w = 2.0 / screen_width;\r\n\tfloat h = 2.0 / screen_height;\r\n\r\n\tfloat weight = 1.0;\r\n\r\n\t// compute blurred color\r\n\tvec4 blurred = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n#ifdef PENTAGON\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.84*w, 0.43*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.48*w, -1.29*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.61*w, 1.51*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.55*w, -0.74*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.71*w, -0.52*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.94*w, 1.59*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.40*w, -1.87*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.62*w, 1.16*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.09*w, 0.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.46*w, -1.71*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.08*w, 2.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.85*w, -1.89*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.89*w, 0.16*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.29*w, 1.88*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.40*w, -2.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.54*w, 2.26*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.60*w, -0.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.31*w, -1.30*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.83*w, 2.53*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.12*w, -2.48*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.60*w, 1.11*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.82*w, 0.99*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.50*w, -2.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.85*w, 3.33*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.94*w, -1.92*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.27*w, -0.53*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.95*w, 2.48*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.23*w, -3.04*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.17*w, 2.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.97*w, -0.04*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.25*w, -2.00*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.31*w, 3.08*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.94*w, -2.59*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.37*w, 0.64*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.13*w, 1.93*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.03*w, -3.65*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.60*w, 3.17*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.14*w, -1.19*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.00*w, -1.19*h)));\r\n#else\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.85*w, 0.36*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.52*w, -1.14*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.46*w, 1.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.46*w, -0.83*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.79*w, -0.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.11*w, 1.62*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.29*w, -2.07*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.69*w, 1.39*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.28*w, 0.12*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.65*w, -1.69*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.08*w, 2.44*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.63*w, -1.90*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.55*w, 0.31*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.13*w, 1.52*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.56*w, -2.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.38*w, 2.34*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.64*w, -0.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.53*w, -1.21*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.06*w, 2.63*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.00*w, -2.69*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.59*w, 1.32*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.82*w, 0.78*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.57*w, -2.50*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.54*w, 2.93*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.39*w, -1.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.01*w, -0.28*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.04*w, 2.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.02*w, -3.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.09*w, 2.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.07*w, -0.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.44*w, -1.90*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.52*w, 3.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.68*w, -2.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.01*w, 0.79*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.76*w, 1.46*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.05*w, -2.94*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.21*w, 2.88*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.84*w, -1.30*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.98*w, -0.96*h)));\r\n#endif\r\n\r\n\tblurred /= 39.0;\r\n\r\n\tgl_FragColor = blurred;\r\n\r\n\t//if(vUV.x > 0.5) { gl_FragColor.rgb *= 0.0; }\r\n}","linePixelShader":"precision highp float;\r\n\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tgl_FragColor = color;\r\n}","lineVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\nattribute vec4 normal;\r\n\r\n// Uniforms\r\nuniform mat4 worldViewProjection;\r\n\r\nuniform float width;\r\nuniform float aspectRatio;\r\n\r\nvoid main(void) {\r\n\tvec4 viewPosition = worldViewProjection * vec4(position, 1.0);\r\n\tvec4 viewPositionNext = worldViewProjection * vec4(normal.xyz, 1.0);\r\n\r\n\tvec2 currentScreen = viewPosition.xy / viewPosition.w;\r\n\tvec2 nextScreen = viewPositionNext.xy / viewPositionNext.w;\r\n\r\n\tcurrentScreen.x *= aspectRatio;\r\n\tnextScreen.x *= aspectRatio;\r\n\r\n\tvec2 dir = normalize(nextScreen - currentScreen);\r\n\tvec2 normalDir = vec2(-dir.y, dir.x);\r\n\r\n\tnormalDir *= width / 2.0;\r\n\tnormalDir.x /= aspectRatio;\r\n\r\n\tvec4 offset = vec4(normalDir * normal.w, 0.0, 0.0);\r\n\tgl_Position = viewPosition + offset;\r\n}","outlinePixelShader":"precision highp float;\r\n\r\nuniform vec4 color;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\nvoid main(void) {\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","outlineVertexShader":"precision highp float;\r\n\r\n// Attribute\r\nattribute vec3 position;\r\nattribute vec3 normal;\r\n\r\n#include<bonesDeclaration>\r\n\r\n// Uniform\r\nuniform float offset;\r\n\r\n#include<instancesDeclaration>\r\n\r\nuniform mat4 viewProjection;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n\tvec3 offsetPosition = position + normal * offset;\r\n\r\n#include<instancesVertex>\r\n#include<bonesVertex>\r\n\r\n\tgl_Position = viewProjection * finalWorld * vec4(offsetPosition, 1.0);\r\n\r\n#ifdef ALPHATEST\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}\r\n","particlesPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\nuniform vec4 textureMask;\r\nuniform sampler2D diffuseSampler;\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\nvoid main(void) {\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\tvec4 baseColor = texture2D(diffuseSampler, vUV);\r\n\r\n\tgl_FragColor = (baseColor * textureMask + (vec4(1., 1., 1., 1.) - textureMask)) * vColor;\r\n}","particlesVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\nattribute vec4 color;\r\nattribute vec4 options;\r\n\r\n// Uniforms\r\nuniform mat4 view;\r\nuniform mat4 projection;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nuniform mat4 invView;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\nvoid main(void) {\t\r\n\tvec3 viewPos = (view * vec4(position, 1.0)).xyz; \r\n\tvec3 cornerPos;\r\n\tfloat size = options.y;\r\n\tfloat angle = options.x;\r\n\tvec2 offset = options.zw;\r\n\r\n\tcornerPos = vec3(offset.x - 0.5, offset.y - 0.5, 0.) * size;\r\n\r\n\t// Rotate\r\n\tvec3 rotatedCorner;\r\n\trotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\r\n\trotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\r\n\trotatedCorner.z = 0.;\r\n\r\n\t// Position\r\n\tviewPos += rotatedCorner;\r\n\tgl_Position = projection * vec4(viewPos, 1.0); \r\n\t\r\n\tvColor = color;\r\n\tvUV = offset;\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tvec4 worldPos = invView * vec4(viewPos, 1.0);\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n}","passPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nvoid main(void) \r\n{\r\n\tgl_FragColor = texture2D(textureSampler, vUV);\r\n}","postprocessVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = vec4(position, 0.0, 1.0);\r\n}","proceduralVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Output\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\tvPosition = position;\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = vec4(position, 0.0, 1.0);\r\n}","refractionPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D refractionSampler;\r\n\r\n// Parameters\r\nuniform vec3 baseColor;\r\nuniform float depth;\r\nuniform float colorLevel;\r\n\r\nvoid main() {\r\n\tfloat ref = 1.0 - texture2D(refractionSampler, vUV).r;\r\n\r\n\tvec2 uv = vUV - vec2(0.5);\r\n\tvec2 offset = uv * depth * ref;\r\n\tvec3 sourceColor = texture2D(textureSampler, vUV - offset).rgb;\r\n\r\n\tgl_FragColor = vec4(sourceColor + sourceColor * ref * colorLevel, 1.0);\r\n}","shadowMapPixelShader":"precision highp float;\r\n\r\nvec4 pack(float depth)\r\n{\r\n\tconst vec4 bit_shift = vec4(255.0 * 255.0 * 255.0, 255.0 * 255.0, 255.0, 1.0);\r\n\tconst vec4 bit_mask = vec4(0.0, 1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0);\r\n\r\n\tvec4 res = fract(depth * bit_shift);\r\n\tres -= res.xxyz * bit_mask;\r\n\r\n\treturn res;\r\n}\r\n\r\n// Thanks to http://devmaster.net/\r\nvec2 packHalf(float depth) \r\n{ \r\n\tconst vec2 bitOffset = vec2(1.0 / 255., 0.);\r\n\tvec2 color = vec2(depth, fract(depth * 255.));\r\n\r\n\treturn color - (color.yy * bitOffset);\r\n}\r\n\r\nvarying vec4 vPosition;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\n#ifdef CUBEMAP\r\nuniform vec3 lightPosition;\r\nuniform vec2 depthValues;\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n#ifdef CUBEMAP\r\n\tvec3 directionToLight = vPosition.xyz - lightPosition;\r\n\t\r\n\tfloat depth = length(directionToLight);\r\n\tdepth = (depth - depthValues.x) / (depthValues.y - depthValues.x);\r\n\tdepth = clamp(depth, 0., 1.0);\r\n#else\r\n\tfloat depth = vPosition.z / vPosition.w;\r\n\tdepth = depth * 0.5 + 0.5;\r\n#endif\r\n\r\n#ifdef VSM\r\n\tfloat moment1 = depth;\r\n\tfloat moment2 = moment1 * moment1;\r\n\r\n\tgl_FragColor = vec4(packHalf(moment1), packHalf(moment2));\r\n#else\r\n\tgl_FragColor = pack(depth);\r\n#endif\r\n}","shadowMapVertexShader":"precision highp float;\r\n\r\n// Attribute\r\nattribute vec3 position;\r\n\r\n#include<bonesDeclaration>\r\n\r\n// Uniforms\r\n#include<instancesDeclaration>\r\n\r\nuniform mat4 viewProjection;\r\n\r\nvarying vec4 vPosition;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#include<instancesVertex>\r\n#include<bonesVertex>\r\n\r\n#ifdef CUBEMAP\r\n\tvPosition = finalWorld * vec4(position, 1.0);\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n#else\r\n\tvPosition = viewProjection * finalWorld * vec4(position, 1.0);\r\n\tgl_Position = vPosition;\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}","spritesPixelShader":"precision highp float;\r\n\r\nuniform bool alphaTest;\r\n\r\nvarying vec4 vColor;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n\r\n// Fog\r\n#include<fogFragmentDeclaration>\r\n\r\nvoid main(void) {\r\n\tvec4 color = texture2D(diffuseSampler, vUV);\r\n\r\n\tif (alphaTest) \r\n\t{\r\n\t\tif (color.a < 0.95)\r\n\t\t\tdiscard;\r\n\t}\r\n\r\n\tcolor *= vColor;\r\n\r\n#include<fogFragment>\r\n\r\n\tgl_FragColor = color;\r\n}","spritesVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec4 position;\r\nattribute vec4 options;\r\nattribute vec4 cellInfo;\r\nattribute vec4 color;\r\n\r\n// Uniforms\r\nuniform vec2 textureInfos;\r\nuniform mat4 view;\r\nuniform mat4 projection;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\n\r\n#include<fogVertexDeclaration>\r\n\r\nvoid main(void) {\t\r\n\tvec3 viewPos = (view * vec4(position.xyz, 1.0)).xyz; \r\n\tvec2 cornerPos;\r\n\t\r\n\tfloat angle = position.w;\r\n\tvec2 size = vec2(options.x, options.y);\r\n\tvec2 offset = options.zw;\r\n\tvec2 uvScale = textureInfos.xy;\r\n\r\n\tcornerPos = vec2(offset.x - 0.5, offset.y - 0.5) * size;\r\n\r\n\t// Rotate\r\n\tvec3 rotatedCorner;\r\n\trotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\r\n\trotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\r\n\trotatedCorner.z = 0.;\r\n\r\n\t// Position\r\n\tviewPos += rotatedCorner;\r\n\tgl_Position = projection * vec4(viewPos, 1.0); \r\n\r\n\t// Color\r\n\tvColor = color;\r\n\t\r\n\t// Texture\r\n\tvec2 uvOffset = vec2(abs(offset.x - cellInfo.x), 1.0 - abs(offset.y - cellInfo.y));\r\n\r\n\tvUV = (uvOffset + cellInfo.zw) * uvScale;\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = viewPos.z;\r\n#endif\r\n}","ssaoPixelShader":"precision highp float;\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D randomSampler;\r\n\r\nuniform float randTextureTiles;\r\nuniform float samplesFactor;\r\nuniform vec3 sampleSphere[SAMPLES];\r\n\r\nuniform float totalStrength;\r\nuniform float radius;\r\nuniform float area;\r\nuniform float fallOff;\r\nuniform float base;\r\n\r\nvarying vec2 vUV;\r\n\r\nvec3 normalFromDepth(float depth, vec2 coords) {\r\n\tvec2 offset1 = vec2(0.0, radius);\r\n\tvec2 offset2 = vec2(radius, 0.0);\r\n\r\n\tfloat depth1 = texture2D(textureSampler, coords + offset1).r;\r\n\tfloat depth2 = texture2D(textureSampler, coords + offset2).r;\r\n\r\n vec3 p1 = vec3(offset1, depth1 - depth);\r\n vec3 p2 = vec3(offset2, depth2 - depth);\r\n\r\n vec3 normal = cross(p1, p2);\r\n\tnormal.z = -normal.z;\r\n\r\n return normalize(normal);\r\n}\r\n\r\nvoid main()\r\n{\r\n\tvec3 random = normalize(texture2D(randomSampler, vUV * randTextureTiles).rgb);\r\n\tfloat depth = texture2D(textureSampler, vUV).r;\r\n\tvec3 position = vec3(vUV, depth);\r\n\tvec3 normal = normalFromDepth(depth, vUV);\r\n\tfloat radiusDepth = radius / depth;\r\n\tfloat occlusion = 0.0;\r\n\r\n\tvec3 ray;\r\n\tvec3 hemiRay;\r\n\tfloat occlusionDepth;\r\n\tfloat difference;\r\n\r\n\tfor (int i = 0; i < SAMPLES; i++)\r\n\t{\r\n\t\tray = radiusDepth * reflect(sampleSphere[i], random);\r\n\t\themiRay = position + sign(dot(ray, normal)) * ray;\r\n\r\n\t\tocclusionDepth = texture2D(textureSampler, clamp(hemiRay.xy, vec2(0.001, 0.001), vec2(0.999, 0.999))).r;\r\n\t\tdifference = depth - occlusionDepth;\r\n\r\n\t\tocclusion += step(fallOff, difference) * (1.0 - smoothstep(fallOff, area, difference));\r\n\t}\r\n\r\n\tfloat ao = 1.0 - totalStrength * occlusion * samplesFactor;\r\n\r\n\tfloat result = clamp(ao + base, 0.0, 1.0);\r\n\tgl_FragColor.r = result;\r\n\tgl_FragColor.g = result;\r\n\tgl_FragColor.b = result;\r\n\tgl_FragColor.a = 1.0;\r\n}\r\n","ssaoCombinePixelShader":"precision highp float;\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D originalColor;\r\n\r\nvarying vec2 vUV;\r\n\r\nvoid main(void) {\r\n\tvec4 ssaoColor = texture2D(textureSampler, vUV);\r\n\tvec4 sceneColor = texture2D(originalColor, vUV);\r\n\r\n\tgl_FragColor = sceneColor * ssaoColor;\r\n}\r\n","stereoscopicInterlacePixelShader":"precision highp float;\r\n\r\nconst vec3 TWO = vec3(2.0, 2.0, 2.0);\r\n\r\nvarying vec2 vUV;\r\nuniform sampler2D camASampler;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 stepSize;\r\n\r\nvoid main(void)\r\n{\r\n bool useCamB;\r\n vec2 texCoord1;\r\n vec2 texCoord2;\r\n \r\n vec3 frag1;\r\n vec3 frag2;\r\n \r\n#ifdef IS_STEREOSCOPIC_HORIZ\r\n\t useCamB = vUV.x > 0.5;\r\n\t texCoord1 = vec2(useCamB ? (vUV.x - 0.5) * 2.0 : vUV.x * 2.0, vUV.y);\r\n\t texCoord2 = vec2(texCoord1.x + stepSize.x, vUV.y);\r\n#else\r\n\t useCamB = vUV.y > 0.5;\r\n\t texCoord1 = vec2(vUV.x, useCamB ? (vUV.y - 0.5) * 2.0 : vUV.y * 2.0);\r\n\t texCoord2 = vec2(vUV.x, texCoord1.y + stepSize.y);\r\n#endif\r\n \r\n // cannot assign a sampler to a variable, so must duplicate texture accesses\r\n if (useCamB){\r\n frag1 = texture2D(textureSampler, texCoord1).rgb;\r\n frag2 = texture2D(textureSampler, texCoord2).rgb;\r\n }else{\r\n frag1 = texture2D(camASampler , texCoord1).rgb;\r\n frag2 = texture2D(camASampler , texCoord2).rgb;\r\n }\r\n \r\n gl_FragColor = vec4((frag1 + frag2) / TWO, 1.0);\r\n}","tonemapPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Constants\r\nuniform float _ExposureAdjustment;\r\n\r\n#if defined(HABLE_TONEMAPPING)\r\n const float A = 0.15;\r\n const float B = 0.50;\r\n const float C = 0.10;\r\n const float D = 0.20;\r\n const float E = 0.02;\r\n const float F = 0.30;\r\n const float W = 11.2;\r\n#endif\r\n\r\nfloat Luminance(vec3 c)\r\n{\r\n return dot(c, vec3(0.22, 0.707, 0.071));\r\n}\r\n\r\nvoid main(void) \r\n{\r\n vec3 colour = texture2D(textureSampler, vUV).rgb;\r\n\r\n#if defined(REINHARD_TONEMAPPING)\r\n\r\n float lum = Luminance(colour.rgb); \r\n float lumTm = lum * _ExposureAdjustment;\r\n float scale = lumTm / (1.0 + lumTm); \r\n\r\n colour *= scale / lum;\r\n\r\n#elif defined(HABLE_TONEMAPPING)\r\n\r\n colour *= _ExposureAdjustment;\r\n\r\n const float ExposureBias = 2.0;\r\n vec3 x = ExposureBias * colour;\r\n\r\n vec3 curr = ((x * (A * x + C * B) + D * E) / (x * (A * x + B) + D * F)) - E / F;\r\n \r\n x = vec3(W, W, W);\r\n vec3 whiteScale = 1.0 / (((x * (A * x + C * B) + D * E) / (x * (A * x + B) + D * F)) - E / F);\r\n colour = curr * whiteScale;\r\n\r\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\r\n\r\n colour *= _ExposureAdjustment;\r\n \r\n vec3 X = max(vec3(0.0, 0.0, 0.0), colour - 0.004);\r\n vec3 retColor = (X * (6.2 * X + 0.5)) / (X * (6.2 * X + 1.7) + 0.06);\r\n\r\n colour = retColor * retColor;\r\n\r\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\r\n\r\n colour = vec3(1.0, 1.0, 1.0) - exp2(-_ExposureAdjustment * colour);\r\n\r\n#endif\r\n\r\n\tgl_FragColor = vec4(colour.rgb, 1.0);\r\n}","volumetricLightScatteringPixelShader":"precision highp float;\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D lightScatteringSampler;\r\n\r\nuniform float decay;\r\nuniform float exposure;\r\nuniform float weight;\r\nuniform float density;\r\nuniform vec2 meshPositionOnScreen;\r\n\r\nvarying vec2 vUV;\r\n\r\nvoid main(void) {\r\n vec2 tc = vUV;\r\n\tvec2 deltaTexCoord = (tc - meshPositionOnScreen.xy);\r\n deltaTexCoord *= 1.0 / float(NUM_SAMPLES) * density;\r\n\r\n float illuminationDecay = 1.0;\r\n\r\n\tvec4 color = texture2D(lightScatteringSampler, tc) * 0.4;\r\n\r\n for(int i=0; i < NUM_SAMPLES; i++) {\r\n tc -= deltaTexCoord;\r\n\t\tvec4 sample = texture2D(lightScatteringSampler, tc) * 0.4;\r\n sample *= illuminationDecay * weight;\r\n color += sample;\r\n illuminationDecay *= decay;\r\n }\r\n\r\n vec4 realColor = texture2D(textureSampler, vUV);\r\n gl_FragColor = ((vec4((vec3(color.r, color.g, color.b) * exposure), 1)) + (realColor * (1.5 - 0.4)));\r\n}\r\n","volumetricLightScatteringPassPixelShader":"precision highp float;\r\n\r\n#if defined(ALPHATEST) || defined(NEED_UV)\r\nvarying vec2 vUV;\r\n#endif\r\n\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\n#if defined(DIFFUSE_COLOR_RENDER)\r\nuniform vec3 color;\r\n#endif\r\n\r\n#if defined(OPACITY)\r\nuniform sampler2D opacitySampler;\r\nuniform float opacityLevel;\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\n\tvec4 diffuseColor = texture2D(diffuseSampler, vUV);\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\n\tif (diffuseColor.a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityColor = texture2D(opacitySampler, vUV);\r\n\tfloat alpha = 1.0;\r\n\r\n\t#ifdef OPACITYRGB\r\n\topacityColor.rgb = opacityColor.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityColor.x + opacityColor.y + opacityColor.z) * opacityLevel;\r\n\t#else\r\n\talpha *= opacityColor.a * opacityLevel;\r\n\t#endif\r\n\r\n\t#if defined(BASIC_RENDER)\r\n\tgl_FragColor = vec4(diffuseColor.rgb, alpha);\r\n\t#elif defined(DIFFUSE_COLOR_RENDER)\r\n\tgl_FragColor = vec4(color.rgb, alpha);\r\n\t#else\r\n\tgl_FragColor = vec4(0.0, 0.0, 0.0, alpha);\r\n\t#endif\r\n\r\n\tgl_FragColor.a = alpha;\r\n#else\r\n\r\n\t#if defined(BASIC_RENDER)\r\n\tgl_FragColor = diffuseColor;\r\n\t#elif defined(DIFFUSE_COLOR_RENDER)\r\n\tgl_FragColor = vec4(color.rgb, 1.0);\r\n\t#else\r\n\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\t#endif\r\n#endif\r\n\r\n}\r\n","vrDistortionCorrectionPixelShader":"precision highp float;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 LensCenter;\r\nuniform vec2 Scale;\r\nuniform vec2 ScaleIn;\r\nuniform vec4 HmdWarpParam;\r\n\r\nvec2 HmdWarp(vec2 in01) {\r\n\r\n\tvec2 theta = (in01 - LensCenter) * ScaleIn; // Scales to [-1, 1]\r\n\tfloat rSq = theta.x * theta.x + theta.y * theta.y;\r\n\tvec2 rvector = theta * (HmdWarpParam.x + HmdWarpParam.y * rSq + HmdWarpParam.z * rSq * rSq + HmdWarpParam.w * rSq * rSq * rSq);\r\n\treturn LensCenter + Scale * rvector;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 tc = HmdWarp(vUV);\r\n\tif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\r\n\t\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\telse{\r\n\t\tgl_FragColor = vec4(texture2D(textureSampler, tc).rgb, 1.0);\r\n\t}\r\n}"};
  38673. BABYLON.CollisionWorker="var BABYLON;!function(t){var e=function(t,e,o,i){return t.x>o.x+i?!1:o.x-i>e.x?!1:t.y>o.y+i?!1:o.y-i>e.y?!1:t.z>o.z+i?!1:o.z-i>e.z?!1:!0},o=function(t,e,o,i){var s=e*e-4*t*o,r={root:0,found:!1};if(0>s)return r;var n=Math.sqrt(s),c=(-e-n)/(2*t),h=(-e+n)/(2*t);if(c>h){var a=h;h=c,c=a}return c>0&&i>c?(r.root=c,r.found=!0,r):h>0&&i>h?(r.root=h,r.found=!0,r):r},i=function(){function i(){this.radius=new t.Vector3(1,1,1),this.retry=0,this.basePointWorld=t.Vector3.Zero(),this.velocityWorld=t.Vector3.Zero(),this.normalizedVelocity=t.Vector3.Zero(),this._collisionPoint=t.Vector3.Zero(),this._planeIntersectionPoint=t.Vector3.Zero(),this._tempVector=t.Vector3.Zero(),this._tempVector2=t.Vector3.Zero(),this._tempVector3=t.Vector3.Zero(),this._tempVector4=t.Vector3.Zero(),this._edge=t.Vector3.Zero(),this._baseToVertex=t.Vector3.Zero(),this._destinationPoint=t.Vector3.Zero(),this._slidePlaneNormal=t.Vector3.Zero(),this._displacementVector=t.Vector3.Zero()}return i.prototype._initialize=function(e,o,i){this.velocity=o,t.Vector3.NormalizeToRef(o,this.normalizedVelocity),this.basePoint=e,e.multiplyToRef(this.radius,this.basePointWorld),o.multiplyToRef(this.radius,this.velocityWorld),this.velocityWorldLength=this.velocityWorld.length(),this.epsilon=i,this.collisionFound=!1},i.prototype._checkPointInTriangle=function(e,o,i,s,r){o.subtractToRef(e,this._tempVector),i.subtractToRef(e,this._tempVector2),t.Vector3.CrossToRef(this._tempVector,this._tempVector2,this._tempVector4);var n=t.Vector3.Dot(this._tempVector4,r);return 0>n?!1:(s.subtractToRef(e,this._tempVector3),t.Vector3.CrossToRef(this._tempVector2,this._tempVector3,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),0>n?!1:(t.Vector3.CrossToRef(this._tempVector3,this._tempVector,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),n>=0))},i.prototype._canDoCollision=function(o,i,s,r){var n=t.Vector3.Distance(this.basePointWorld,o),c=Math.max(this.radius.x,this.radius.y,this.radius.z);return n>this.velocityWorldLength+c+i?!1:e(s,r,this.basePointWorld,this.velocityWorldLength+c)?!0:!1},i.prototype._testTriangle=function(e,i,s,r,n,c){var h,a=!1;i||(i=[]),i[e]||(i[e]=new t.Plane(0,0,0,0),i[e].copyFromPoints(s,r,n));var l=i[e];if(c||l.isFrontFacingTo(this.normalizedVelocity,0)){var _=l.signedDistanceTo(this.basePoint),d=t.Vector3.Dot(l.normal,this.velocity);if(0==d){if(Math.abs(_)>=1)return;a=!0,h=0}else{h=(-1-_)/d;var V=(1-_)/d;if(h>V){var u=V;V=h,h=u}if(h>1||0>V)return;0>h&&(h=0),h>1&&(h=1)}this._collisionPoint.copyFromFloats(0,0,0);var P=!1,p=1;if(a||(this.basePoint.subtractToRef(l.normal,this._planeIntersectionPoint),this.velocity.scaleToRef(h,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,s,r,n,l.normal)&&(P=!0,p=h,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!P){var m=this.velocity.lengthSquared(),f=m;this.basePoint.subtractToRef(s,this._tempVector);var T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p);y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(s)),this.basePoint.subtractToRef(r,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(r)),this.basePoint.subtractToRef(n,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(n)),r.subtractToRef(s,this._edge),s.subtractToRef(this.basePoint,this._baseToVertex);var g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex);if(f=g*-m+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found){var D=(v*y.root-R)/g;D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),s.addToRef(this._edge,this._collisionPoint))}n.subtractToRef(r,this._edge),r.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),f=g*-m+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),r.addToRef(this._edge,this._collisionPoint))),s.subtractToRef(n,this._edge),n.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),f=g*-m+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),n.addToRef(this._edge,this._collisionPoint)))}if(P){var x=p*this.velocity.length();(!this.collisionFound||x<this.nearestDistance)&&(this.intersectionPoint?this.intersectionPoint.copyFrom(this._collisionPoint):this.intersectionPoint=this._collisionPoint.clone(),this.nearestDistance=x,this.collisionFound=!0)}}},i.prototype._collide=function(t,e,o,i,s,r,n){for(var c=i;s>c;c+=3){var h=e[o[c]-r],a=e[o[c+1]-r],l=e[o[c+2]-r];this._testTriangle(c,t,l,a,h,n)}},i.prototype._getResponse=function(e,o){e.addToRef(o,this._destinationPoint),o.scaleInPlace(this.nearestDistance/o.length()),this.basePoint.addToRef(o,e),e.subtractToRef(this.intersectionPoint,this._slidePlaneNormal),this._slidePlaneNormal.normalize(),this._slidePlaneNormal.scaleToRef(this.epsilon,this._displacementVector),e.addInPlace(this._displacementVector),this.intersectionPoint.addInPlace(this._displacementVector),this._slidePlaneNormal.scaleInPlace(t.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint,this._slidePlaneNormal,this._destinationPoint)),this._destinationPoint.subtractInPlace(this._slidePlaneNormal),this._destinationPoint.subtractToRef(this.intersectionPoint,o)},i}();t.Collider=i}(BABYLON||(BABYLON={}));var BABYLON;!function(o){o.WorkerIncluded=!0;var e=function(){function o(){this._meshes={},this._geometries={}}return o.prototype.getMeshes=function(){return this._meshes},o.prototype.getGeometries=function(){return this._geometries},o.prototype.getMesh=function(o){return this._meshes[o]},o.prototype.addMesh=function(o){this._meshes[o.uniqueId]=o},o.prototype.removeMesh=function(o){delete this._meshes[o]},o.prototype.getGeometry=function(o){return this._geometries[o]},o.prototype.addGeometry=function(o){this._geometries[o.id]=o},o.prototype.removeGeometry=function(o){delete this._geometries[o]},o}();o.CollisionCache=e;var i=function(){function e(e,i,r){this.collider=e,this._collisionCache=i,this.finalPosition=r,this.collisionsScalingMatrix=o.Matrix.Zero(),this.collisionTranformationMatrix=o.Matrix.Zero()}return e.prototype.collideWithWorld=function(o,e,i,r){var t=.01;if(this.collider.retry>=i)return void this.finalPosition.copyFrom(o);this.collider._initialize(o,e,t);for(var s,l=this._collisionCache.getMeshes(),n=Object.keys(l),a=n.length,c=0;a>c;++c)if(s=n[c],parseInt(s)!=r){var d=l[s];d.checkCollisions&&this.checkCollision(d)}return this.collider.collisionFound?((0!==e.x||0!==e.y||0!==e.z)&&this.collider._getResponse(o,e),e.length()<=t?void this.finalPosition.copyFrom(o):(this.collider.retry++,void this.collideWithWorld(o,e,i,r))):void o.addToRef(e,this.finalPosition)},e.prototype.checkCollision=function(e){if(this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))){o.Matrix.ScalingToRef(1/this.collider.radius.x,1/this.collider.radius.y,1/this.collider.radius.z,this.collisionsScalingMatrix);var i=o.Matrix.FromArray(e.worldMatrixFromCache);i.multiplyToRef(this.collisionsScalingMatrix,this.collisionTranformationMatrix),this.processCollisionsForSubMeshes(this.collisionTranformationMatrix,e)}},e.prototype.processCollisionsForSubMeshes=function(o,e){var i=e.subMeshes,r=i.length;if(!e.geometryId)return void console.log(\"no mesh geometry id\");var t=this._collisionCache.getGeometry(e.geometryId);if(!t)return void console.log(\"couldn't find geometry\",e.geometryId);for(var s=0;r>s;s++){var l=i[s];r>1&&!this.checkSubmeshCollision(l)||(this.collideForSubMesh(l,o,t),this.collider.collisionFound&&(this.collider.collidedMesh=e.uniqueId))}},e.prototype.collideForSubMesh=function(e,i,r){if(!r.positionsArray){r.positionsArray=[];for(var t=0,s=r.positions.length;s>t;t+=3){var l=o.Vector3.FromArray([r.positions[t],r.positions[t+1],r.positions[t+2]]);r.positionsArray.push(l)}}if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(i)){e._lastColliderTransformMatrix=i.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];for(var n=e.verticesStart,a=e.verticesStart+e.verticesCount,t=n;a>t;t++)e._lastColliderWorldVertices.push(o.Vector3.TransformCoordinates(r.positionsArray[t],i))}this.collider._collide(e._trianglePlanes,e._lastColliderWorldVertices,r.indices,e.indexStart,e.indexStart+e.indexCount,e.verticesStart,e.hasMaterial)},e.prototype.checkSubmeshCollision=function(e){return this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))},e}();o.CollideWorker=i;var r=function(){function r(){}return r.prototype.onInit=function(i){this._collisionCache=new e;var r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.INIT};postMessage(r,void 0)},r.prototype.onUpdate=function(e){var i=this,r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.UPDATE};try{for(var t in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(t)&&this._collisionCache.addGeometry(e.updatedGeometries[t]);for(var s in e.updatedMeshes)e.updatedMeshes.hasOwnProperty(s)&&this._collisionCache.addMesh(e.updatedMeshes[s]);e.removedGeometries.forEach(function(o){i._collisionCache.removeGeometry(o)}),e.removedMeshes.forEach(function(o){i._collisionCache.removeMesh(o)})}catch(l){r.error=o.WorkerReplyType.UNKNOWN_ERROR}postMessage(r,void 0)},r.prototype.onCollision=function(e){var r=o.Vector3.Zero(),t=new o.Collider;t.radius=o.Vector3.FromArray(e.collider.radius);var s=new i(t,this._collisionCache,r);s.collideWithWorld(o.Vector3.FromArray(e.collider.position),o.Vector3.FromArray(e.collider.velocity),e.maximumRetry,e.excludedMeshUniqueId);var l={collidedMeshUniqueId:t.collidedMesh,collisionId:e.collisionId,newPosition:r.asArray()},n={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.COLLIDE,payload:l};postMessage(n,void 0)},r}();o.CollisionDetectorTransferable=r;try{if(self&&self instanceof WorkerGlobalScope){window={},o.Collider||(importScripts(\"./babylon.collisionCoordinator.js\"),importScripts(\"./babylon.collider.js\"),importScripts(\"../Math/babylon.math.js\"));var t=new r,s=function(e){var i=e.data;switch(i.taskType){case o.WorkerTaskType.INIT:t.onInit(i.payload);break;case o.WorkerTaskType.COLLIDE:t.onCollision(i.payload);break;case o.WorkerTaskType.UPDATE:t.onUpdate(i.payload)}};self.onmessage=s}}catch(l){console.log(\"single worker init\")}}(BABYLON||(BABYLON={}));var BABYLON;!function(e){e.CollisionWorker=\"\",function(e){e[e.INIT=0]=\"INIT\",e[e.UPDATE=1]=\"UPDATE\",e[e.COLLIDE=2]=\"COLLIDE\"}(e.WorkerTaskType||(e.WorkerTaskType={}));var o=e.WorkerTaskType;!function(e){e[e.SUCCESS=0]=\"SUCCESS\",e[e.UNKNOWN_ERROR=1]=\"UNKNOWN_ERROR\"}(e.WorkerReplyType||(e.WorkerReplyType={}));var i=e.WorkerReplyType,t=function(){function t(){var r=this;this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this.onMeshUpdated=function(e){r._addUpdateMeshesList[e.uniqueId]=t.SerializeMesh(e)},this.onGeometryUpdated=function(e){r._addUpdateGeometriesList[e.id]=t.SerializeGeometry(e)},this._afterRender=function(){if(r._init&&!(0==r._toRemoveGeometryArray.length&&0==r._toRemoveMeshesArray.length&&0==Object.keys(r._addUpdateGeometriesList).length&&0==Object.keys(r._addUpdateMeshesList).length||r._runningUpdated>4)){++r._runningUpdated;var e={updatedMeshes:r._addUpdateMeshesList,updatedGeometries:r._addUpdateGeometriesList,removedGeometries:r._toRemoveGeometryArray,removedMeshes:r._toRemoveMeshesArray},i={payload:e,taskType:o.UPDATE},t=[];for(var s in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(s)&&(t.push(i.payload.updatedGeometries[s].indices.buffer),t.push(i.payload.updatedGeometries[s].normals.buffer),t.push(i.payload.updatedGeometries[s].positions.buffer));r._worker.postMessage(i,t),r._addUpdateMeshesList={},r._addUpdateGeometriesList={},r._toRemoveGeometryArray=[],r._toRemoveMeshesArray=[]}},this._onMessageFromWorker=function(t){var s=t.data;if(s.error!=i.SUCCESS)return void e.Tools.Warn(\"error returned from worker!\");switch(s.taskType){case o.INIT:r._init=!0,r._scene.meshes.forEach(function(e){r.onMeshAdded(e)}),r._scene.getGeometries().forEach(function(e){r.onGeometryAdded(e)});break;case o.UPDATE:r._runningUpdated--;break;case o.COLLIDE:r._runningCollisionTask=!1;var n=s.payload;if(!r._collisionsCallbackArray[n.collisionId])return;r._collisionsCallbackArray[n.collisionId](n.collisionId,e.Vector3.FromArray(n.newPosition),r._scene.getMeshByUniqueID(n.collidedMeshUniqueId)),r._collisionsCallbackArray[n.collisionId]=void 0}},this._collisionsCallbackArray=[],this._init=!1,this._runningUpdated=0,this._runningCollisionTask=!1,this._addUpdateMeshesList={},this._addUpdateGeometriesList={},this._toRemoveGeometryArray=[],this._toRemoveMeshesArray=[]}return t.prototype.getNewPosition=function(e,i,t,r,s,n,a){if(this._init&&!this._collisionsCallbackArray[a]&&!this._collisionsCallbackArray[a+1e5]){e.divideToRef(t.radius,this._scaledPosition),i.divideToRef(t.radius,this._scaledVelocity),this._collisionsCallbackArray[a]=n;var d={collider:{position:this._scaledPosition.asArray(),velocity:this._scaledVelocity.asArray(),radius:t.radius.asArray()},collisionId:a,excludedMeshUniqueId:s?s.uniqueId:null,maximumRetry:r},l={payload:d,taskType:o.COLLIDE};this._worker.postMessage(l)}},t.prototype.init=function(i){this._scene=i,this._scene.registerAfterRender(this._afterRender);var t=e.WorkerIncluded?e.Engine.CodeRepository+\"Collisions/babylon.collisionWorker.js\":URL.createObjectURL(new Blob([e.CollisionWorker],{type:\"application/javascript\"}));this._worker=new Worker(t),this._worker.onmessage=this._onMessageFromWorker;var r={payload:{},taskType:o.INIT};this._worker.postMessage(r)},t.prototype.destroy=function(){this._scene.unregisterAfterRender(this._afterRender),this._worker.terminate()},t.prototype.onMeshAdded=function(e){e.registerAfterWorldMatrixUpdate(this.onMeshUpdated),this.onMeshUpdated(e)},t.prototype.onMeshRemoved=function(e){this._toRemoveMeshesArray.push(e.uniqueId)},t.prototype.onGeometryAdded=function(e){e.onGeometryUpdated=this.onGeometryUpdated,this.onGeometryUpdated(e)},t.prototype.onGeometryDeleted=function(e){this._toRemoveGeometryArray.push(e.id)},t.SerializeMesh=function(o){var i=[];o.subMeshes&&(i=o.subMeshes.map(function(e,o){return{position:o,verticesStart:e.verticesStart,verticesCount:e.verticesCount,indexStart:e.indexStart,indexCount:e.indexCount,hasMaterial:!!e.getMaterial(),sphereCenter:e.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:e.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:e.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:e.getBoundingInfo().boundingBox.maximumWorld.asArray()}}));var t=null;return o instanceof e.Mesh?t=o.geometry?o.geometry.id:null:o instanceof e.InstancedMesh&&(t=o.sourceMesh&&o.sourceMesh.geometry?o.sourceMesh.geometry.id:null),{uniqueId:o.uniqueId,id:o.id,name:o.name,geometryId:t,sphereCenter:o.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:o.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:o.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:o.getBoundingInfo().boundingBox.maximumWorld.asArray(),worldMatrixFromCache:o.worldMatrixFromCache.asArray(),subMeshes:i,checkCollisions:o.checkCollisions}},t.SerializeGeometry=function(o){return{id:o.id,positions:new Float32Array(o.getVerticesData(e.VertexBuffer.PositionKind)||[]),normals:new Float32Array(o.getVerticesData(e.VertexBuffer.NormalKind)||[]),indices:new Int32Array(o.getIndices()||[])}},t}();e.CollisionCoordinatorWorker=t;var r=function(){function o(){this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this._finalPosition=e.Vector3.Zero()}return o.prototype.getNewPosition=function(e,o,i,t,r,s,n){e.divideToRef(i.radius,this._scaledPosition),o.divideToRef(i.radius,this._scaledVelocity),i.collidedMesh=null,i.retry=0,i.initialVelocity=this._scaledVelocity,i.initialPosition=this._scaledPosition,this._collideWithWorld(this._scaledPosition,this._scaledVelocity,i,t,this._finalPosition,r),this._finalPosition.multiplyInPlace(i.radius),s(n,this._finalPosition,i.collidedMesh)},o.prototype.init=function(e){this._scene=e},o.prototype.destroy=function(){},o.prototype.onMeshAdded=function(e){},o.prototype.onMeshUpdated=function(e){},o.prototype.onMeshRemoved=function(e){},o.prototype.onGeometryAdded=function(e){},o.prototype.onGeometryUpdated=function(e){},o.prototype.onGeometryDeleted=function(e){},o.prototype._collideWithWorld=function(o,i,t,r,s,n){void 0===n&&(n=null);var a=10*e.Engine.CollisionsEpsilon;if(t.retry>=r)return void s.copyFrom(o);t._initialize(o,i,a);for(var d=0;d<this._scene.meshes.length;d++){var l=this._scene.meshes[d];l.isEnabled()&&l.checkCollisions&&l.subMeshes&&l!==n&&l._checkCollision(t)}return t.collisionFound?((0!==i.x||0!==i.y||0!==i.z)&&t._getResponse(o,i),i.length()<=a?void s.copyFrom(o):(t.retry++,void this._collideWithWorld(o,i,t,r,s,n))):void o.addToRef(i,s)},o}();e.CollisionCoordinatorLegacy=r}(BABYLON||(BABYLON={}));var BABYLON;!function(t){var i=1/2.2,n=2.2,r=function(){function r(t,i,n){void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=0),this.r=t,this.g=i,this.b=n}return r.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\"}\"},r.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,this},r.prototype.toColor4=function(t){return void 0===t&&(t=1),new o(this.r,this.g,this.b,t)},r.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},r.prototype.toLuminance=function(){return.3*this.r+.59*this.g+.11*this.b},r.prototype.multiply=function(t){return new r(this.r*t.r,this.g*t.g,this.b*t.b)},r.prototype.multiplyToRef=function(t,i){return i.r=this.r*t.r,i.g=this.g*t.g,i.b=this.b*t.b,this},r.prototype.equals=function(t){return t&&this.r===t.r&&this.g===t.g&&this.b===t.b},r.prototype.equalsFloats=function(t,i,n){return this.r===t&&this.g===i&&this.b===n},r.prototype.scale=function(t){return new r(this.r*t,this.g*t,this.b*t)},r.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,this},r.prototype.add=function(t){return new r(this.r+t.r,this.g+t.g,this.b+t.b)},r.prototype.addToRef=function(t,i){return i.r=this.r+t.r,i.g=this.g+t.g,i.b=this.b+t.b,this},r.prototype.subtract=function(t){return new r(this.r-t.r,this.g-t.g,this.b-t.b)},r.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,this},r.prototype.clone=function(){return new r(this.r,this.g,this.b)},r.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this},r.prototype.copyFromFloats=function(t,i,n){return this.r=t,this.g=i,this.b=n,this},r.prototype.toHexString=function(){var i=255*this.r|0,n=255*this.g|0,r=255*this.b|0;return\"#\"+t.Tools.ToHex(i)+t.Tools.ToHex(n)+t.Tools.ToHex(r)},r.prototype.toLinearSpace=function(){var t=new r;return this.toLinearSpaceToRef(t),t},r.prototype.toLinearSpaceToRef=function(t){return t.r=Math.pow(this.r,n),t.g=Math.pow(this.g,n),t.b=Math.pow(this.b,n),this},r.prototype.toGammaSpace=function(){var t=new r;return this.toGammaSpaceToRef(t),t},r.prototype.toGammaSpaceToRef=function(t){return t.r=Math.pow(this.r,i),t.g=Math.pow(this.g,i),t.b=Math.pow(this.b,i),this},r.FromHexString=function(i){if(\"#\"!==i.substring(0,1)||7!==i.length)return t.Tools.Warn(\"Color3.FromHexString must be called with a string like #FFFFFF\"),new r(0,0,0);var n=parseInt(i.substring(1,3),16),o=parseInt(i.substring(3,5),16),s=parseInt(i.substring(5,7),16);return r.FromInts(n,o,s)},r.FromArray=function(t,i){return void 0===i&&(i=0),new r(t[i],t[i+1],t[i+2])},r.FromInts=function(t,i,n){return new r(t/255,i/255,n/255)},r.Lerp=function(t,i,n){var o=t.r+(i.r-t.r)*n,s=t.g+(i.g-t.g)*n,e=t.b+(i.b-t.b)*n;return new r(o,s,e)},r.Red=function(){return new r(1,0,0)},r.Green=function(){return new r(0,1,0)},r.Blue=function(){return new r(0,0,1)},r.Black=function(){return new r(0,0,0)},r.White=function(){return new r(1,1,1)},r.Purple=function(){return new r(.5,0,.5)},r.Magenta=function(){return new r(1,0,1)},r.Yellow=function(){return new r(1,1,0)},r.Gray=function(){return new r(.5,.5,.5)},r}();t.Color3=r;var o=function(){function i(t,i,n,r){this.r=t,this.g=i,this.b=n,this.a=r}return i.prototype.addInPlace=function(t){return this.r+=t.r,this.g+=t.g,this.b+=t.b,this.a+=t.a,this},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,t[i+3]=this.a,this},i.prototype.add=function(t){return new i(this.r+t.r,this.g+t.g,this.b+t.b,this.a+t.a)},i.prototype.subtract=function(t){return new i(this.r-t.r,this.g-t.g,this.b-t.b,this.a-t.a)},i.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,i.a=this.a-t.a,this},i.prototype.scale=function(t){return new i(this.r*t,this.g*t,this.b*t,this.a*t)},i.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,i.a=this.a*t,this},i.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\" A:\"+this.a+\"}\"},i.prototype.clone=function(){return new i(this.r,this.g,this.b,this.a)},i.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this.a=t.a,this},i.prototype.toHexString=function(){var i=255*this.r|0,n=255*this.g|0,r=255*this.b|0,o=255*this.a|0;return\"#\"+t.Tools.ToHex(i)+t.Tools.ToHex(n)+t.Tools.ToHex(r)+t.Tools.ToHex(o)},i.FromHexString=function(n){if(\"#\"!==n.substring(0,1)||9!==n.length)return t.Tools.Warn(\"Color4.FromHexString must be called with a string like #FFFFFFFF\"),new i(0,0,0,0);var r=parseInt(n.substring(1,3),16),o=parseInt(n.substring(3,5),16),s=parseInt(n.substring(5,7),16),e=parseInt(n.substring(7,9),16);return i.FromInts(r,o,s,e)},i.Lerp=function(t,n,r){var o=new i(0,0,0,0);return i.LerpToRef(t,n,r,o),o},i.LerpToRef=function(t,i,n,r){r.r=t.r+(i.r-t.r)*n,r.g=t.g+(i.g-t.g)*n,r.b=t.b+(i.b-t.b)*n,r.a=t.a+(i.a-t.a)*n},i.FromArray=function(t,n){return void 0===n&&(n=0),new i(t[n],t[n+1],t[n+2],t[n+3])},i.FromInts=function(t,n,r,o){return new i(t/255,n/255,r/255,o/255)},i.CheckColors4=function(t,i){if(t.length===3*i){for(var n=[],r=0;r<t.length;r+=3){var o=r/3*4;n[o]=t[r],n[o+1]=t[r+1],n[o+2]=t[r+2],n[o+3]=1}return n}return t},i}();t.Color4=o;var s=function(){function i(t,i){this.x=t,this.y=i}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\"}\"},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,this},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this},i.prototype.copyFromFloats=function(t,i){return this.x=t,this.y=i,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y)},i.prototype.addVector3=function(t){return new i(this.x+t.x,this.y+t.y)},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y)},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y)},i.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,this},i.prototype.multiplyByFloats=function(t,n){return new i(this.x*t,this.y*n)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,this},i.prototype.negate=function(){return new i(-this.x,-this.y)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t)},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y},i.prototype.equalsWithEpsilon=function(i,n){return void 0===n&&(n=t.Engine.Epsilon),i&&t.Tools.WithinEpsilon(this.x,i.x,n)&&t.Tools.WithinEpsilon(this.y,i.y,n)},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y},i.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this},i.prototype.clone=function(){return new i(this.x,this.y)},i.Zero=function(){return new i(0,0)},i.FromArray=function(t,n){return void 0===n&&(n=0),new i(t[n],t[n+1])},i.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1]},i.CatmullRom=function(t,n,r,o,s){var e=s*s,h=s*e,a=.5*(2*n.x+(-t.x+r.x)*s+(2*t.x-5*n.x+4*r.x-o.x)*e+(-t.x+3*n.x-3*r.x+o.x)*h),u=.5*(2*n.y+(-t.y+r.y)*s+(2*t.y-5*n.y+4*r.y-o.y)*e+(-t.y+3*n.y-3*r.y+o.y)*h);return new i(a,u)},i.Clamp=function(t,n,r){var o=t.x;o=o>r.x?r.x:o,o=o<n.x?n.x:o;var s=t.y;return s=s>r.y?r.y:s,s=s<n.y?n.y:s,new i(o,s)},i.Hermite=function(t,n,r,o,s){var e=s*s,h=s*e,a=2*h-3*e+1,u=-2*h+3*e,m=h-2*e+s,c=h-e,y=t.x*a+r.x*u+n.x*m+o.x*c,p=t.y*a+r.y*u+n.y*m+o.y*c;return new i(y,p)},i.Lerp=function(t,n,r){var o=t.x+(n.x-t.x)*r,s=t.y+(n.y-t.y)*r;return new i(o,s)},i.Dot=function(t,i){return t.x*i.x+t.y*i.y},i.Normalize=function(t){var i=t.clone();return i.normalize(),i},i.Minimize=function(t,n){var r=t.x<n.x?t.x:n.x,o=t.y<n.y?t.y:n.y;return new i(r,o)},i.Maximize=function(t,n){var r=t.x>n.x?t.x:n.x,o=t.y>n.y?t.y:n.y;return new i(r,o)},i.Transform=function(t,n){var r=t.x*n.m[0]+t.y*n.m[4],o=t.x*n.m[1]+t.y*n.m[5];return new i(r,o)},i.Distance=function(t,n){return Math.sqrt(i.DistanceSquared(t,n))},i.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y;return n*n+r*r},i}();t.Vector2=s;var e=function(){function i(t,i,n){this.x=t,this.y=i,this.z=n}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"}\"},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,this},i.prototype.toQuaternion=function(){var t=new a(0,0,0,1),i=Math.cos(.5*(this.x+this.z)),n=Math.sin(.5*(this.x+this.z)),r=Math.cos(.5*(this.z-this.x)),o=Math.sin(.5*(this.z-this.x)),s=Math.cos(.5*this.y),e=Math.sin(.5*this.y);return t.x=r*e,t.y=-o*e,t.z=n*s,t.w=i*s,t},i.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y,this.z+t.z)},i.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,this},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y,this.z-t.z)},i.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,this},i.prototype.subtractFromFloats=function(t,n,r){return new i(this.x-t,this.y-n,this.z-r)},i.prototype.subtractFromFloatsToRef=function(t,i,n,r){return r.x=this.x-t,r.y=this.y-i,r.z=this.z-n,this},i.prototype.negate=function(){return new i(-this.x,-this.y,-this.z)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t,this.z*t)},i.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z},i.prototype.equalsWithEpsilon=function(i,n){return void 0===n&&(n=t.Engine.Epsilon),i&&t.Tools.WithinEpsilon(this.x,i.x,n)&&t.Tools.WithinEpsilon(this.y,i.y,n)&&t.Tools.WithinEpsilon(this.z,i.z,n)},i.prototype.equalsToFloats=function(t,i,n){return this.x===t&&this.y===i&&this.z===n},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y,this.z*t.z)},i.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,this},i.prototype.multiplyByFloats=function(t,n,r){return new i(this.x*t,this.y*n,this.z*r)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y,this.z/t.z)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,this},i.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),this},i.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),this},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z},i.prototype.normalize=function(){var t=this.length();if(0===t||1===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this},i.prototype.clone=function(){return new i(this.x,this.y,this.z)},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this},i.prototype.copyFromFloats=function(t,i,n){return this.x=t,this.y=i,this.z=n,this},i.GetClipFactor=function(t,n,r,o){var s=i.Dot(t,r)-o,e=i.Dot(n,r)-o,h=s/(s-e);return h},i.FromArray=function(t,n){return n||(n=0),new i(t[n],t[n+1],t[n+2])},i.FromFloatArray=function(t,n){return n||(n=0),new i(t[n],t[n+1],t[n+2])},i.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2]},i.FromFloatArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2]},i.FromFloatsToRef=function(t,i,n,r){r.x=t,r.y=i,r.z=n},i.Zero=function(){return new i(0,0,0)},i.Up=function(){return new i(0,1,0)},i.TransformCoordinates=function(t,n){var r=i.Zero();return i.TransformCoordinatesToRef(t,n,r),r},i.TransformCoordinatesToRef=function(t,i,n){var r=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8]+i.m[12],o=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9]+i.m[13],s=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]+i.m[14],e=t.x*i.m[3]+t.y*i.m[7]+t.z*i.m[11]+i.m[15];n.x=r/e,n.y=o/e,n.z=s/e},i.TransformCoordinatesFromFloatsToRef=function(t,i,n,r,o){var s=t*r.m[0]+i*r.m[4]+n*r.m[8]+r.m[12],e=t*r.m[1]+i*r.m[5]+n*r.m[9]+r.m[13],h=t*r.m[2]+i*r.m[6]+n*r.m[10]+r.m[14],a=t*r.m[3]+i*r.m[7]+n*r.m[11]+r.m[15];o.x=s/a,o.y=e/a,o.z=h/a},i.TransformNormal=function(t,n){var r=i.Zero();return i.TransformNormalToRef(t,n,r),r},i.TransformNormalToRef=function(t,i,n){n.x=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8],n.y=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9],n.z=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]},i.TransformNormalFromFloatsToRef=function(t,i,n,r,o){o.x=t*r.m[0]+i*r.m[4]+n*r.m[8],o.y=t*r.m[1]+i*r.m[5]+n*r.m[9],o.z=t*r.m[2]+i*r.m[6]+n*r.m[10]},i.CatmullRom=function(t,n,r,o,s){var e=s*s,h=s*e,a=.5*(2*n.x+(-t.x+r.x)*s+(2*t.x-5*n.x+4*r.x-o.x)*e+(-t.x+3*n.x-3*r.x+o.x)*h),u=.5*(2*n.y+(-t.y+r.y)*s+(2*t.y-5*n.y+4*r.y-o.y)*e+(-t.y+3*n.y-3*r.y+o.y)*h),m=.5*(2*n.z+(-t.z+r.z)*s+(2*t.z-5*n.z+4*r.z-o.z)*e+(-t.z+3*n.z-3*r.z+o.z)*h);return new i(a,u,m)},i.Clamp=function(t,n,r){var o=t.x;o=o>r.x?r.x:o,o=o<n.x?n.x:o;var s=t.y;s=s>r.y?r.y:s,s=s<n.y?n.y:s;var e=t.z;return e=e>r.z?r.z:e,e=e<n.z?n.z:e,new i(o,s,e)},i.Hermite=function(t,n,r,o,s){var e=s*s,h=s*e,a=2*h-3*e+1,u=-2*h+3*e,m=h-2*e+s,c=h-e,y=t.x*a+r.x*u+n.x*m+o.x*c,p=t.y*a+r.y*u+n.y*m+o.y*c,f=t.z*a+r.z*u+n.z*m+o.z*c;return new i(y,p,f)},i.Lerp=function(t,n,r){var o=t.x+(n.x-t.x)*r,s=t.y+(n.y-t.y)*r,e=t.z+(n.z-t.z)*r;return new i(o,s,e)},i.Dot=function(t,i){return t.x*i.x+t.y*i.y+t.z*i.z},i.Cross=function(t,n){var r=i.Zero();return i.CrossToRef(t,n,r),r},i.CrossToRef=function(t,i,n){n.x=t.y*i.z-t.z*i.y,n.y=t.z*i.x-t.x*i.z,n.z=t.x*i.y-t.y*i.x},i.Normalize=function(t){var n=i.Zero();return i.NormalizeToRef(t,n),n},i.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},i.Project=function(t,n,r,o){var s=o.width,e=o.height,h=o.x,a=o.y,m=u.FromValues(s/2,0,0,0,0,-e/2,0,0,0,0,1,0,h+s/2,e/2+a,0,1),c=n.multiply(r).multiply(m);return i.TransformCoordinates(t,c)},i.UnprojectFromTransform=function(n,r,o,s,e){var h=s.multiply(e);h.invert(),n.x=n.x/r*2-1,n.y=-(n.y/o*2-1);var a=i.TransformCoordinates(n,h),u=n.x*h.m[3]+n.y*h.m[7]+n.z*h.m[11]+h.m[15];return t.Tools.WithinEpsilon(u,1)&&(a=a.scale(1/u)),a},i.Unproject=function(n,r,o,s,e,h){var a=s.multiply(e).multiply(h);a.invert();var u=new i(n.x/r*2-1,-(n.y/o*2-1),n.z),m=i.TransformCoordinates(u,a),c=u.x*a.m[3]+u.y*a.m[7]+u.z*a.m[11]+a.m[15];return t.Tools.WithinEpsilon(c,1)&&(m=m.scale(1/c)),m},i.Minimize=function(t,i){var n=t.clone();return n.MinimizeInPlace(i),n},i.Maximize=function(t,i){var n=t.clone();return n.MaximizeInPlace(i),n},i.Distance=function(t,n){return Math.sqrt(i.DistanceSquared(t,n))},i.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y,o=t.z-i.z;return n*n+r*r+o*o},i.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},i.RotationFromAxis=function(t,n,r){var o=i.Zero();return i.RotationFromAxisToRef(t,n,r,o),o},i.RotationFromAxisToRef=function(n,r,o,s){var e=n.normalize(),h=o.normalize(),a=f.X,u=f.Y,m=0,c=0,y=0,p=0,l=0,x=0,z=0,w=-1,v=0,d=b.Vector3[0],g=0,T=b.Vector3[1];t.Tools.WithinEpsilon(h.z,0,t.Engine.Epsilon)?x=1:t.Tools.WithinEpsilon(h.x,0,t.Engine.Epsilon)?p=1:(z=h.z/h.x,p=-z*Math.sqrt(1/(1+z*z)),x=Math.sqrt(1/(1+z*z))),T.x=p,T.y=l,T.z=x,T.normalize(),i.CrossToRef(e,T,d),d.normalize(),i.Dot(h,d)<0&&(w=1),g=i.Dot(e,T),g=Math.min(1,Math.max(-1,g)),y=Math.acos(g)*w,i.Dot(T,a)<0&&(y=Math.PI+y,T=T.scaleInPlace(-1),v++);var R=b.Vector3[2],_=b.Vector3[3];p=0,l=0,x=0,w=-1,t.Tools.WithinEpsilon(h.z,0,t.Engine.Epsilon)?p=1:(z=T.z/T.x,p=-z*Math.sqrt(1/(1+z*z)),x=Math.sqrt(1/(1+z*z))),R.x=p,R.y=l,R.z=x,R.normalize(),i.CrossToRef(R,T,_),_.normalize(),i.CrossToRef(h,R,d),d.normalize(),i.Dot(T,d)<0&&(w=1),g=i.Dot(h,R),g=Math.min(1,Math.max(-1,g)),c=Math.acos(g)*w,i.Dot(_,u)<0&&(c=Math.PI+c,v++),w=-1,i.CrossToRef(a,T,d),d.normalize(),i.Dot(d,u)<0&&(w=1),g=i.Dot(T,a),g=Math.min(1,Math.max(-1,g)),m=-Math.acos(g)*w,0>g&&2>v&&(m=Math.PI+m),s.x=c,s.y=m,s.z=y},i}();t.Vector3=e;var h=function(){function i(t,i,n,r){this.x=t,this.y=i,this.z=n,this.w=r}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"W:\"+this.w+\"}\"},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,t[i+3]=this.w,this},i.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)},i.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,i.w=this.w+t.w,this},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)},i.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,i.w=this.w-t.w,this},i.prototype.subtractFromFloats=function(t,n,r,o){return new i(this.x-t,this.y-n,this.z-r,this.w-o)},i.prototype.subtractFromFloatsToRef=function(t,i,n,r,o){return o.x=this.x-t,o.y=this.y-i,o.z=this.z-n,o.w=this.w-r,this},i.prototype.negate=function(){return new i(-this.x,-this.y,-this.z,-this.w)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t,this.z*t,this.w*t)},i.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t,i.w=this.w*t},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},i.prototype.equalsWithEpsilon=function(i,n){return void 0===n&&(n=t.Engine.Epsilon),i&&t.Tools.WithinEpsilon(this.x,i.x,n)&&t.Tools.WithinEpsilon(this.y,i.y,n)&&t.Tools.WithinEpsilon(this.z,i.z,n)&&t.Tools.WithinEpsilon(this.w,i.w,n)},i.prototype.equalsToFloats=function(t,i,n,r){return this.x===t&&this.y===i&&this.z===n&&this.w===r},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y,this.z*t.z,this.w*t.w)},i.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,i.w=this.w*t.w,this},i.prototype.multiplyByFloats=function(t,n,r,o){return new i(this.x*t,this.y*n,this.z*r,this.w*o)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y,this.z/t.z,this.w/t.w)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,i.w=this.w/t.w,this},i.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),t.w<this.w&&(this.w=t.w),this},i.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),t.w>this.w&&(this.w=t.w),this},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},i.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this.w*=i,this},i.prototype.clone=function(){return new i(this.x,this.y,this.z,this.w)},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},i.prototype.copyFromFloats=function(t,i,n,r){return this.x=t,this.y=i,this.z=n,this.w=r,this},i.FromArray=function(t,n){return n||(n=0),new i(t[n],t[n+1],t[n+2],t[n+3])},i.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2],n.w=t[i+3]},i.FromFloatArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2],n.w=t[i+3]},i.FromFloatsToRef=function(t,i,n,r,o){o.x=t,o.y=i,o.z=n,o.w=r},i.Zero=function(){return new i(0,0,0,0)},i.Normalize=function(t){var n=i.Zero();return i.NormalizeToRef(t,n),n},i.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},i.Minimize=function(t,i){var n=t.clone();return n.MinimizeInPlace(i),n},i.Maximize=function(t,i){var n=t.clone();return n.MaximizeInPlace(i),n},i.Distance=function(t,n){return Math.sqrt(i.DistanceSquared(t,n))},i.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y,o=t.z-i.z,s=t.w-i.w;return n*n+r*r+o*o+s*s},i.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},i}();t.Vector4=h;var a=function(){function t(t,i,n,r){void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=0),void 0===r&&(r=1),this.x=t,this.y=i,this.z=n,this.w=r}return t.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\" W:\"+this.w+\"}\"},t.prototype.asArray=function(){return[this.x,this.y,this.z,this.w]},t.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},t.prototype.clone=function(){return new t(this.x,this.y,this.z,this.w)},t.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},t.prototype.copyFromFloats=function(t,i,n,r){return this.x=t,this.y=i,this.z=n,this.w=r,this},t.prototype.add=function(i){return new t(this.x+i.x,this.y+i.y,this.z+i.z,this.w+i.w)},t.prototype.subtract=function(i){return new t(this.x-i.x,this.y-i.y,this.z-i.z,this.w-i.w)},t.prototype.scale=function(i){return new t(this.x*i,this.y*i,this.z*i,this.w*i)},t.prototype.multiply=function(i){var n=new t(0,0,0,1);return this.multiplyToRef(i,n),n},t.prototype.multiplyToRef=function(t,i){var n=this.x*t.w+this.y*t.z-this.z*t.y+this.w*t.x,r=-this.x*t.z+this.y*t.w+this.z*t.x+this.w*t.y,o=this.x*t.y-this.y*t.x+this.z*t.w+this.w*t.z,s=-this.x*t.x-this.y*t.y-this.z*t.z+this.w*t.w;return i.copyFromFloats(n,r,o,s),this},t.prototype.multiplyInPlace=function(t){return this.multiplyToRef(t,this),this},t.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},t.prototype.normalize=function(){var t=1/this.length();return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},t.prototype.toEulerAngles=function(t){void 0===t&&(t=\"YZX\");var i=e.Zero();return this.toEulerAnglesToRef(i,t),i},t.prototype.toEulerAnglesToRef=function(t,i){void 0===i&&(i=\"YZX\");var n,r,o,s=this.x,e=this.y,h=this.z,a=this.w;switch(i){case\"YZX\":var u=s*e+h*a;if(u>.499&&(n=2*Math.atan2(s,a),r=Math.PI/2,o=0),-.499>u&&(n=-2*Math.atan2(s,a),r=-Math.PI/2,o=0),isNaN(n)){var m=s*s,c=e*e,y=h*h;n=Math.atan2(2*e*a-2*s*h,1-2*c-2*y),r=Math.asin(2*u),o=Math.atan2(2*s*a-2*e*h,1-2*m-2*y)}break;default:throw new Error(\"Euler order \"+i+\" not supported yet.\")}return t.y=n,t.z=r,t.x=o,this},t.prototype.toRotationMatrix=function(t){var i=this.x*this.x,n=this.y*this.y,r=this.z*this.z,o=this.x*this.y,s=this.z*this.w,e=this.z*this.x,h=this.y*this.w,a=this.y*this.z,u=this.x*this.w;return t.m[0]=1-2*(n+r),t.m[1]=2*(o+s),t.m[2]=2*(e-h),t.m[3]=0,t.m[4]=2*(o-s),t.m[5]=1-2*(r+i),t.m[6]=2*(a+u),t.m[7]=0,t.m[8]=2*(e+h),t.m[9]=2*(a-u),t.m[10]=1-2*(n+i),t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0,t.m[15]=1,this},t.prototype.fromRotationMatrix=function(i){return t.FromRotationMatrixToRef(i,this),this},t.FromRotationMatrix=function(i){var n=new t;return t.FromRotationMatrixToRef(i,n),n},t.FromRotationMatrixToRef=function(t,i){var n,r=t.m,o=r[0],s=r[4],e=r[8],h=r[1],a=r[5],u=r[9],m=r[2],c=r[6],y=r[10],p=o+a+y;p>0?(n=.5/Math.sqrt(p+1),i.w=.25/n,i.x=(c-u)*n,i.y=(e-m)*n,i.z=(h-s)*n):o>a&&o>y?(n=2*Math.sqrt(1+o-a-y),i.w=(c-u)/n,i.x=.25*n,i.y=(s+h)/n,i.z=(e+m)/n):a>y?(n=2*Math.sqrt(1+a-o-y),i.w=(e-m)/n,i.x=(s+h)/n,i.y=.25*n,i.z=(u+c)/n):(n=2*Math.sqrt(1+y-o-a),i.w=(h-s)/n,i.x=(e+m)/n,i.y=(u+c)/n,i.z=.25*n)},t.Inverse=function(i){return new t(-i.x,-i.y,-i.z,i.w)},t.Identity=function(){return new t(0,0,0,1)},t.RotationAxis=function(i,n){var r=new t,o=Math.sin(n/2);return i.normalize(),r.w=Math.cos(n/2),r.x=i.x*o,r.y=i.y*o,r.z=i.z*o,r},t.FromArray=function(i,n){return n||(n=0),new t(i[n],i[n+1],i[n+2],i[n+3])},t.RotationYawPitchRoll=function(i,n,r){var o=new t;return t.RotationYawPitchRollToRef(i,n,r,o),o},t.RotationYawPitchRollToRef=function(t,i,n,r){var o=.5*n,s=.5*i,e=.5*t,h=Math.sin(o),a=Math.cos(o),u=Math.sin(s),m=Math.cos(s),c=Math.sin(e),y=Math.cos(e);r.x=y*u*a+c*m*h,r.y=c*m*a-y*u*h,r.z=y*m*h-c*u*a,r.w=y*m*a+c*u*h},t.RotationAlphaBetaGamma=function(i,n,r){var o=new t;return t.RotationAlphaBetaGammaToRef(i,n,r,o),o},t.RotationAlphaBetaGammaToRef=function(t,i,n,r){var o=.5*(n+t),s=.5*(n-t),e=.5*i;r.x=Math.cos(s)*Math.sin(e),r.y=Math.sin(s)*Math.sin(e),r.z=Math.sin(o)*Math.cos(e),r.w=Math.cos(o)*Math.cos(e)},t.Slerp=function(i,n,r){var o,s,e=r,h=i.x*n.x+i.y*n.y+i.z*n.z+i.w*n.w,a=!1;if(0>h&&(a=!0,h=-h),h>.999999)s=1-e,o=a?-e:e;else{var u=Math.acos(h),m=1/Math.sin(u);s=Math.sin((1-e)*u)*m,o=a?-Math.sin(e*u)*m:Math.sin(e*u)*m}return new t(s*i.x+o*n.x,s*i.y+o*n.y,s*i.z+o*n.z,s*i.w+o*n.w)},t}();t.Quaternion=a;var u=function(){function i(){this.m=new Float32Array(16)}return i.prototype.isIdentity=function(){return 1!==this.m[0]||1!==this.m[5]||1!==this.m[10]||1!==this.m[15]?!1:0!==this.m[1]||0!==this.m[2]||0!==this.m[3]||0!==this.m[4]||0!==this.m[6]||0!==this.m[7]||0!==this.m[8]||0!==this.m[9]||0!==this.m[11]||0!==this.m[12]||0!==this.m[13]||0!==this.m[14]?!1:!0},i.prototype.determinant=function(){var t=this.m[10]*this.m[15]-this.m[11]*this.m[14],i=this.m[9]*this.m[15]-this.m[11]*this.m[13],n=this.m[9]*this.m[14]-this.m[10]*this.m[13],r=this.m[8]*this.m[15]-this.m[11]*this.m[12],o=this.m[8]*this.m[14]-this.m[10]*this.m[12],s=this.m[8]*this.m[13]-this.m[9]*this.m[12];return this.m[0]*(this.m[5]*t-this.m[6]*i+this.m[7]*n)-this.m[1]*(this.m[4]*t-this.m[6]*r+this.m[7]*o)+this.m[2]*(this.m[4]*i-this.m[5]*r+this.m[7]*s)-this.m[3]*(this.m[4]*n-this.m[5]*o+this.m[6]*s)},i.prototype.toArray=function(){return this.m},i.prototype.asArray=function(){return this.toArray()},i.prototype.invert=function(){return this.invertToRef(this),this},i.prototype.reset=function(){for(var t=0;16>t;t++)this.m[t]=0;return this},i.prototype.add=function(t){var n=new i;return this.addToRef(t,n),n},i.prototype.addToRef=function(t,i){for(var n=0;16>n;n++)i.m[n]=this.m[n]+t.m[n];return this},i.prototype.addToSelf=function(t){for(var i=0;16>i;i++)this.m[i]+=t.m[i];return this},i.prototype.invertToRef=function(t){var i=this.m[0],n=this.m[1],r=this.m[2],o=this.m[3],s=this.m[4],e=this.m[5],h=this.m[6],a=this.m[7],u=this.m[8],m=this.m[9],c=this.m[10],y=this.m[11],p=this.m[12],f=this.m[13],l=this.m[14],x=this.m[15],z=c*x-y*l,w=m*x-y*f,v=m*l-c*f,d=u*x-y*p,g=u*l-c*p,T=u*f-m*p,R=e*z-h*w+a*v,_=-(s*z-h*d+a*g),M=s*w-e*d+a*T,F=-(s*v-e*g+h*T),b=1/(i*R+n*_+r*M+o*F),A=h*x-a*l,L=e*x-a*f,P=e*l-h*f,Z=s*x-a*p,C=s*l-h*p,I=s*f-e*p,E=h*y-a*c,S=e*y-a*m,q=e*c-h*m,D=s*y-a*u,V=s*c-h*u,W=s*m-e*u;return t.m[0]=R*b,t.m[4]=_*b,t.m[8]=M*b,t.m[12]=F*b,t.m[1]=-(n*z-r*w+o*v)*b,t.m[5]=(i*z-r*d+o*g)*b,t.m[9]=-(i*w-n*d+o*T)*b,t.m[13]=(i*v-n*g+r*T)*b,t.m[2]=(n*A-r*L+o*P)*b,t.m[6]=-(i*A-r*Z+o*C)*b,t.m[10]=(i*L-n*Z+o*I)*b,t.m[14]=-(i*P-n*C+r*I)*b,t.m[3]=-(n*E-r*S+o*q)*b,t.m[7]=(i*E-r*D+o*V)*b,t.m[11]=-(i*S-n*D+o*W)*b,t.m[15]=(i*q-n*V+r*W)*b,this},i.prototype.setTranslation=function(t){return this.m[12]=t.x,this.m[13]=t.y,this.m[14]=t.z,this},i.prototype.multiply=function(t){var n=new i;return this.multiplyToRef(t,n),n},i.prototype.copyFrom=function(t){for(var i=0;16>i;i++)this.m[i]=t.m[i];return this},i.prototype.copyToArray=function(t,i){void 0===i&&(i=0);for(var n=0;16>n;n++)t[i+n]=this.m[n];return this},i.prototype.multiplyToRef=function(t,i){return this.multiplyToArray(t,i.m,0),this},i.prototype.multiplyToArray=function(t,i,n){var r=this.m[0],o=this.m[1],s=this.m[2],e=this.m[3],h=this.m[4],a=this.m[5],u=this.m[6],m=this.m[7],c=this.m[8],y=this.m[9],p=this.m[10],f=this.m[11],l=this.m[12],x=this.m[13],z=this.m[14],w=this.m[15],v=t.m[0],d=t.m[1],g=t.m[2],T=t.m[3],R=t.m[4],_=t.m[5],M=t.m[6],F=t.m[7],b=t.m[8],A=t.m[9],L=t.m[10],P=t.m[11],Z=t.m[12],C=t.m[13],I=t.m[14],E=t.m[15];return i[n]=r*v+o*R+s*b+e*Z,i[n+1]=r*d+o*_+s*A+e*C,i[n+2]=r*g+o*M+s*L+e*I,i[n+3]=r*T+o*F+s*P+e*E,i[n+4]=h*v+a*R+u*b+m*Z,i[n+5]=h*d+a*_+u*A+m*C,i[n+6]=h*g+a*M+u*L+m*I,i[n+7]=h*T+a*F+u*P+m*E,i[n+8]=c*v+y*R+p*b+f*Z,i[n+9]=c*d+y*_+p*A+f*C,i[n+10]=c*g+y*M+p*L+f*I,i[n+11]=c*T+y*F+p*P+f*E,i[n+12]=l*v+x*R+z*b+w*Z,i[n+13]=l*d+x*_+z*A+w*C,i[n+14]=l*g+x*M+z*L+w*I,i[n+15]=l*T+x*F+z*P+w*E,this},i.prototype.equals=function(t){return t&&this.m[0]===t.m[0]&&this.m[1]===t.m[1]&&this.m[2]===t.m[2]&&this.m[3]===t.m[3]&&this.m[4]===t.m[4]&&this.m[5]===t.m[5]&&this.m[6]===t.m[6]&&this.m[7]===t.m[7]&&this.m[8]===t.m[8]&&this.m[9]===t.m[9]&&this.m[10]===t.m[10]&&this.m[11]===t.m[11]&&this.m[12]===t.m[12]&&this.m[13]===t.m[13]&&this.m[14]===t.m[14]&&this.m[15]===t.m[15]},i.prototype.clone=function(){return i.FromValues(this.m[0],this.m[1],this.m[2],this.m[3],this.m[4],this.m[5],this.m[6],this.m[7],this.m[8],this.m[9],this.m[10],this.m[11],this.m[12],this.m[13],this.m[14],this.m[15])},i.prototype.decompose=function(n,r,o){o.x=this.m[12],o.y=this.m[13],o.z=this.m[14];var s=t.Tools.Sign(this.m[0]*this.m[1]*this.m[2]*this.m[3])<0?-1:1,e=t.Tools.Sign(this.m[4]*this.m[5]*this.m[6]*this.m[7])<0?-1:1,h=t.Tools.Sign(this.m[8]*this.m[9]*this.m[10]*this.m[11])<0?-1:1;if(n.x=s*Math.sqrt(this.m[0]*this.m[0]+this.m[1]*this.m[1]+this.m[2]*this.m[2]),n.y=e*Math.sqrt(this.m[4]*this.m[4]+this.m[5]*this.m[5]+this.m[6]*this.m[6]),n.z=h*Math.sqrt(this.m[8]*this.m[8]+this.m[9]*this.m[9]+this.m[10]*this.m[10]),0===n.x||0===n.y||0===n.z)return r.x=0,r.y=0,r.z=0,r.w=1,!1;var u=i.FromValues(this.m[0]/n.x,this.m[1]/n.x,this.m[2]/n.x,0,this.m[4]/n.y,this.m[5]/n.y,this.m[6]/n.y,0,this.m[8]/n.z,this.m[9]/n.z,this.m[10]/n.z,0,0,0,0,1);return a.FromRotationMatrixToRef(u,r),!0},i.FromArray=function(t,n){var r=new i;return n||(n=0),i.FromArrayToRef(t,n,r),r},i.FromArrayToRef=function(t,i,n){for(var r=0;16>r;r++)n.m[r]=t[r+i]},i.FromFloat32ArrayToRefScaled=function(t,i,n,r){for(var o=0;16>o;o++)r.m[o]=t[o+i]*n},i.FromValuesToRef=function(t,i,n,r,o,s,e,h,a,u,m,c,y,p,f,l,x){x.m[0]=t,x.m[1]=i,x.m[2]=n,x.m[3]=r,x.m[4]=o,x.m[5]=s,x.m[6]=e,x.m[7]=h,x.m[8]=a,x.m[9]=u,x.m[10]=m,x.m[11]=c,x.m[12]=y,x.m[13]=p,x.m[14]=f,x.m[15]=l},i.FromValues=function(t,n,r,o,s,e,h,a,u,m,c,y,p,f,l,x){var z=new i;return z.m[0]=t,z.m[1]=n,z.m[2]=r,z.m[3]=o,z.m[4]=s,z.m[5]=e,z.m[6]=h,z.m[7]=a,z.m[8]=u,z.m[9]=m,z.m[10]=c,z.m[11]=y,z.m[12]=p,z.m[13]=f,z.m[14]=l,z.m[15]=x,z},i.Compose=function(t,n,r){var o=i.FromValues(t.x,0,0,0,0,t.y,0,0,0,0,t.z,0,0,0,0,1),s=i.Identity();return n.toRotationMatrix(s),o=o.multiply(s),o.setTranslation(r),o},i.Identity=function(){return i.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},i.IdentityToRef=function(t){i.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,t)},i.Zero=function(){return i.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)},i.RotationX=function(t){var n=new i;return i.RotationXToRef(t,n),n},i.Invert=function(t){var n=new i;return t.invertToRef(n),n},i.RotationXToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[0]=1,i.m[15]=1,i.m[5]=r,i.m[10]=r,i.m[9]=-n,i.m[6]=n,i.m[1]=0,i.m[2]=0,i.m[3]=0,i.m[4]=0,i.m[7]=0,i.m[8]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationY=function(t){var n=new i;return i.RotationYToRef(t,n),n},i.RotationYToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[5]=1,i.m[15]=1,i.m[0]=r,i.m[2]=-n,i.m[8]=n,i.m[10]=r,i.m[1]=0,i.m[3]=0,i.m[4]=0,i.m[6]=0,i.m[7]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationZ=function(t){var n=new i;return i.RotationZToRef(t,n),n},i.RotationZToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[10]=1,i.m[15]=1,i.m[0]=r,i.m[1]=n,i.m[4]=-n,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;\n},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){a.RotationYawPitchRollToRef(t,i,n,this._tempQuaternion),this._tempQuaternion.toRotationMatrix(r)},i.Scaling=function(t,n,r){var o=i.Zero();return i.ScalingToRef(t,n,r,o),o},i.ScalingToRef=function(t,i,n,r){r.m[0]=t,r.m[1]=0,r.m[2]=0,r.m[3]=0,r.m[4]=0,r.m[5]=i,r.m[6]=0,r.m[7]=0,r.m[8]=0,r.m[9]=0,r.m[10]=n,r.m[11]=0,r.m[12]=0,r.m[13]=0,r.m[14]=0,r.m[15]=1},i.Translation=function(t,n,r){var o=i.Identity();return i.TranslationToRef(t,n,r,o),o},i.TranslationToRef=function(t,n,r,o){i.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,t,n,r,1,o)},i.Lerp=function(t,n,r){var o=new e(0,0,0),s=new a,h=new e(0,0,0);t.decompose(o,s,h);var u=new e(0,0,0),m=new a,c=new e(0,0,0);n.decompose(u,m,c);var y=e.Lerp(o,u,r),p=a.Slerp(s,m,r),f=e.Lerp(h,c,r);return i.Compose(y,p,f)},i.LookAtLH=function(t,n,r){var o=i.Zero();return i.LookAtLHToRef(t,n,r,o),o},i.LookAtLHToRef=function(t,n,r,o){n.subtractToRef(t,this._zAxis),this._zAxis.normalize(),e.CrossToRef(r,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),e.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var s=-e.Dot(this._xAxis,t),h=-e.Dot(this._yAxis,t),a=-e.Dot(this._zAxis,t);return i.FromValuesToRef(this._xAxis.x,this._yAxis.x,this._zAxis.x,0,this._xAxis.y,this._yAxis.y,this._zAxis.y,0,this._xAxis.z,this._yAxis.z,this._zAxis.z,0,s,h,a,1,o)},i.OrthoLH=function(t,n,r,o){var s=i.Zero();return i.OrthoLHToRef(t,n,r,o,s),s},i.OrthoLHToRef=function(t,n,r,o,s){var e=2/t,h=2/n,a=1/(o-r),u=r/(r-o);i.FromValuesToRef(e,0,0,0,0,h,0,0,0,0,a,0,0,0,u,1,s)},i.OrthoOffCenterLH=function(t,n,r,o,s,e){var h=i.Zero();return i.OrthoOffCenterLHToRef(t,n,r,o,s,e,h),h},i.OrthoOffCenterLHToRef=function(t,i,n,r,o,s,e){e.m[0]=2/(i-t),e.m[1]=e.m[2]=e.m[3]=0,e.m[5]=2/(r-n),e.m[4]=e.m[6]=e.m[7]=0,e.m[10]=-1/(o-s),e.m[8]=e.m[9]=e.m[11]=0,e.m[12]=(t+i)/(t-i),e.m[13]=(r+n)/(n-r),e.m[14]=o/(o-s),e.m[15]=1},i.PerspectiveLH=function(t,n,r,o){var s=i.Zero();return s.m[0]=2*r/t,s.m[1]=s.m[2]=s.m[3]=0,s.m[5]=2*r/n,s.m[4]=s.m[6]=s.m[7]=0,s.m[10]=-o/(r-o),s.m[8]=s.m[9]=0,s.m[11]=1,s.m[12]=s.m[13]=s.m[15]=0,s.m[14]=r*o/(r-o),s},i.PerspectiveFovLH=function(t,n,r,o){var s=i.Zero();return i.PerspectiveFovLHToRef(t,n,r,o,s),s},i.PerspectiveFovLHToRef=function(i,n,r,o,s,e){void 0===e&&(e=t.Camera.FOVMODE_VERTICAL_FIXED);var h=1/Math.tan(.5*i),a=e===t.Camera.FOVMODE_VERTICAL_FIXED;a?s.m[0]=h/n:s.m[0]=h,s.m[1]=s.m[2]=s.m[3]=0,a?s.m[5]=h:s.m[5]=h*n,s.m[4]=s.m[6]=s.m[7]=0,s.m[8]=s.m[9]=0,s.m[10]=-o/(r-o),s.m[11]=1,s.m[12]=s.m[13]=s.m[15]=0,s.m[14]=r*o/(r-o)},i.GetFinalMatrix=function(t,n,r,o,s,e){var h=t.width,a=t.height,u=t.x,m=t.y,c=i.FromValues(h/2,0,0,0,0,-a/2,0,0,0,0,e-s,0,u+h/2,a/2+m,s,1);return n.multiply(r).multiply(o).multiply(c)},i.GetAsMatrix2x2=function(t){return new Float32Array([t.m[0],t.m[1],t.m[4],t.m[5]])},i.GetAsMatrix3x3=function(t){return new Float32Array([t.m[0],t.m[1],t.m[2],t.m[4],t.m[5],t.m[6],t.m[8],t.m[9],t.m[10]])},i.Transpose=function(t){var n=new i;return n.m[0]=t.m[0],n.m[1]=t.m[4],n.m[2]=t.m[8],n.m[3]=t.m[12],n.m[4]=t.m[1],n.m[5]=t.m[5],n.m[6]=t.m[9],n.m[7]=t.m[13],n.m[8]=t.m[2],n.m[9]=t.m[6],n.m[10]=t.m[10],n.m[11]=t.m[14],n.m[12]=t.m[3],n.m[13]=t.m[7],n.m[14]=t.m[11],n.m[15]=t.m[15],n},i.Reflection=function(t){var n=new i;return i.ReflectionToRef(t,n),n},i.ReflectionToRef=function(t,i){t.normalize();var n=t.normal.x,r=t.normal.y,o=t.normal.z,s=-2*n,e=-2*r,h=-2*o;i.m[0]=s*n+1,i.m[1]=e*n,i.m[2]=h*n,i.m[3]=0,i.m[4]=s*r,i.m[5]=e*r+1,i.m[6]=h*r,i.m[7]=0,i.m[8]=s*o,i.m[9]=e*o,i.m[10]=h*o+1,i.m[11]=0,i.m[12]=s*t.d,i.m[13]=e*t.d,i.m[14]=h*t.d,i.m[15]=1},i._tempQuaternion=new a,i._xAxis=e.Zero(),i._yAxis=e.Zero(),i._zAxis=e.Zero(),i}();t.Matrix=u;var m=function(){function t(t,i,n,r){this.normal=new e(t,i,n),this.d=r}return t.prototype.asArray=function(){return[this.normal.x,this.normal.y,this.normal.z,this.d]},t.prototype.clone=function(){return new t(this.normal.x,this.normal.y,this.normal.z,this.d)},t.prototype.normalize=function(){var t=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z),i=0;return 0!==t&&(i=1/t),this.normal.x*=i,this.normal.y*=i,this.normal.z*=i,this.d*=i,this},t.prototype.transform=function(i){var n=u.Transpose(i),r=this.normal.x,o=this.normal.y,s=this.normal.z,e=this.d,h=r*n.m[0]+o*n.m[1]+s*n.m[2]+e*n.m[3],a=r*n.m[4]+o*n.m[5]+s*n.m[6]+e*n.m[7],m=r*n.m[8]+o*n.m[9]+s*n.m[10]+e*n.m[11],c=r*n.m[12]+o*n.m[13]+s*n.m[14]+e*n.m[15];return new t(h,a,m,c)},t.prototype.dotCoordinate=function(t){return this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z+this.d},t.prototype.copyFromPoints=function(t,i,n){var r,o=i.x-t.x,s=i.y-t.y,e=i.z-t.z,h=n.x-t.x,a=n.y-t.y,u=n.z-t.z,m=s*u-e*a,c=e*h-o*u,y=o*a-s*h,p=Math.sqrt(m*m+c*c+y*y);return r=0!==p?1/p:0,this.normal.x=m*r,this.normal.y=c*r,this.normal.z=y*r,this.d=-(this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z),this},t.prototype.isFrontFacingTo=function(t,i){var n=e.Dot(this.normal,t);return i>=n},t.prototype.signedDistanceTo=function(t){return e.Dot(t,this.normal)+this.d},t.FromArray=function(i){return new t(i[0],i[1],i[2],i[3])},t.FromPoints=function(i,n,r){var o=new t(0,0,0,0);return o.copyFromPoints(i,n,r),o},t.FromPositionAndNormal=function(i,n){var r=new t(0,0,0,0);return n.normalize(),r.normal=n,r.d=-(n.x*i.x+n.y*i.y+n.z*i.z),r},t.SignedDistanceToPlaneFromPositionAndNormal=function(t,i,n){var r=-(i.x*t.x+i.y*t.y+i.z*t.z);return e.Dot(n,i)+r},t}();t.Plane=m;var c=function(){function t(t,i,n,r){this.x=t,this.y=i,this.width=n,this.height=r}return t.prototype.toGlobal=function(i){var n=i.getRenderWidth(),r=i.getRenderHeight();return new t(this.x*n,this.y*r,this.width*n,this.height*r)},t.prototype.toScreenGlobal=function(i){var n=i.getRenderWidth(!0),r=i.getRenderHeight(!0);return new t(this.x*n,this.y*r,this.width*n,this.height*r)},t}();t.Viewport=c;var y=function(){function t(){}return t.GetPlanes=function(i){for(var n=[],r=0;6>r;r++)n.push(new m(0,0,0,0));return t.GetPlanesToRef(i,n),n},t.GetPlanesToRef=function(t,i){i[0].normal.x=t.m[3]+t.m[2],i[0].normal.y=t.m[7]+t.m[6],i[0].normal.z=t.m[11]+t.m[10],i[0].d=t.m[15]+t.m[14],i[0].normalize(),i[1].normal.x=t.m[3]-t.m[2],i[1].normal.y=t.m[7]-t.m[6],i[1].normal.z=t.m[11]-t.m[10],i[1].d=t.m[15]-t.m[14],i[1].normalize(),i[2].normal.x=t.m[3]+t.m[0],i[2].normal.y=t.m[7]+t.m[4],i[2].normal.z=t.m[11]+t.m[8],i[2].d=t.m[15]+t.m[12],i[2].normalize(),i[3].normal.x=t.m[3]-t.m[0],i[3].normal.y=t.m[7]-t.m[4],i[3].normal.z=t.m[11]-t.m[8],i[3].d=t.m[15]-t.m[12],i[3].normalize(),i[4].normal.x=t.m[3]-t.m[1],i[4].normal.y=t.m[7]-t.m[5],i[4].normal.z=t.m[11]-t.m[9],i[4].d=t.m[15]-t.m[13],i[4].normalize(),i[5].normal.x=t.m[3]+t.m[1],i[5].normal.y=t.m[7]+t.m[5],i[5].normal.z=t.m[11]+t.m[9],i[5].d=t.m[15]+t.m[13],i[5].normalize()},t}();t.Frustum=y;var p=function(){function i(t,i,n){void 0===n&&(n=Number.MAX_VALUE),this.origin=t,this.direction=i,this.length=n}return i.prototype.intersectsBoxMinMax=function(t,i){var n,r,o,s,e=0,h=Number.MAX_VALUE;if(Math.abs(this.direction.x)<1e-7){if(this.origin.x<t.x||this.origin.x>i.x)return!1}else if(n=1/this.direction.x,r=(t.x-this.origin.x)*n,o=(i.x-this.origin.x)*n,o===-(1/0)&&(o=1/0),r>o&&(s=r,r=o,o=s),e=Math.max(r,e),h=Math.min(o,h),e>h)return!1;if(Math.abs(this.direction.y)<1e-7){if(this.origin.y<t.y||this.origin.y>i.y)return!1}else if(n=1/this.direction.y,r=(t.y-this.origin.y)*n,o=(i.y-this.origin.y)*n,o===-(1/0)&&(o=1/0),r>o&&(s=r,r=o,o=s),e=Math.max(r,e),h=Math.min(o,h),e>h)return!1;if(Math.abs(this.direction.z)<1e-7){if(this.origin.z<t.z||this.origin.z>i.z)return!1}else if(n=1/this.direction.z,r=(t.z-this.origin.z)*n,o=(i.z-this.origin.z)*n,o===-(1/0)&&(o=1/0),r>o&&(s=r,r=o,o=s),e=Math.max(r,e),h=Math.min(o,h),e>h)return!1;return!0},i.prototype.intersectsBox=function(t){return this.intersectsBoxMinMax(t.minimum,t.maximum)},i.prototype.intersectsSphere=function(t){var i=t.center.x-this.origin.x,n=t.center.y-this.origin.y,r=t.center.z-this.origin.z,o=i*i+n*n+r*r,s=t.radius*t.radius;if(s>=o)return!0;var e=i*this.direction.x+n*this.direction.y+r*this.direction.z;if(0>e)return!1;var h=o-e*e;return s>=h},i.prototype.intersectsTriangle=function(i,n,r){this._edge1||(this._edge1=e.Zero(),this._edge2=e.Zero(),this._pvec=e.Zero(),this._tvec=e.Zero(),this._qvec=e.Zero()),n.subtractToRef(i,this._edge1),r.subtractToRef(i,this._edge2),e.CrossToRef(this.direction,this._edge2,this._pvec);var o=e.Dot(this._edge1,this._pvec);if(0===o)return null;var s=1/o;this.origin.subtractToRef(i,this._tvec);var h=e.Dot(this._tvec,this._pvec)*s;if(0>h||h>1)return null;e.CrossToRef(this._tvec,this._edge1,this._qvec);var a=e.Dot(this.direction,this._qvec)*s;if(0>a||h+a>1)return null;var u=e.Dot(this._edge2,this._qvec)*s;return u>this.length?null:new t.IntersectionInfo(h,a,u)},i.CreateNew=function(t,n,r,o,s,h,a){var u=e.Unproject(new e(t,n,0),r,o,s,h,a),m=e.Unproject(new e(t,n,1),r,o,s,h,a),c=m.subtract(u);return c.normalize(),new i(u,c)},i.CreateNewFromTo=function(t,n,r){void 0===r&&(r=u.Identity());var o=n.subtract(t),s=Math.sqrt(o.x*o.x+o.y*o.y+o.z*o.z);return o.normalize(),i.Transform(new i(t,o,s),r)},i.Transform=function(t,n){var r=e.TransformCoordinates(t.origin,n),o=e.TransformNormal(t.direction,n);return new i(r,o,t.length)},i}();t.Ray=p,function(t){t[t.LOCAL=0]=\"LOCAL\",t[t.WORLD=1]=\"WORLD\"}(t.Space||(t.Space={}));var f=(t.Space,function(){function t(){}return t.X=new e(1,0,0),t.Y=new e(0,1,0),t.Z=new e(0,0,1),t}());t.Axis=f;var l=function(){function t(){}return t.interpolate=function(t,i,n,r,o){for(var s=1-3*r+3*i,e=3*r-6*i,h=3*i,a=t,u=0;5>u;u++){var m=a*a,c=m*a,y=s*c+e*m+h*a,p=1/(3*s*m+2*e*a+h);a-=(y-t)*p,a=Math.min(1,Math.max(0,a))}return 3*Math.pow(1-a,2)*a*n+3*(1-a)*Math.pow(a,2)*o+Math.pow(a,3)},t}();t.BezierCurve=l,function(t){t[t.CW=0]=\"CW\",t[t.CCW=1]=\"CCW\"}(t.Orientation||(t.Orientation={}));var x=t.Orientation,z=function(){function t(t){var i=this;this.degrees=function(){return 180*i._radians/Math.PI},this.radians=function(){return i._radians},this._radians=t,this._radians<0&&(this._radians+=2*Math.PI)}return t.BetweenTwoPoints=function(i,n){var r=n.subtract(i),o=Math.atan2(r.y,r.x);return new t(o)},t.FromRadians=function(i){return new t(i)},t.FromDegrees=function(i){return new t(i*Math.PI/180)},t}();t.Angle=z;var w=function(){function t(t,i,n){this.startPoint=t,this.midPoint=i,this.endPoint=n;var r=Math.pow(i.x,2)+Math.pow(i.y,2),o=(Math.pow(t.x,2)+Math.pow(t.y,2)-r)/2,e=(r-Math.pow(n.x,2)-Math.pow(n.y,2))/2,h=(t.x-i.x)*(i.y-n.y)-(i.x-n.x)*(t.y-i.y);this.centerPoint=new s((o*(i.y-n.y)-e*(t.y-i.y))/h,((t.x-i.x)*e-(i.x-n.x)*o)/h),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=z.BetweenTwoPoints(this.centerPoint,this.startPoint);var a=this.startAngle.degrees(),u=z.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),m=z.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();u-a>180&&(u-=360),-180>u-a&&(u+=360),m-u>180&&(m-=360),-180>m-u&&(m+=360),this.orientation=0>u-a?x.CW:x.CCW,this.angle=z.FromDegrees(this.orientation===x.CW?a-m:m-a)}return t}();t.Arc2=w;var v=function(){function t(t){this.path=t,this._onchange=new Array,this.value=0,this.animations=new Array}return t.prototype.getPoint=function(){var t=this.path.getPointAtLengthPosition(this.value);return new e(t.x,0,t.y)},t.prototype.moveAhead=function(t){return void 0===t&&(t=.002),this.move(t),this},t.prototype.moveBack=function(t){return void 0===t&&(t=.002),this.move(-t),this},t.prototype.move=function(t){if(Math.abs(t)>1)throw\"step size should be less than 1.\";return this.value+=t,this.ensureLimits(),this.raiseOnChange(),this},t.prototype.ensureLimits=function(){for(;this.value>1;)this.value-=1;for(;this.value<0;)this.value+=1;return this},t.prototype.markAsDirty=function(t){return this.ensureLimits(),this.raiseOnChange(),this},t.prototype.raiseOnChange=function(){var t=this;return this._onchange.forEach(function(i){return i(t)}),this},t.prototype.onchange=function(t){return this._onchange.push(t),this},t}();t.PathCursor=v;var d=function(){function i(t,i){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new s(t,i))}return i.prototype.addLineTo=function(i,n){if(closed)return t.Tools.Error(\"cannot add lines to closed paths\"),this;var r=new s(i,n),o=this._points[this._points.length-1];return this._points.push(r),this._length+=r.subtract(o).length(),this},i.prototype.addArcTo=function(i,n,r,o,e){if(void 0===e&&(e=36),closed)return t.Tools.Error(\"cannot add arcs to closed paths\"),this;var h=this._points[this._points.length-1],a=new s(i,n),u=new s(r,o),m=new w(h,a,u),c=m.angle.radians()/e;m.orientation===x.CW&&(c*=-1);for(var y=m.startAngle.radians()+c,p=0;e>p;p++){var f=Math.cos(y)*m.radius+m.centerPoint.x,l=Math.sin(y)*m.radius+m.centerPoint.y;this.addLineTo(f,l),y+=c}return this},i.prototype.close=function(){return this.closed=!0,this},i.prototype.length=function(){var t=this._length;if(!this.closed){var i=this._points[this._points.length-1],n=this._points[0];t+=n.subtract(i).length()}return t},i.prototype.getPoints=function(){return this._points},i.prototype.getPointAtLengthPosition=function(i){if(0>i||i>1)return t.Tools.Error(\"normalized length position should be between 0 and 1.\"),s.Zero();for(var n=i*this.length(),r=0,o=0;o<this._points.length;o++){var e=(o+1)%this._points.length,h=this._points[o],a=this._points[e],u=a.subtract(h),m=u.length()+r;if(n>=r&&m>=n){var c=u.normalize(),y=n-r;return new s(h.x+c.x*y,h.y+c.y*y)}r=m}return t.Tools.Error(\"internal error\"),s.Zero()},i.StartingAt=function(t,n){return new i(t,n)},i}();t.Path2=d;var g=function(){function i(t,i,n){this.path=t,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array;for(var r=0;r<t.length;r++)this._curve[r]=t[r].clone();this._raw=n||!1,this._compute(i)}return i.prototype.getCurve=function(){return this._curve},i.prototype.getTangents=function(){return this._tangents},i.prototype.getNormals=function(){return this._normals},i.prototype.getBinormals=function(){return this._binormals},i.prototype.getDistances=function(){return this._distances},i.prototype.update=function(t,i){for(var n=0;n<t.length;n++)this._curve[n].x=t[n].x,this._curve[n].y=t[n].y,this._curve[n].z=t[n].z;return this._compute(i),this},i.prototype._compute=function(t){var i=this._curve.length;this._tangents[0]=this._getFirstNonNullVector(0),this._raw||this._tangents[0].normalize(),this._tangents[i-1]=this._curve[i-1].subtract(this._curve[i-2]),this._raw||this._tangents[i-1].normalize();var n=this._tangents[0],r=this._normalVector(this._curve[0],n,t);this._normals[0]=r,this._raw||this._normals[0].normalize(),this._binormals[0]=e.Cross(n,this._normals[0]),this._raw||this._binormals[0].normalize(),this._distances[0]=0;for(var o,s,h,a,u=1;i>u;u++)o=this._getLastNonNullVector(u),i-1>u&&(s=this._getFirstNonNullVector(u),this._tangents[u]=o.add(s),this._tangents[u].normalize()),this._distances[u]=this._distances[u-1]+o.length(),h=this._tangents[u],a=this._binormals[u-1],this._normals[u]=e.Cross(a,h),this._raw||this._normals[u].normalize(),this._binormals[u]=e.Cross(h,this._normals[u]),this._raw||this._binormals[u].normalize()},i.prototype._getFirstNonNullVector=function(t){for(var i=1,n=this._curve[t+i].subtract(this._curve[t]);0===n.length()&&t+i+1<this._curve.length;)i++,n=this._curve[t+i].subtract(this._curve[t]);return n},i.prototype._getLastNonNullVector=function(t){for(var i=1,n=this._curve[t].subtract(this._curve[t-i]);0===n.length()&&t>i+1;)i++,n=this._curve[t].subtract(this._curve[t-i]);return n},i.prototype._normalVector=function(i,n,r){var o;if(void 0===r||null===r){var s;t.Tools.WithinEpsilon(n.y,1,t.Engine.Epsilon)?t.Tools.WithinEpsilon(n.x,1,t.Engine.Epsilon)?t.Tools.WithinEpsilon(n.z,1,t.Engine.Epsilon)||(s=new e(0,0,1)):s=new e(1,0,0):s=new e(0,-1,0),o=e.Cross(n,s)}else o=e.Cross(n,r),e.CrossToRef(o,n,o);return o.normalize(),o},i}();t.Path3D=g;var T=function(){function t(t){this._length=0,this._points=t,this._length=this._computeLength(t)}return t.CreateQuadraticBezier=function(i,n,r,o){o=o>2?o:3;for(var s=new Array,h=function(t,i,n,r){var o=(1-t)*(1-t)*i+2*t*(1-t)*n+t*t*r;return o},a=0;o>=a;a++)s.push(new e(h(a/o,i.x,n.x,r.x),h(a/o,i.y,n.y,r.y),h(a/o,i.z,n.z,r.z)));return new t(s)},t.CreateCubicBezier=function(i,n,r,o,s){s=s>3?s:4;for(var h=new Array,a=function(t,i,n,r,o){var s=(1-t)*(1-t)*(1-t)*i+3*t*(1-t)*(1-t)*n+3*t*t*(1-t)*r+t*t*t*o;return s},u=0;s>=u;u++)h.push(new e(a(u/s,i.x,n.x,r.x,o.x),a(u/s,i.y,n.y,r.y,o.y),a(u/s,i.z,n.z,r.z,o.z)));return new t(h)},t.CreateHermiteSpline=function(i,n,r,o,s){for(var h=new Array,a=1/s,u=0;s>=u;u++)h.push(e.Hermite(i,n,r,o,u*a));return new t(h)},t.prototype.getPoints=function(){return this._points},t.prototype.length=function(){return this._length},t.prototype[\"continue\"]=function(i){for(var n=this._points[this._points.length-1],r=this._points.slice(),o=i.getPoints(),s=1;s<o.length;s++)r.push(o[s].subtract(o[0]).add(n));var e=new t(r);return e},t.prototype._computeLength=function(t){for(var i=0,n=1;n<t.length;n++)i+=t[n].subtract(t[n-1]).length();return i},t}();t.Curve3=T;var R=function(){function t(){this.L00=e.Zero(),this.L1_1=e.Zero(),this.L10=e.Zero(),this.L11=e.Zero(),this.L2_2=e.Zero(),this.L2_1=e.Zero(),this.L20=e.Zero(),this.L21=e.Zero(),this.L22=e.Zero()}return t.prototype.addLight=function(t,i,n){var r=new e(i.r,i.g,i.b),o=r.scale(n);this.L00=this.L00.add(o.scale(.282095)),this.L1_1=this.L1_1.add(o.scale(.488603*t.y)),this.L10=this.L10.add(o.scale(.488603*t.z)),this.L11=this.L11.add(o.scale(.488603*t.x)),this.L2_2=this.L2_2.add(o.scale(1.092548*t.x*t.y)),this.L2_1=this.L2_1.add(o.scale(1.092548*t.y*t.z)),this.L21=this.L21.add(o.scale(1.092548*t.x*t.z)),this.L20=this.L20.add(o.scale(.315392*(3*t.z*t.z-1))),this.L22=this.L22.add(o.scale(.546274*(t.x*t.x-t.y*t.y)))},t.prototype.scale=function(t){this.L00=this.L00.scale(t),this.L1_1=this.L1_1.scale(t),this.L10=this.L10.scale(t),this.L11=this.L11.scale(t),this.L2_2=this.L2_2.scale(t),this.L2_1=this.L2_1.scale(t),this.L20=this.L20.scale(t),this.L21=this.L21.scale(t),this.L22=this.L22.scale(t)},t}();t.SphericalHarmonics=R;var _=function(){function t(){this.x=e.Zero(),this.y=e.Zero(),this.z=e.Zero(),this.xx=e.Zero(),this.yy=e.Zero(),this.zz=e.Zero(),this.xy=e.Zero(),this.yz=e.Zero(),this.zx=e.Zero()}return t.prototype.addAmbient=function(t){var i=new e(t.r,t.g,t.b);this.xx=this.xx.add(i),this.yy=this.yy.add(i),this.zz=this.zz.add(i)},t.getSphericalPolynomialFromHarmonics=function(i){var n=new t;return n.x=i.L11.scale(1.02333),n.y=i.L1_1.scale(1.02333),n.z=i.L10.scale(1.02333),n.xx=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).add(i.L22.scale(.429043)),n.yy=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).subtract(i.L22.scale(.429043)),n.zz=i.L00.scale(.886277).add(i.L20.scale(.495417)),n.yz=i.L2_1.scale(.858086),n.zx=i.L21.scale(.858086),n.xy=i.L2_2.scale(.858086),n},t}();t.SphericalPolynomial=_;var M=function(){function t(t,i){void 0===t&&(t=e.Zero()),void 0===i&&(i=e.Up()),this.position=t,this.normal=i}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone())},t}();t.PositionNormalVertex=M;var F=function(){function t(t,i,n){void 0===t&&(t=e.Zero()),void 0===i&&(i=e.Up()),void 0===n&&(n=s.Zero()),this.position=t,this.normal=i,this.uv=n}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone(),this.uv.clone())},t}();t.PositionNormalTextureVertex=F;var b=function(){function t(){}return t.Vector2=[s.Zero(),s.Zero(),s.Zero()],t.Vector3=[e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero()],t.Vector4=[h.Zero(),h.Zero(),h.Zero()],t.Quaternion=[new a(0,0,0,0)],t.Matrix=[u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero()],t}();t.Tmp=b}(BABYLON||(BABYLON={}));";
  38674. BABYLON.Effect.IncludesShadersStore={"bonesDeclaration":"#if NUM_BONE_INFLUENCERS > 0\r\n\tuniform mat4 mBones[BonesPerMesh];\r\n\r\n\tattribute vec4 matricesIndices;\r\n\tattribute vec4 matricesWeights;\r\n\t#if NUM_BONE_INFLUENCERS > 4\r\n\t\tattribute vec4 matricesIndicesExtra;\r\n\t\tattribute vec4 matricesWeightsExtra;\r\n\t#endif\r\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS > 0\r\n\tmat4 influence;\r\n\tinfluence = mBones[int(matricesIndices[0])] * matricesWeights[0];\r\n\r\n\t#if NUM_BONE_INFLUENCERS > 1\r\n\t\tinfluence += mBones[int(matricesIndices[1])] * matricesWeights[1];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 2\r\n\t\tinfluence += mBones[int(matricesIndices[2])] * matricesWeights[2];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 3\r\n\t\tinfluence += mBones[int(matricesIndices[3])] * matricesWeights[3];\r\n\t#endif\t\r\n\r\n\t#if NUM_BONE_INFLUENCERS > 4\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[0])] * matricesWeightsExtra[0];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 5\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[1])] * matricesWeightsExtra[1];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 6\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[2])] * matricesWeightsExtra[2];\r\n\t#endif\t\r\n\t#if NUM_BONE_INFLUENCERS > 7\r\n\t\tinfluence += mBones[int(matricesIndicesExtra[3])] * matricesWeightsExtra[3];\r\n\t#endif\t\r\n\r\n\tfinalWorld = finalWorld * influence;\r\n#endif","fogFragment":"#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tcolor.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\r\n#endif","fogFragmentDeclaration":"#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn clamp(fogCoeff, 0.0, 1.0);\r\n}\r\n#endif","fogVertex":"#ifdef FOG\r\nfFogDistance = (view * worldPos).z;\r\n#endif","fogVertexDeclaration":"#ifdef FOG\r\n\tvarying float fFogDistance;\r\n#endif","instancesDeclaration":"#ifdef INSTANCES\r\n\tattribute vec4 world0;\r\n\tattribute vec4 world1;\r\n\tattribute vec4 world2;\r\n\tattribute vec4 world3;\r\n#else\r\n\tuniform mat4 world;\r\n#endif","instancesVertex":"#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif","light0Fragment":"#ifdef LIGHT0\r\n\t#ifndef SPECULARTERM\r\n\t\tvec3 vLightSpecular0 = vec3(0.0);\r\n\t#endif\r\n\t#ifdef SPOTLIGHT0\r\n\t\tlightingInfo info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a, glossiness);\r\n\t#endif\r\n\t#ifdef HEMILIGHT0\r\n\t\tlightingInfo info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightGround0, glossiness);\r\n\t#endif\r\n\t#if defined(POINTLIGHT0) || defined(DIRLIGHT0)\r\n\t\tlightingInfo info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a, glossiness);\r\n\t#endif\r\n\t#ifdef SHADOW0\r\n\t\t#ifdef SHADOWVSM0\r\n\t\t\tshadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0, shadowsInfo0.z, shadowsInfo0.x);\r\n\t\t#else\r\n\t\t#ifdef SHADOWPCF0\r\n\t\t\t#if defined(POINTLIGHT0)\r\n\t\t\t\tshadow = computeShadowWithPCFCube(vLightData0.xyz, shadowSampler0, shadowsInfo0.y, shadowsInfo0.z, shadowsInfo0.x);\r\n\t\t\t#else\r\n\t\t\t\tshadow = computeShadowWithPCF(vPositionFromLight0, shadowSampler0, shadowsInfo0.y, shadowsInfo0.z, shadowsInfo0.x);\r\n\t\t\t#endif\r\n\t\t#else\r\n\t\t\t#if defined(POINTLIGHT0)\r\n\t\t\t\tshadow = computeShadowCube(vLightData0.xyz, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\r\n\t\t\t#else\r\n\t\t\t\tshadow = computeShadow(vPositionFromLight0, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\r\n\t\t\t#endif\r\n\t\t#endif\r\n\t#endif\r\n\t#else\r\n\t\tshadow = 1.;\r\n\t#endif\r\n\t\tdiffuseBase += info.diffuse * shadow;\r\n\t#ifdef SPECULARTERM\r\n\t\tspecularBase += info.specular * shadow;\r\n\t#endif\r\n#endif","light0FragmentDeclaration":"#ifdef LIGHT0\r\n\tuniform vec4 vLightData0;\r\n\tuniform vec4 vLightDiffuse0;\r\n\t#ifdef SPECULARTERM\r\n\t\tuniform vec3 vLightSpecular0;\r\n\t#endif\r\n\t#ifdef SHADOW0\r\n\t\t#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\r\n\t\t\tvarying vec4 vPositionFromLight0;\r\n\t\t\tuniform sampler2D shadowSampler0;\r\n\t\t#else\r\n\t\t\tuniform samplerCube shadowSampler0;\r\n\t\t#endif\r\n\t\tuniform vec3 shadowsInfo0;\r\n\t#endif\r\n\t#ifdef SPOTLIGHT0\r\n\t\tuniform vec4 vLightDirection0;\r\n\t#endif\r\n\t#ifdef HEMILIGHT0\r\n\t\tuniform vec3 vLightGround0;\r\n\t#endif\r\n#endif","light1Fragment":"#ifdef LIGHT1\r\n\t#ifndef SPECULARTERM\r\n\t\tvec3 vLightSpecular1 = vec3(0.0);\r\n\t#endif\r\n\t#ifdef SPOTLIGHT1\r\n\t\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a, glossiness);\r\n\t#endif\r\n\t#ifdef HEMILIGHT1\r\n\t\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightGround1, glossiness);\r\n\t#endif\r\n\t#if defined(POINTLIGHT1) || defined(DIRLIGHT1)\r\n\t\tinfo = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a, glossiness);\r\n\t#endif\r\n\t#ifdef SHADOW1\r\n\t\t#ifdef SHADOWVSM1\r\n\t\t\tshadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1, shadowsInfo1.z, shadowsInfo1.x);\r\n\t\t#else\r\n\t\t\t#ifdef SHADOWPCF1\r\n\t\t\t\t#if defined(POINTLIGHT1)\r\n\t\t\t\t\tshadow = computeShadowWithPCFCube(vLightData1.xyz, shadowSampler1, shadowsInfo1.y, shadowsInfo1.z, shadowsInfo1.x);\r\n\t\t\t\t#else\r\n\t\t\t\t\tshadow = computeShadowWithPCF(vPositionFromLight1, shadowSampler1, shadowsInfo1.y, shadowsInfo1.z, shadowsInfo1.x);\r\n\t\t\t\t#endif\r\n\t\t\t#else\r\n\t\t\t\t#if defined(POINTLIGHT1)\r\n\t\t\t\t\tshadow = computeShadowCube(vLightData1.xyz, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\r\n\t\t\t\t#else\r\n\t\t\t\t\tshadow = computeShadow(vPositionFromLight1, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\r\n\t\t\t\t#endif\r\n\t\t\t#endif\r\n\t\t#endif\r\n\t\t#else\r\n\t\t\tshadow = 1.;\r\n\t#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n\t#ifdef SPECULARTERM\r\n\t\tspecularBase += info.specular * shadow;\r\n\t#endif\r\n#endif","light1FragmentDeclaration":"#ifdef LIGHT1\r\n\tuniform vec4 vLightData1;\r\n\tuniform vec4 vLightDiffuse1;\r\n\t#ifdef SPECULARTERM\r\n\t\tuniform vec3 vLightSpecular1;\r\n\t#endif\r\n\t#ifdef SHADOW1\r\n\t\t#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\r\n\t\t\tvarying vec4 vPositionFromLight1;\r\n\t\t\tuniform sampler2D shadowSampler1;\r\n\t\t#else\r\n\t\t\tuniform samplerCube shadowSampler1;\r\n\t\t#endif\r\n\t\tuniform vec3 shadowsInfo1;\r\n\t#endif\r\n\t#ifdef SPOTLIGHT1\r\n\t\tuniform vec4 vLightDirection1;\r\n\t#endif\r\n\t#ifdef HEMILIGHT1\r\n\t\tuniform vec3 vLightGround1;\r\n\t#endif\r\n#endif","light2Fragment":"#ifdef LIGHT2\r\n\t#ifndef SPECULARTERM\r\n\t\tvec3 vLightSpecular2 = vec3(0.0);\r\n\t#endif\r\n\t#ifdef SPOTLIGHT2\r\n\t\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a, glossiness);\r\n\t#endif\r\n\t#ifdef HEMILIGHT2\r\n\t\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightGround2, glossiness);\r\n\t#endif\r\n\t#if defined(POINTLIGHT2) || defined(DIRLIGHT2)\r\n\t\tinfo = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a, glossiness);\r\n\t#endif\r\n\t#ifdef SHADOW2\r\n\t\t#ifdef SHADOWVSM2\r\n\t\t\tshadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2, shadowsInfo2.z, shadowsInfo2.x);\r\n\t\t#else\r\n\t\t\t#ifdef SHADOWPCF2\r\n\t\t\t\t#if defined(POINTLIGHT2)\r\n\t\t\t\t\tshadow = computeShadowWithPCFCube(vLightData2.xyz, shadowSampler2, shadowsInfo2.y, shadowsInfo2.z, shadowsInfo2.x);\r\n\t\t\t\t#else\r\n\t\t\t\t\tshadow = computeShadowWithPCF(vPositionFromLight2, shadowSampler2, shadowsInfo2.y, shadowsInfo2.z, shadowsInfo2.x);\r\n\t\t\t\t#endif\r\n\t\t\t#else\r\n\t\t\t\t#if defined(POINTLIGHT2)\r\n\t\t\t\t\tshadow = computeShadowCube(vLightData2.xyz, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\r\n\t\t\t\t#else\r\n\t\t\t\t\tshadow = computeShadow(vPositionFromLight2, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\r\n\t\t\t\t#endif\r\n\t\t\t#endif\t\r\n\t\t#endif\t\r\n\t\t#else\r\n\t\tshadow = 1.;\r\n\t#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n\t#ifdef SPECULARTERM\r\n\t\tspecularBase += info.specular * shadow;\r\n\t#endif\r\n#endif","light2FragmentDeclaration":"#ifdef LIGHT2\r\n\tuniform vec4 vLightData2;\r\n\tuniform vec4 vLightDiffuse2;\r\n\t#ifdef SPECULARTERM\r\n\t\tuniform vec3 vLightSpecular2;\r\n\t#endif\r\n\t#ifdef SHADOW2\r\n\t\t#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\r\n\t\t\tvarying vec4 vPositionFromLight2;\r\n\t\t\tuniform sampler2D shadowSampler2;\r\n\t\t#else\r\n\t\t\tuniform samplerCube shadowSampler2;\r\n\t\t#endif\r\n\t\tuniform vec3 shadowsInfo2;\r\n\t#endif\r\n\t#ifdef SPOTLIGHT2\r\n\t\tuniform vec4 vLightDirection2;\r\n\t#endif\r\n\t#ifdef HEMILIGHT2\r\n\t\tuniform vec3 vLightGround2;\r\n\t#endif\r\n#endif","light3Fragment":"#ifdef LIGHT3\r\n\t#ifndef SPECULARTERM\r\n\t\tvec3 vLightSpecular3 = vec3(0.0);\r\n\t#endif\r\n\t#ifdef SPOTLIGHT3\r\n\t\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a, glossiness);\r\n\t#endif\r\n\t#ifdef HEMILIGHT3\r\n\t\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightGround3, glossiness);\r\n\t#endif\r\n\t#if defined(POINTLIGHT3) || defined(DIRLIGHT3)\r\n\t\tinfo = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a, glossiness);\r\n\t#endif\r\n\t#ifdef SHADOW3\r\n\t\t#ifdef SHADOWVSM3\r\n\t\t\tshadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3, shadowsInfo3.z, shadowsInfo3.x);\r\n\t\t#else\r\n\t\t\t#ifdef SHADOWPCF3\r\n\t\t\t\t#if defined(POINTLIGHT3)\r\n\t\t\t\t\tshadow = computeShadowWithPCFCube(vLightData3.xyz, shadowSampler3, shadowsInfo3.y, shadowsInfo3.z, shadowsInfo3.x);\r\n\t\t\t\t#else\r\n\t\t\t\t\tshadow = computeShadowWithPCF(vPositionFromLight3, shadowSampler3, shadowsInfo3.y, shadowsInfo3.z, shadowsInfo3.x);\r\n\t\t\t\t#endif\r\n\t\t\t#else\r\n\t\t\t\t#if defined(POINTLIGHT3)\r\n\t\t\t\t\tshadow = computeShadowCube(vLightData3.xyz, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\r\n\t\t\t\t#else\r\n\t\t\t\t\tshadow = computeShadow(vPositionFromLight3, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\r\n\t\t\t\t#endif\r\n\t\t\t#endif\t\r\n\t\t#endif\t\r\n\t#else\r\n\t\tshadow = 1.;\r\n\t#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n\t#ifdef SPECULARTERM\r\n\t\tspecularBase += info.specular * shadow;\r\n\t#endif\r\n#endif","light3FragmentDeclaration":"#ifdef LIGHT3\r\n\tuniform vec4 vLightData3;\r\n\tuniform vec4 vLightDiffuse3;\r\n\t#ifdef SPECULARTERM\r\n\t\tuniform vec3 vLightSpecular3;\r\n\t#endif\r\n\t#ifdef SHADOW3\r\n\t\t#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\r\n\t\t\tvarying vec4 vPositionFromLight3;\r\n\t\t\tuniform sampler2D shadowSampler3;\r\n\t\t#else\r\n\t\t\tuniform samplerCube shadowSampler3;\r\n\t\t#endif\r\n\t\tuniform vec3 shadowsInfo3;\r\n\t#endif\r\n\t#ifdef SPOTLIGHT3\r\n\t\tuniform vec4 vLightDirection3;\r\n\t#endif\r\n\t#ifdef HEMILIGHT3\r\n\t\tuniform vec3 vLightGround3;\r\n\t#endif\r\n#endif","lightsFragmentFunctions":"// Light Computing\r\nstruct lightingInfo\r\n{\r\n\tvec3 diffuse;\r\n#ifdef SPECULARTERM\r\n\tvec3 specular;\r\n#endif\r\n};\r\n\r\nlightingInfo computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, float range, float glossiness) {\r\n\tlightingInfo result;\r\n\r\n\tvec3 lightVectorW;\r\n\tfloat attenuation = 1.0;\r\n\tif (lightData.w == 0.)\r\n\t{\r\n\t\tvec3 direction = lightData.xyz - vPositionW;\r\n\r\n\t\tattenuation = max(0., 1.0 - length(direction) / range);\r\n\t\tlightVectorW = normalize(direction);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tlightVectorW = normalize(-lightData.xyz);\r\n\t}\r\n\r\n\t// diffuse\r\n\tfloat ndl = max(0., dot(vNormal, lightVectorW));\r\n\tresult.diffuse = ndl * diffuseColor * attenuation;\r\n\r\n#ifdef SPECULARTERM\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightVectorW);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = pow(specComp, max(1., glossiness));\r\n\r\n\tresult.specular = specComp * specularColor * attenuation;\r\n#endif\r\n\treturn result;\r\n}\r\n\r\nlightingInfo computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec3 diffuseColor, vec3 specularColor, float range, float glossiness) {\r\n\tlightingInfo result;\r\n\r\n\tvec3 direction = lightData.xyz - vPositionW;\r\n\tvec3 lightVectorW = normalize(direction);\r\n\tfloat attenuation = max(0., 1.0 - length(direction) / range);\r\n\r\n\t// diffuse\r\n\tfloat cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\r\n\r\n\tif (cosAngle >= lightDirection.w)\r\n\t{\r\n\t\tcosAngle = max(0., pow(cosAngle, lightData.w));\r\n\t\tattenuation *= cosAngle;\r\n\r\n\t\t// Diffuse\r\n\t\tfloat ndl = max(0., dot(vNormal, -lightDirection.xyz));\r\n\t\tresult.diffuse = ndl * diffuseColor * attenuation;\r\n\r\n#ifdef SPECULARTERM\r\n\t\t// Specular\r\n\t\tvec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\r\n\t\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\t\tspecComp = pow(specComp, max(1., glossiness));\r\n\r\n\t\tresult.specular = specComp * specularColor * attenuation;\r\n#endif\r\n\t\treturn result;\r\n\t}\r\n\r\n\tresult.diffuse = vec3(0.);\r\n#ifdef SPECULARTERM\r\n\tresult.specular = vec3(0.);\r\n#endif\r\n\r\n\treturn result;\r\n}\r\n\r\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, vec3 groundColor, float glossiness) {\r\n\tlightingInfo result;\r\n\r\n\t// Diffuse\r\n\tfloat ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\r\n\tresult.diffuse = mix(groundColor, diffuseColor, ndl);\r\n\r\n#ifdef SPECULARTERM\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightData.xyz);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = pow(specComp, max(1., glossiness));\r\n\r\n\tresult.specular = specComp * specularColor;\r\n#endif\r\n\r\n\treturn result;\r\n}\r\n","shadowsFragmentFunctions":"#ifdef SHADOWS\r\n\tfloat unpack(vec4 color)\r\n\t{\r\n\t\tconst vec4 bit_shift = vec4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0);\r\n\t\treturn dot(color, bit_shift);\r\n\t}\r\n\r\n\t#if defined(POINTLIGHT0) || defined(POINTLIGHT1) || defined(POINTLIGHT2) || defined(POINTLIGHT3)\r\n\t\tuniform vec2 depthValues;\r\n\r\n\t\tfloat computeShadowCube(vec3 lightPosition, samplerCube shadowSampler, float darkness, float bias)\r\n\t\t{\r\n\t\t\tvec3 directionToLight = vPositionW - lightPosition;\r\n\t\t\tfloat depth = length(directionToLight);\r\n\t\t\tdepth = (depth - depthValues.x) / (depthValues.y - depthValues.x);\r\n\t\t\tdepth = clamp(depth, 0., 1.0);\r\n\r\n\t\t\tdirectionToLight = normalize(directionToLight);\r\n\t\t\tdirectionToLight.y = -directionToLight.y;\r\n\r\n\t\t\tfloat shadow = unpack(textureCube(shadowSampler, directionToLight)) + bias;\r\n\r\n\t\t\tif (depth > shadow)\r\n\t\t\t{\r\n\t\t\t\treturn darkness;\r\n\t\t\t}\r\n\t\t\treturn 1.0;\r\n\t\t}\r\n\r\n\t\tfloat computeShadowWithPCFCube(vec3 lightPosition, samplerCube shadowSampler, float mapSize, float bias, float darkness)\r\n\t\t{\r\n\t\t\tvec3 directionToLight = vPositionW - lightPosition;\r\n\t\t\tfloat depth = length(directionToLight);\r\n\r\n\t\t\tdepth = (depth - depthValues.x) / (depthValues.y - depthValues.x);\r\n\t\t\tdepth = clamp(depth, 0., 1.0);\r\n\r\n\t\t\tdirectionToLight = normalize(directionToLight);\r\n\t\t\tdirectionToLight.y = -directionToLight.y;\r\n\r\n\t\t\tfloat visibility = 1.;\r\n\r\n\t\t\tvec3 poissonDisk[4];\r\n\t\t\tpoissonDisk[0] = vec3(-1.0, 1.0, -1.0);\r\n\t\t\tpoissonDisk[1] = vec3(1.0, -1.0, -1.0);\r\n\t\t\tpoissonDisk[2] = vec3(-1.0, -1.0, -1.0);\r\n\t\t\tpoissonDisk[3] = vec3(1.0, -1.0, 1.0);\r\n\r\n\t\t\t// Poisson Sampling\r\n\t\t\tfloat biasedDepth = depth - bias;\r\n\r\n\t\t\tif (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[0] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\t\t\tif (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[1] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\t\t\tif (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[2] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\t\t\tif (unpack(textureCube(shadowSampler, directionToLight + poissonDisk[3] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\r\n\t\t\treturn min(1.0, visibility + darkness);\r\n\t\t}\r\n\t#endif\r\n\r\n\t#if defined(SPOTLIGHT0) || defined(SPOTLIGHT1) || defined(SPOTLIGHT2) || defined(SPOTLIGHT3) || defined(DIRLIGHT0) || defined(DIRLIGHT1) || defined(DIRLIGHT2) || defined(DIRLIGHT3)\r\n\t\tfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler, float darkness, float bias)\r\n\t\t{\r\n\t\t\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\t\t\tdepth = 0.5 * depth + vec3(0.5);\r\n\t\t\tvec2 uv = depth.xy;\r\n\r\n\t\t\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t\t\t{\r\n\t\t\t\treturn 1.0;\r\n\t\t\t}\r\n\r\n\t\t\tfloat shadow = unpack(texture2D(shadowSampler, uv)) + bias;\r\n\r\n\t\t\tif (depth.z > shadow)\r\n\t\t\t{\r\n\t\t\t\treturn darkness;\r\n\t\t\t}\r\n\t\t\treturn 1.;\r\n\t\t}\r\n\r\n\t\tfloat computeShadowWithPCF(vec4 vPositionFromLight, sampler2D shadowSampler, float mapSize, float bias, float darkness)\r\n\t\t{\r\n\t\t\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\t\t\tdepth = 0.5 * depth + vec3(0.5);\r\n\t\t\tvec2 uv = depth.xy;\r\n\r\n\t\t\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t\t\t{\r\n\t\t\t\treturn 1.0;\r\n\t\t\t}\r\n\r\n\t\t\tfloat visibility = 1.;\r\n\r\n\t\t\tvec2 poissonDisk[4];\r\n\t\t\tpoissonDisk[0] = vec2(-0.94201624, -0.39906216);\r\n\t\t\tpoissonDisk[1] = vec2(0.94558609, -0.76890725);\r\n\t\t\tpoissonDisk[2] = vec2(-0.094184101, -0.92938870);\r\n\t\t\tpoissonDisk[3] = vec2(0.34495938, 0.29387760);\r\n\r\n\t\t\t// Poisson Sampling\r\n\t\t\tfloat biasedDepth = depth.z - bias;\r\n\r\n\t\t\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[0] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\t\t\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[1] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\t\t\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[2] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\t\t\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[3] * mapSize)) < biasedDepth) visibility -= 0.25;\r\n\r\n\t\t\treturn min(1.0, visibility + darkness);\r\n\t\t}\r\n\r\n\t\t// Thanks to http://devmaster.net/\r\n\t\tfloat unpackHalf(vec2 color)\r\n\t\t{\r\n\t\t\treturn color.x + (color.y / 255.0);\r\n\t\t}\r\n\r\n\t\tfloat linstep(float low, float high, float v) {\r\n\t\t\treturn clamp((v - low) / (high - low), 0.0, 1.0);\r\n\t\t}\r\n\r\n\t\tfloat ChebychevInequality(vec2 moments, float compare, float bias)\r\n\t\t{\r\n\t\t\tfloat p = smoothstep(compare - bias, compare, moments.x);\r\n\t\t\tfloat variance = max(moments.y - moments.x * moments.x, 0.02);\r\n\t\t\tfloat d = compare - moments.x;\r\n\t\t\tfloat p_max = linstep(0.2, 1.0, variance / (variance + d * d));\r\n\r\n\t\t\treturn clamp(max(p, p_max), 0.0, 1.0);\r\n\t\t}\r\n\r\n\t\tfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler, float bias, float darkness)\r\n\t\t{\r\n\t\t\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\t\t\tdepth = 0.5 * depth + vec3(0.5);\r\n\t\t\tvec2 uv = depth.xy;\r\n\r\n\t\t\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0 || depth.z >= 1.0)\r\n\t\t\t{\r\n\t\t\t\treturn 1.0;\r\n\t\t\t}\r\n\r\n\t\t\tvec4 texel = texture2D(shadowSampler, uv);\r\n\r\n\t\t\tvec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\r\n\t\t\treturn min(1.0, 1.0 - ChebychevInequality(moments, depth.z, bias) + darkness);\r\n\t\t}\r\n\t#endif\r\n#endif","shadowsVertex":"#ifdef SHADOWS\r\n\t#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\r\n\t\tvPositionFromLight0 = lightMatrix0 * worldPos;\r\n\t#endif\r\n\t#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\r\n\t\tvPositionFromLight1 = lightMatrix1 * worldPos;\r\n\t#endif\r\n\t#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\r\n\t\tvPositionFromLight2 = lightMatrix2 * worldPos;\r\n\t#endif\r\n\t#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\r\n\t\tvPositionFromLight3 = lightMatrix3 * worldPos;\r\n\t#endif\r\n#endif","shadowsVertexDeclaration":"#ifdef SHADOWS\r\n\t#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\r\n\t\tuniform mat4 lightMatrix0;\r\n\t\tvarying vec4 vPositionFromLight0;\r\n\t#endif\r\n\t#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\r\n\t\tuniform mat4 lightMatrix1;\r\n\t\tvarying vec4 vPositionFromLight1;\r\n\t#endif\r\n\t#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\r\n\t\tuniform mat4 lightMatrix2;\r\n\t\tvarying vec4 vPositionFromLight2;\r\n\t#endif\r\n\t#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\r\n\t\tuniform mat4 lightMatrix3;\r\n\t\tvarying vec4 vPositionFromLight3;\r\n\t#endif\r\n#endif"};
  38675. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  38676. module.exports = BABYLON;
  38677. };