babylon.max.js 2.0 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468
  1. var __extends = (this && this.__extends) || function (d, b) {
  2. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  3. function __() { this.constructor = d; }
  4. __.prototype = b.prototype;
  5. d.prototype = new __();
  6. };
  7. var BABYLON;
  8. (function (BABYLON) {
  9. BABYLON.ToGammaSpace = 1 / 2.2;
  10. BABYLON.ToLinearSpace = 2.2;
  11. BABYLON.Epsilon = 0.001;
  12. var MathTools = (function () {
  13. function MathTools() {
  14. }
  15. MathTools.WithinEpsilon = function (a, b, epsilon) {
  16. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  17. var num = a - b;
  18. return -epsilon <= num && num <= epsilon;
  19. };
  20. MathTools.ToHex = function (i) {
  21. var str = i.toString(16);
  22. if (i <= 15) {
  23. return ("0" + str).toUpperCase();
  24. }
  25. return str.toUpperCase();
  26. };
  27. // Returns -1 when value is a negative number and
  28. // +1 when value is a positive number.
  29. MathTools.Sign = function (value) {
  30. value = +value; // convert to a number
  31. if (value === 0 || isNaN(value))
  32. return value;
  33. return value > 0 ? 1 : -1;
  34. };
  35. MathTools.Clamp = function (value, min, max) {
  36. if (min === void 0) { min = 0; }
  37. if (max === void 0) { max = 1; }
  38. return Math.min(max, Math.max(min, value));
  39. };
  40. return MathTools;
  41. })();
  42. BABYLON.MathTools = MathTools;
  43. var Color3 = (function () {
  44. function Color3(r, g, b) {
  45. if (r === void 0) { r = 0; }
  46. if (g === void 0) { g = 0; }
  47. if (b === void 0) { b = 0; }
  48. this.r = r;
  49. this.g = g;
  50. this.b = b;
  51. }
  52. Color3.prototype.toString = function () {
  53. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  54. };
  55. // Operators
  56. Color3.prototype.toArray = function (array, index) {
  57. if (index === undefined) {
  58. index = 0;
  59. }
  60. array[index] = this.r;
  61. array[index + 1] = this.g;
  62. array[index + 2] = this.b;
  63. return this;
  64. };
  65. Color3.prototype.toColor4 = function (alpha) {
  66. if (alpha === void 0) { alpha = 1; }
  67. return new Color4(this.r, this.g, this.b, alpha);
  68. };
  69. Color3.prototype.asArray = function () {
  70. var result = [];
  71. this.toArray(result, 0);
  72. return result;
  73. };
  74. Color3.prototype.toLuminance = function () {
  75. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  76. };
  77. Color3.prototype.multiply = function (otherColor) {
  78. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  79. };
  80. Color3.prototype.multiplyToRef = function (otherColor, result) {
  81. result.r = this.r * otherColor.r;
  82. result.g = this.g * otherColor.g;
  83. result.b = this.b * otherColor.b;
  84. return this;
  85. };
  86. Color3.prototype.equals = function (otherColor) {
  87. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  88. };
  89. Color3.prototype.equalsFloats = function (r, g, b) {
  90. return this.r === r && this.g === g && this.b === b;
  91. };
  92. Color3.prototype.scale = function (scale) {
  93. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  94. };
  95. Color3.prototype.scaleToRef = function (scale, result) {
  96. result.r = this.r * scale;
  97. result.g = this.g * scale;
  98. result.b = this.b * scale;
  99. return this;
  100. };
  101. Color3.prototype.add = function (otherColor) {
  102. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  103. };
  104. Color3.prototype.addToRef = function (otherColor, result) {
  105. result.r = this.r + otherColor.r;
  106. result.g = this.g + otherColor.g;
  107. result.b = this.b + otherColor.b;
  108. return this;
  109. };
  110. Color3.prototype.subtract = function (otherColor) {
  111. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  112. };
  113. Color3.prototype.subtractToRef = function (otherColor, result) {
  114. result.r = this.r - otherColor.r;
  115. result.g = this.g - otherColor.g;
  116. result.b = this.b - otherColor.b;
  117. return this;
  118. };
  119. Color3.prototype.clone = function () {
  120. return new Color3(this.r, this.g, this.b);
  121. };
  122. Color3.prototype.copyFrom = function (source) {
  123. this.r = source.r;
  124. this.g = source.g;
  125. this.b = source.b;
  126. return this;
  127. };
  128. Color3.prototype.copyFromFloats = function (r, g, b) {
  129. this.r = r;
  130. this.g = g;
  131. this.b = b;
  132. return this;
  133. };
  134. Color3.prototype.toHexString = function () {
  135. var intR = (this.r * 255) | 0;
  136. var intG = (this.g * 255) | 0;
  137. var intB = (this.b * 255) | 0;
  138. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB);
  139. };
  140. Color3.prototype.toLinearSpace = function () {
  141. var convertedColor = new Color3();
  142. this.toLinearSpaceToRef(convertedColor);
  143. return convertedColor;
  144. };
  145. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  146. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  147. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  148. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  149. return this;
  150. };
  151. Color3.prototype.toGammaSpace = function () {
  152. var convertedColor = new Color3();
  153. this.toGammaSpaceToRef(convertedColor);
  154. return convertedColor;
  155. };
  156. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  157. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  158. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  159. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  160. return this;
  161. };
  162. // Statics
  163. Color3.FromHexString = function (hex) {
  164. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  165. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  166. return new Color3(0, 0, 0);
  167. }
  168. var r = parseInt(hex.substring(1, 3), 16);
  169. var g = parseInt(hex.substring(3, 5), 16);
  170. var b = parseInt(hex.substring(5, 7), 16);
  171. return Color3.FromInts(r, g, b);
  172. };
  173. Color3.FromArray = function (array, offset) {
  174. if (offset === void 0) { offset = 0; }
  175. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  176. };
  177. Color3.FromInts = function (r, g, b) {
  178. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  179. };
  180. Color3.Lerp = function (start, end, amount) {
  181. var r = start.r + ((end.r - start.r) * amount);
  182. var g = start.g + ((end.g - start.g) * amount);
  183. var b = start.b + ((end.b - start.b) * amount);
  184. return new Color3(r, g, b);
  185. };
  186. Color3.Red = function () { return new Color3(1, 0, 0); };
  187. Color3.Green = function () { return new Color3(0, 1, 0); };
  188. Color3.Blue = function () { return new Color3(0, 0, 1); };
  189. Color3.Black = function () { return new Color3(0, 0, 0); };
  190. Color3.White = function () { return new Color3(1, 1, 1); };
  191. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  192. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  193. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  194. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  195. return Color3;
  196. })();
  197. BABYLON.Color3 = Color3;
  198. var Color4 = (function () {
  199. function Color4(r, g, b, a) {
  200. this.r = r;
  201. this.g = g;
  202. this.b = b;
  203. this.a = a;
  204. }
  205. // Operators
  206. Color4.prototype.addInPlace = function (right) {
  207. this.r += right.r;
  208. this.g += right.g;
  209. this.b += right.b;
  210. this.a += right.a;
  211. return this;
  212. };
  213. Color4.prototype.asArray = function () {
  214. var result = [];
  215. this.toArray(result, 0);
  216. return result;
  217. };
  218. Color4.prototype.toArray = function (array, index) {
  219. if (index === undefined) {
  220. index = 0;
  221. }
  222. array[index] = this.r;
  223. array[index + 1] = this.g;
  224. array[index + 2] = this.b;
  225. array[index + 3] = this.a;
  226. return this;
  227. };
  228. Color4.prototype.add = function (right) {
  229. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  230. };
  231. Color4.prototype.subtract = function (right) {
  232. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  233. };
  234. Color4.prototype.subtractToRef = function (right, result) {
  235. result.r = this.r - right.r;
  236. result.g = this.g - right.g;
  237. result.b = this.b - right.b;
  238. result.a = this.a - right.a;
  239. return this;
  240. };
  241. Color4.prototype.scale = function (scale) {
  242. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  243. };
  244. Color4.prototype.scaleToRef = function (scale, result) {
  245. result.r = this.r * scale;
  246. result.g = this.g * scale;
  247. result.b = this.b * scale;
  248. result.a = this.a * scale;
  249. return this;
  250. };
  251. Color4.prototype.toString = function () {
  252. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  253. };
  254. Color4.prototype.clone = function () {
  255. return new Color4(this.r, this.g, this.b, this.a);
  256. };
  257. Color4.prototype.copyFrom = function (source) {
  258. this.r = source.r;
  259. this.g = source.g;
  260. this.b = source.b;
  261. this.a = source.a;
  262. return this;
  263. };
  264. Color4.prototype.toHexString = function () {
  265. var intR = (this.r * 255) | 0;
  266. var intG = (this.g * 255) | 0;
  267. var intB = (this.b * 255) | 0;
  268. var intA = (this.a * 255) | 0;
  269. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB) + MathTools.ToHex(intA);
  270. };
  271. // Statics
  272. Color4.FromHexString = function (hex) {
  273. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  274. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  275. return new Color4(0, 0, 0, 0);
  276. }
  277. var r = parseInt(hex.substring(1, 3), 16);
  278. var g = parseInt(hex.substring(3, 5), 16);
  279. var b = parseInt(hex.substring(5, 7), 16);
  280. var a = parseInt(hex.substring(7, 9), 16);
  281. return Color4.FromInts(r, g, b, a);
  282. };
  283. Color4.Lerp = function (left, right, amount) {
  284. var result = new Color4(0, 0, 0, 0);
  285. Color4.LerpToRef(left, right, amount, result);
  286. return result;
  287. };
  288. Color4.LerpToRef = function (left, right, amount, result) {
  289. result.r = left.r + (right.r - left.r) * amount;
  290. result.g = left.g + (right.g - left.g) * amount;
  291. result.b = left.b + (right.b - left.b) * amount;
  292. result.a = left.a + (right.a - left.a) * amount;
  293. };
  294. Color4.FromArray = function (array, offset) {
  295. if (offset === void 0) { offset = 0; }
  296. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  297. };
  298. Color4.FromInts = function (r, g, b, a) {
  299. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  300. };
  301. Color4.CheckColors4 = function (colors, count) {
  302. // Check if color3 was used
  303. if (colors.length === count * 3) {
  304. var colors4 = [];
  305. for (var index = 0; index < colors.length; index += 3) {
  306. var newIndex = (index / 3) * 4;
  307. colors4[newIndex] = colors[index];
  308. colors4[newIndex + 1] = colors[index + 1];
  309. colors4[newIndex + 2] = colors[index + 2];
  310. colors4[newIndex + 3] = 1.0;
  311. }
  312. return colors4;
  313. }
  314. return colors;
  315. };
  316. return Color4;
  317. })();
  318. BABYLON.Color4 = Color4;
  319. var Vector2 = (function () {
  320. function Vector2(x, y) {
  321. this.x = x;
  322. this.y = y;
  323. }
  324. Vector2.prototype.toString = function () {
  325. return "{X: " + this.x + " Y:" + this.y + "}";
  326. };
  327. // Operators
  328. Vector2.prototype.toArray = function (array, index) {
  329. if (index === void 0) { index = 0; }
  330. array[index] = this.x;
  331. array[index + 1] = this.y;
  332. return this;
  333. };
  334. Vector2.prototype.asArray = function () {
  335. var result = [];
  336. this.toArray(result, 0);
  337. return result;
  338. };
  339. Vector2.prototype.copyFrom = function (source) {
  340. this.x = source.x;
  341. this.y = source.y;
  342. return this;
  343. };
  344. Vector2.prototype.copyFromFloats = function (x, y) {
  345. this.x = x;
  346. this.y = y;
  347. return this;
  348. };
  349. Vector2.prototype.add = function (otherVector) {
  350. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  351. };
  352. Vector2.prototype.addVector3 = function (otherVector) {
  353. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  354. };
  355. Vector2.prototype.subtract = function (otherVector) {
  356. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  357. };
  358. Vector2.prototype.subtractInPlace = function (otherVector) {
  359. this.x -= otherVector.x;
  360. this.y -= otherVector.y;
  361. return this;
  362. };
  363. Vector2.prototype.multiplyInPlace = function (otherVector) {
  364. this.x *= otherVector.x;
  365. this.y *= otherVector.y;
  366. return this;
  367. };
  368. Vector2.prototype.multiply = function (otherVector) {
  369. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  370. };
  371. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  372. result.x = this.x * otherVector.x;
  373. result.y = this.y * otherVector.y;
  374. return this;
  375. };
  376. Vector2.prototype.multiplyByFloats = function (x, y) {
  377. return new Vector2(this.x * x, this.y * y);
  378. };
  379. Vector2.prototype.divide = function (otherVector) {
  380. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  381. };
  382. Vector2.prototype.divideToRef = function (otherVector, result) {
  383. result.x = this.x / otherVector.x;
  384. result.y = this.y / otherVector.y;
  385. return this;
  386. };
  387. Vector2.prototype.negate = function () {
  388. return new Vector2(-this.x, -this.y);
  389. };
  390. Vector2.prototype.scaleInPlace = function (scale) {
  391. this.x *= scale;
  392. this.y *= scale;
  393. return this;
  394. };
  395. Vector2.prototype.scale = function (scale) {
  396. return new Vector2(this.x * scale, this.y * scale);
  397. };
  398. Vector2.prototype.equals = function (otherVector) {
  399. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  400. };
  401. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  402. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  403. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon);
  404. };
  405. // Properties
  406. Vector2.prototype.length = function () {
  407. return Math.sqrt(this.x * this.x + this.y * this.y);
  408. };
  409. Vector2.prototype.lengthSquared = function () {
  410. return (this.x * this.x + this.y * this.y);
  411. };
  412. // Methods
  413. Vector2.prototype.normalize = function () {
  414. var len = this.length();
  415. if (len === 0)
  416. return this;
  417. var num = 1.0 / len;
  418. this.x *= num;
  419. this.y *= num;
  420. return this;
  421. };
  422. Vector2.prototype.clone = function () {
  423. return new Vector2(this.x, this.y);
  424. };
  425. // Statics
  426. Vector2.Zero = function () {
  427. return new Vector2(0, 0);
  428. };
  429. Vector2.FromArray = function (array, offset) {
  430. if (offset === void 0) { offset = 0; }
  431. return new Vector2(array[offset], array[offset + 1]);
  432. };
  433. Vector2.FromArrayToRef = function (array, offset, result) {
  434. result.x = array[offset];
  435. result.y = array[offset + 1];
  436. };
  437. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  438. var squared = amount * amount;
  439. var cubed = amount * squared;
  440. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  441. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  442. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  443. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  444. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  445. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  446. return new Vector2(x, y);
  447. };
  448. Vector2.Clamp = function (value, min, max) {
  449. var x = value.x;
  450. x = (x > max.x) ? max.x : x;
  451. x = (x < min.x) ? min.x : x;
  452. var y = value.y;
  453. y = (y > max.y) ? max.y : y;
  454. y = (y < min.y) ? min.y : y;
  455. return new Vector2(x, y);
  456. };
  457. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  458. var squared = amount * amount;
  459. var cubed = amount * squared;
  460. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  461. var part2 = (-2.0 * cubed) + (3.0 * squared);
  462. var part3 = (cubed - (2.0 * squared)) + amount;
  463. var part4 = cubed - squared;
  464. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  465. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  466. return new Vector2(x, y);
  467. };
  468. Vector2.Lerp = function (start, end, amount) {
  469. var x = start.x + ((end.x - start.x) * amount);
  470. var y = start.y + ((end.y - start.y) * amount);
  471. return new Vector2(x, y);
  472. };
  473. Vector2.Dot = function (left, right) {
  474. return left.x * right.x + left.y * right.y;
  475. };
  476. Vector2.Normalize = function (vector) {
  477. var newVector = vector.clone();
  478. newVector.normalize();
  479. return newVector;
  480. };
  481. Vector2.Minimize = function (left, right) {
  482. var x = (left.x < right.x) ? left.x : right.x;
  483. var y = (left.y < right.y) ? left.y : right.y;
  484. return new Vector2(x, y);
  485. };
  486. Vector2.Maximize = function (left, right) {
  487. var x = (left.x > right.x) ? left.x : right.x;
  488. var y = (left.y > right.y) ? left.y : right.y;
  489. return new Vector2(x, y);
  490. };
  491. Vector2.Transform = function (vector, transformation) {
  492. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  493. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  494. return new Vector2(x, y);
  495. };
  496. Vector2.Distance = function (value1, value2) {
  497. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  498. };
  499. Vector2.DistanceSquared = function (value1, value2) {
  500. var x = value1.x - value2.x;
  501. var y = value1.y - value2.y;
  502. return (x * x) + (y * y);
  503. };
  504. return Vector2;
  505. })();
  506. BABYLON.Vector2 = Vector2;
  507. var Vector3 = (function () {
  508. function Vector3(x, y, z) {
  509. this.x = x;
  510. this.y = y;
  511. this.z = z;
  512. }
  513. Vector3.prototype.toString = function () {
  514. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  515. };
  516. // Operators
  517. Vector3.prototype.asArray = function () {
  518. var result = [];
  519. this.toArray(result, 0);
  520. return result;
  521. };
  522. Vector3.prototype.toArray = function (array, index) {
  523. if (index === void 0) { index = 0; }
  524. array[index] = this.x;
  525. array[index + 1] = this.y;
  526. array[index + 2] = this.z;
  527. return this;
  528. };
  529. Vector3.prototype.toQuaternion = function () {
  530. var result = new Quaternion(0, 0, 0, 1);
  531. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  532. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  533. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  534. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  535. var cosy = Math.cos(this.y * 0.5);
  536. var siny = Math.sin(this.y * 0.5);
  537. result.x = coszMinusx * siny;
  538. result.y = -sinzMinusx * siny;
  539. result.z = sinxPlusz * cosy;
  540. result.w = cosxPlusz * cosy;
  541. return result;
  542. };
  543. Vector3.prototype.addInPlace = function (otherVector) {
  544. this.x += otherVector.x;
  545. this.y += otherVector.y;
  546. this.z += otherVector.z;
  547. return this;
  548. };
  549. Vector3.prototype.add = function (otherVector) {
  550. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  551. };
  552. Vector3.prototype.addToRef = function (otherVector, result) {
  553. result.x = this.x + otherVector.x;
  554. result.y = this.y + otherVector.y;
  555. result.z = this.z + otherVector.z;
  556. return this;
  557. };
  558. Vector3.prototype.subtractInPlace = function (otherVector) {
  559. this.x -= otherVector.x;
  560. this.y -= otherVector.y;
  561. this.z -= otherVector.z;
  562. return this;
  563. };
  564. Vector3.prototype.subtract = function (otherVector) {
  565. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  566. };
  567. Vector3.prototype.subtractToRef = function (otherVector, result) {
  568. result.x = this.x - otherVector.x;
  569. result.y = this.y - otherVector.y;
  570. result.z = this.z - otherVector.z;
  571. return this;
  572. };
  573. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  574. return new Vector3(this.x - x, this.y - y, this.z - z);
  575. };
  576. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  577. result.x = this.x - x;
  578. result.y = this.y - y;
  579. result.z = this.z - z;
  580. return this;
  581. };
  582. Vector3.prototype.negate = function () {
  583. return new Vector3(-this.x, -this.y, -this.z);
  584. };
  585. Vector3.prototype.scaleInPlace = function (scale) {
  586. this.x *= scale;
  587. this.y *= scale;
  588. this.z *= scale;
  589. return this;
  590. };
  591. Vector3.prototype.scale = function (scale) {
  592. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  593. };
  594. Vector3.prototype.scaleToRef = function (scale, result) {
  595. result.x = this.x * scale;
  596. result.y = this.y * scale;
  597. result.z = this.z * scale;
  598. };
  599. Vector3.prototype.equals = function (otherVector) {
  600. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  601. };
  602. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  603. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  604. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon) && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon);
  605. };
  606. Vector3.prototype.equalsToFloats = function (x, y, z) {
  607. return this.x === x && this.y === y && this.z === z;
  608. };
  609. Vector3.prototype.multiplyInPlace = function (otherVector) {
  610. this.x *= otherVector.x;
  611. this.y *= otherVector.y;
  612. this.z *= otherVector.z;
  613. return this;
  614. };
  615. Vector3.prototype.multiply = function (otherVector) {
  616. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  617. };
  618. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  619. result.x = this.x * otherVector.x;
  620. result.y = this.y * otherVector.y;
  621. result.z = this.z * otherVector.z;
  622. return this;
  623. };
  624. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  625. return new Vector3(this.x * x, this.y * y, this.z * z);
  626. };
  627. Vector3.prototype.divide = function (otherVector) {
  628. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  629. };
  630. Vector3.prototype.divideToRef = function (otherVector, result) {
  631. result.x = this.x / otherVector.x;
  632. result.y = this.y / otherVector.y;
  633. result.z = this.z / otherVector.z;
  634. return this;
  635. };
  636. Vector3.prototype.MinimizeInPlace = function (other) {
  637. if (other.x < this.x)
  638. this.x = other.x;
  639. if (other.y < this.y)
  640. this.y = other.y;
  641. if (other.z < this.z)
  642. this.z = other.z;
  643. return this;
  644. };
  645. Vector3.prototype.MaximizeInPlace = function (other) {
  646. if (other.x > this.x)
  647. this.x = other.x;
  648. if (other.y > this.y)
  649. this.y = other.y;
  650. if (other.z > this.z)
  651. this.z = other.z;
  652. return this;
  653. };
  654. // Properties
  655. Vector3.prototype.length = function () {
  656. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  657. };
  658. Vector3.prototype.lengthSquared = function () {
  659. return (this.x * this.x + this.y * this.y + this.z * this.z);
  660. };
  661. // Methods
  662. Vector3.prototype.normalize = function () {
  663. var len = this.length();
  664. if (len === 0 || len === 1.0)
  665. return this;
  666. var num = 1.0 / len;
  667. this.x *= num;
  668. this.y *= num;
  669. this.z *= num;
  670. return this;
  671. };
  672. Vector3.prototype.clone = function () {
  673. return new Vector3(this.x, this.y, this.z);
  674. };
  675. Vector3.prototype.copyFrom = function (source) {
  676. this.x = source.x;
  677. this.y = source.y;
  678. this.z = source.z;
  679. return this;
  680. };
  681. Vector3.prototype.copyFromFloats = function (x, y, z) {
  682. this.x = x;
  683. this.y = y;
  684. this.z = z;
  685. return this;
  686. };
  687. // Statics
  688. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  689. var d0 = Vector3.Dot(vector0, axis) - size;
  690. var d1 = Vector3.Dot(vector1, axis) - size;
  691. var s = d0 / (d0 - d1);
  692. return s;
  693. };
  694. Vector3.FromArray = function (array, offset) {
  695. if (!offset) {
  696. offset = 0;
  697. }
  698. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  699. };
  700. Vector3.FromFloatArray = function (array, offset) {
  701. if (!offset) {
  702. offset = 0;
  703. }
  704. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  705. };
  706. Vector3.FromArrayToRef = function (array, offset, result) {
  707. result.x = array[offset];
  708. result.y = array[offset + 1];
  709. result.z = array[offset + 2];
  710. };
  711. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  712. result.x = array[offset];
  713. result.y = array[offset + 1];
  714. result.z = array[offset + 2];
  715. };
  716. Vector3.FromFloatsToRef = function (x, y, z, result) {
  717. result.x = x;
  718. result.y = y;
  719. result.z = z;
  720. };
  721. Vector3.Zero = function () {
  722. return new Vector3(0, 0, 0);
  723. };
  724. Vector3.Up = function () {
  725. return new Vector3(0, 1.0, 0);
  726. };
  727. Vector3.TransformCoordinates = function (vector, transformation) {
  728. var result = Vector3.Zero();
  729. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  730. return result;
  731. };
  732. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  733. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  734. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  735. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  736. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  737. result.x = x / w;
  738. result.y = y / w;
  739. result.z = z / w;
  740. };
  741. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  742. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  743. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  744. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  745. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  746. result.x = rx / rw;
  747. result.y = ry / rw;
  748. result.z = rz / rw;
  749. };
  750. Vector3.TransformNormal = function (vector, transformation) {
  751. var result = Vector3.Zero();
  752. Vector3.TransformNormalToRef(vector, transformation, result);
  753. return result;
  754. };
  755. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  756. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  757. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  758. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  759. };
  760. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  761. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  762. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  763. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  764. };
  765. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  766. var squared = amount * amount;
  767. var cubed = amount * squared;
  768. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  769. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  770. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  771. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  772. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  773. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  774. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  775. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  776. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  777. return new Vector3(x, y, z);
  778. };
  779. Vector3.Clamp = function (value, min, max) {
  780. var x = value.x;
  781. x = (x > max.x) ? max.x : x;
  782. x = (x < min.x) ? min.x : x;
  783. var y = value.y;
  784. y = (y > max.y) ? max.y : y;
  785. y = (y < min.y) ? min.y : y;
  786. var z = value.z;
  787. z = (z > max.z) ? max.z : z;
  788. z = (z < min.z) ? min.z : z;
  789. return new Vector3(x, y, z);
  790. };
  791. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  792. var squared = amount * amount;
  793. var cubed = amount * squared;
  794. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  795. var part2 = (-2.0 * cubed) + (3.0 * squared);
  796. var part3 = (cubed - (2.0 * squared)) + amount;
  797. var part4 = cubed - squared;
  798. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  799. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  800. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  801. return new Vector3(x, y, z);
  802. };
  803. Vector3.Lerp = function (start, end, amount) {
  804. var x = start.x + ((end.x - start.x) * amount);
  805. var y = start.y + ((end.y - start.y) * amount);
  806. var z = start.z + ((end.z - start.z) * amount);
  807. return new Vector3(x, y, z);
  808. };
  809. Vector3.Dot = function (left, right) {
  810. return (left.x * right.x + left.y * right.y + left.z * right.z);
  811. };
  812. Vector3.Cross = function (left, right) {
  813. var result = Vector3.Zero();
  814. Vector3.CrossToRef(left, right, result);
  815. return result;
  816. };
  817. Vector3.CrossToRef = function (left, right, result) {
  818. result.x = left.y * right.z - left.z * right.y;
  819. result.y = left.z * right.x - left.x * right.z;
  820. result.z = left.x * right.y - left.y * right.x;
  821. };
  822. Vector3.Normalize = function (vector) {
  823. var result = Vector3.Zero();
  824. Vector3.NormalizeToRef(vector, result);
  825. return result;
  826. };
  827. Vector3.NormalizeToRef = function (vector, result) {
  828. result.copyFrom(vector);
  829. result.normalize();
  830. };
  831. Vector3.Project = function (vector, world, transform, viewport) {
  832. var cw = viewport.width;
  833. var ch = viewport.height;
  834. var cx = viewport.x;
  835. var cy = viewport.y;
  836. 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);
  837. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  838. return Vector3.TransformCoordinates(vector, finalMatrix);
  839. };
  840. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  841. var matrix = world.multiply(transform);
  842. matrix.invert();
  843. source.x = source.x / viewportWidth * 2 - 1;
  844. source.y = -(source.y / viewportHeight * 2 - 1);
  845. var vector = Vector3.TransformCoordinates(source, matrix);
  846. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  847. if (MathTools.WithinEpsilon(num, 1.0)) {
  848. vector = vector.scale(1.0 / num);
  849. }
  850. return vector;
  851. };
  852. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  853. var matrix = world.multiply(view).multiply(projection);
  854. matrix.invert();
  855. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), source.z);
  856. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  857. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  858. if (MathTools.WithinEpsilon(num, 1.0)) {
  859. vector = vector.scale(1.0 / num);
  860. }
  861. return vector;
  862. };
  863. Vector3.Minimize = function (left, right) {
  864. var min = left.clone();
  865. min.MinimizeInPlace(right);
  866. return min;
  867. };
  868. Vector3.Maximize = function (left, right) {
  869. var max = left.clone();
  870. max.MaximizeInPlace(right);
  871. return max;
  872. };
  873. Vector3.Distance = function (value1, value2) {
  874. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  875. };
  876. Vector3.DistanceSquared = function (value1, value2) {
  877. var x = value1.x - value2.x;
  878. var y = value1.y - value2.y;
  879. var z = value1.z - value2.z;
  880. return (x * x) + (y * y) + (z * z);
  881. };
  882. Vector3.Center = function (value1, value2) {
  883. var center = value1.add(value2);
  884. center.scaleInPlace(0.5);
  885. return center;
  886. };
  887. /**
  888. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  889. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  890. * to something in order to rotate it from its local system to the given target system.
  891. */
  892. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  893. var rotation = Vector3.Zero();
  894. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  895. return rotation;
  896. };
  897. /**
  898. * The same than RotationFromAxis but updates the passed ref Vector3 parameter.
  899. */
  900. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  901. var u = axis1.normalize();
  902. var w = axis3.normalize();
  903. // world axis
  904. var X = Axis.X;
  905. var Y = Axis.Y;
  906. // equation unknowns and vars
  907. var yaw = 0.0;
  908. var pitch = 0.0;
  909. var roll = 0.0;
  910. var x = 0.0;
  911. var y = 0.0;
  912. var z = 0.0;
  913. var t = 0.0;
  914. var sign = -1.0;
  915. var nbRevert = 0;
  916. var cross = Tmp.Vector3[0];
  917. var dot = 0.0;
  918. // step 1 : rotation around w
  919. // Rv3(u) = u1, and u1 belongs to plane xOz
  920. // Rv3(w) = w1 = w invariant
  921. var u1 = Tmp.Vector3[1];
  922. if (MathTools.WithinEpsilon(w.z, 0, BABYLON.Epsilon)) {
  923. z = 1.0;
  924. }
  925. else if (MathTools.WithinEpsilon(w.x, 0, BABYLON.Epsilon)) {
  926. x = 1.0;
  927. }
  928. else {
  929. t = w.z / w.x;
  930. x = -t * Math.sqrt(1 / (1 + t * t));
  931. z = Math.sqrt(1 / (1 + t * t));
  932. }
  933. u1.x = x;
  934. u1.y = y;
  935. u1.z = z;
  936. u1.normalize();
  937. Vector3.CrossToRef(u, u1, cross); // returns same direction as w (=local z) if positive angle : cross(source, image)
  938. cross.normalize();
  939. if (Vector3.Dot(w, cross) < 0) {
  940. sign = 1.0;
  941. }
  942. dot = Vector3.Dot(u, u1);
  943. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  944. roll = Math.acos(dot) * sign;
  945. if (Vector3.Dot(u1, X) < 0) {
  946. roll = Math.PI + roll;
  947. u1 = u1.scaleInPlace(-1);
  948. nbRevert++;
  949. }
  950. // step 2 : rotate around u1
  951. // Ru1(w1) = Ru1(w) = w2, and w2 belongs to plane xOz
  952. // u1 is yet in xOz and invariant by Ru1, so after this step u1 and w2 will be in xOz
  953. var w2 = Tmp.Vector3[2];
  954. var v2 = Tmp.Vector3[3];
  955. x = 0.0;
  956. y = 0.0;
  957. z = 0.0;
  958. sign = -1.0;
  959. if (MathTools.WithinEpsilon(w.z, 0, BABYLON.Epsilon)) {
  960. x = 1.0;
  961. }
  962. else {
  963. t = u1.z / u1.x;
  964. x = -t * Math.sqrt(1 / (1 + t * t));
  965. z = Math.sqrt(1 / (1 + t * t));
  966. }
  967. w2.x = x;
  968. w2.y = y;
  969. w2.z = z;
  970. w2.normalize();
  971. Vector3.CrossToRef(w2, u1, v2); // v2 image of v1 through rotation around u1
  972. v2.normalize();
  973. Vector3.CrossToRef(w, w2, cross); // returns same direction as u1 (=local x) if positive angle : cross(source, image)
  974. cross.normalize();
  975. if (Vector3.Dot(u1, cross) < 0) {
  976. sign = 1.0;
  977. }
  978. dot = Vector3.Dot(w, w2);
  979. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  980. pitch = Math.acos(dot) * sign;
  981. if (Vector3.Dot(v2, Y) < 0) {
  982. pitch = Math.PI + pitch;
  983. nbRevert++;
  984. }
  985. // step 3 : rotate around v2
  986. // Rv2(u1) = X, same as Rv2(w2) = Z, with X=(1,0,0) and Z=(0,0,1)
  987. sign = -1.0;
  988. Vector3.CrossToRef(X, u1, cross); // returns same direction as Y if positive angle : cross(source, image)
  989. cross.normalize();
  990. if (Vector3.Dot(cross, Y) < 0) {
  991. sign = 1.0;
  992. }
  993. dot = Vector3.Dot(u1, X);
  994. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  995. yaw = -Math.acos(dot) * sign; // negative : plane zOx oriented clockwise
  996. if (dot < 0 && nbRevert < 2) {
  997. yaw = Math.PI + yaw;
  998. }
  999. ref.x = pitch;
  1000. ref.y = yaw;
  1001. ref.z = roll;
  1002. };
  1003. return Vector3;
  1004. })();
  1005. BABYLON.Vector3 = Vector3;
  1006. //Vector4 class created for EulerAngle class conversion to Quaternion
  1007. var Vector4 = (function () {
  1008. function Vector4(x, y, z, w) {
  1009. this.x = x;
  1010. this.y = y;
  1011. this.z = z;
  1012. this.w = w;
  1013. }
  1014. Vector4.prototype.toString = function () {
  1015. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  1016. };
  1017. // Operators
  1018. Vector4.prototype.asArray = function () {
  1019. var result = [];
  1020. this.toArray(result, 0);
  1021. return result;
  1022. };
  1023. Vector4.prototype.toArray = function (array, index) {
  1024. if (index === undefined) {
  1025. index = 0;
  1026. }
  1027. array[index] = this.x;
  1028. array[index + 1] = this.y;
  1029. array[index + 2] = this.z;
  1030. array[index + 3] = this.w;
  1031. return this;
  1032. };
  1033. Vector4.prototype.addInPlace = function (otherVector) {
  1034. this.x += otherVector.x;
  1035. this.y += otherVector.y;
  1036. this.z += otherVector.z;
  1037. this.w += otherVector.w;
  1038. return this;
  1039. };
  1040. Vector4.prototype.add = function (otherVector) {
  1041. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1042. };
  1043. Vector4.prototype.addToRef = function (otherVector, result) {
  1044. result.x = this.x + otherVector.x;
  1045. result.y = this.y + otherVector.y;
  1046. result.z = this.z + otherVector.z;
  1047. result.w = this.w + otherVector.w;
  1048. return this;
  1049. };
  1050. Vector4.prototype.subtractInPlace = function (otherVector) {
  1051. this.x -= otherVector.x;
  1052. this.y -= otherVector.y;
  1053. this.z -= otherVector.z;
  1054. this.w -= otherVector.w;
  1055. return this;
  1056. };
  1057. Vector4.prototype.subtract = function (otherVector) {
  1058. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1059. };
  1060. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1061. result.x = this.x - otherVector.x;
  1062. result.y = this.y - otherVector.y;
  1063. result.z = this.z - otherVector.z;
  1064. result.w = this.w - otherVector.w;
  1065. return this;
  1066. };
  1067. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1068. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1069. };
  1070. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1071. result.x = this.x - x;
  1072. result.y = this.y - y;
  1073. result.z = this.z - z;
  1074. result.w = this.w - w;
  1075. return this;
  1076. };
  1077. Vector4.prototype.negate = function () {
  1078. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1079. };
  1080. Vector4.prototype.scaleInPlace = function (scale) {
  1081. this.x *= scale;
  1082. this.y *= scale;
  1083. this.z *= scale;
  1084. this.w *= scale;
  1085. return this;
  1086. };
  1087. Vector4.prototype.scale = function (scale) {
  1088. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1089. };
  1090. Vector4.prototype.scaleToRef = function (scale, result) {
  1091. result.x = this.x * scale;
  1092. result.y = this.y * scale;
  1093. result.z = this.z * scale;
  1094. result.w = this.w * scale;
  1095. };
  1096. Vector4.prototype.equals = function (otherVector) {
  1097. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1098. };
  1099. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1100. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1101. return otherVector
  1102. && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1103. && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1104. && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1105. && MathTools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1106. };
  1107. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1108. return this.x === x && this.y === y && this.z === z && this.w === w;
  1109. };
  1110. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1111. this.x *= otherVector.x;
  1112. this.y *= otherVector.y;
  1113. this.z *= otherVector.z;
  1114. this.w *= otherVector.w;
  1115. return this;
  1116. };
  1117. Vector4.prototype.multiply = function (otherVector) {
  1118. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1119. };
  1120. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1121. result.x = this.x * otherVector.x;
  1122. result.y = this.y * otherVector.y;
  1123. result.z = this.z * otherVector.z;
  1124. result.w = this.w * otherVector.w;
  1125. return this;
  1126. };
  1127. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1128. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1129. };
  1130. Vector4.prototype.divide = function (otherVector) {
  1131. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1132. };
  1133. Vector4.prototype.divideToRef = function (otherVector, result) {
  1134. result.x = this.x / otherVector.x;
  1135. result.y = this.y / otherVector.y;
  1136. result.z = this.z / otherVector.z;
  1137. result.w = this.w / otherVector.w;
  1138. return this;
  1139. };
  1140. Vector4.prototype.MinimizeInPlace = function (other) {
  1141. if (other.x < this.x)
  1142. this.x = other.x;
  1143. if (other.y < this.y)
  1144. this.y = other.y;
  1145. if (other.z < this.z)
  1146. this.z = other.z;
  1147. if (other.w < this.w)
  1148. this.w = other.w;
  1149. return this;
  1150. };
  1151. Vector4.prototype.MaximizeInPlace = function (other) {
  1152. if (other.x > this.x)
  1153. this.x = other.x;
  1154. if (other.y > this.y)
  1155. this.y = other.y;
  1156. if (other.z > this.z)
  1157. this.z = other.z;
  1158. if (other.w > this.w)
  1159. this.w = other.w;
  1160. return this;
  1161. };
  1162. // Properties
  1163. Vector4.prototype.length = function () {
  1164. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1165. };
  1166. Vector4.prototype.lengthSquared = function () {
  1167. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1168. };
  1169. // Methods
  1170. Vector4.prototype.normalize = function () {
  1171. var len = this.length();
  1172. if (len === 0)
  1173. return this;
  1174. var num = 1.0 / len;
  1175. this.x *= num;
  1176. this.y *= num;
  1177. this.z *= num;
  1178. this.w *= num;
  1179. return this;
  1180. };
  1181. Vector4.prototype.clone = function () {
  1182. return new Vector4(this.x, this.y, this.z, this.w);
  1183. };
  1184. Vector4.prototype.copyFrom = function (source) {
  1185. this.x = source.x;
  1186. this.y = source.y;
  1187. this.z = source.z;
  1188. this.w = source.w;
  1189. return this;
  1190. };
  1191. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1192. this.x = x;
  1193. this.y = y;
  1194. this.z = z;
  1195. this.w = w;
  1196. return this;
  1197. };
  1198. // Statics
  1199. Vector4.FromArray = function (array, offset) {
  1200. if (!offset) {
  1201. offset = 0;
  1202. }
  1203. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1204. };
  1205. Vector4.FromArrayToRef = function (array, offset, result) {
  1206. result.x = array[offset];
  1207. result.y = array[offset + 1];
  1208. result.z = array[offset + 2];
  1209. result.w = array[offset + 3];
  1210. };
  1211. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1212. result.x = array[offset];
  1213. result.y = array[offset + 1];
  1214. result.z = array[offset + 2];
  1215. result.w = array[offset + 3];
  1216. };
  1217. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1218. result.x = x;
  1219. result.y = y;
  1220. result.z = z;
  1221. result.w = w;
  1222. };
  1223. Vector4.Zero = function () {
  1224. return new Vector4(0, 0, 0, 0);
  1225. };
  1226. Vector4.Normalize = function (vector) {
  1227. var result = Vector4.Zero();
  1228. Vector4.NormalizeToRef(vector, result);
  1229. return result;
  1230. };
  1231. Vector4.NormalizeToRef = function (vector, result) {
  1232. result.copyFrom(vector);
  1233. result.normalize();
  1234. };
  1235. Vector4.Minimize = function (left, right) {
  1236. var min = left.clone();
  1237. min.MinimizeInPlace(right);
  1238. return min;
  1239. };
  1240. Vector4.Maximize = function (left, right) {
  1241. var max = left.clone();
  1242. max.MaximizeInPlace(right);
  1243. return max;
  1244. };
  1245. Vector4.Distance = function (value1, value2) {
  1246. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1247. };
  1248. Vector4.DistanceSquared = function (value1, value2) {
  1249. var x = value1.x - value2.x;
  1250. var y = value1.y - value2.y;
  1251. var z = value1.z - value2.z;
  1252. var w = value1.w - value2.w;
  1253. return (x * x) + (y * y) + (z * z) + (w * w);
  1254. };
  1255. Vector4.Center = function (value1, value2) {
  1256. var center = value1.add(value2);
  1257. center.scaleInPlace(0.5);
  1258. return center;
  1259. };
  1260. return Vector4;
  1261. })();
  1262. BABYLON.Vector4 = Vector4;
  1263. var Quaternion = (function () {
  1264. function Quaternion(x, y, z, w) {
  1265. if (x === void 0) { x = 0; }
  1266. if (y === void 0) { y = 0; }
  1267. if (z === void 0) { z = 0; }
  1268. if (w === void 0) { w = 1; }
  1269. this.x = x;
  1270. this.y = y;
  1271. this.z = z;
  1272. this.w = w;
  1273. }
  1274. Quaternion.prototype.toString = function () {
  1275. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1276. };
  1277. Quaternion.prototype.asArray = function () {
  1278. return [this.x, this.y, this.z, this.w];
  1279. };
  1280. Quaternion.prototype.equals = function (otherQuaternion) {
  1281. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1282. };
  1283. Quaternion.prototype.clone = function () {
  1284. return new Quaternion(this.x, this.y, this.z, this.w);
  1285. };
  1286. Quaternion.prototype.copyFrom = function (other) {
  1287. this.x = other.x;
  1288. this.y = other.y;
  1289. this.z = other.z;
  1290. this.w = other.w;
  1291. return this;
  1292. };
  1293. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1294. this.x = x;
  1295. this.y = y;
  1296. this.z = z;
  1297. this.w = w;
  1298. return this;
  1299. };
  1300. Quaternion.prototype.add = function (other) {
  1301. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1302. };
  1303. Quaternion.prototype.subtract = function (other) {
  1304. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1305. };
  1306. Quaternion.prototype.scale = function (value) {
  1307. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1308. };
  1309. Quaternion.prototype.multiply = function (q1) {
  1310. var result = new Quaternion(0, 0, 0, 1.0);
  1311. this.multiplyToRef(q1, result);
  1312. return result;
  1313. };
  1314. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1315. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1316. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1317. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1318. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1319. result.copyFromFloats(x, y, z, w);
  1320. return this;
  1321. };
  1322. Quaternion.prototype.multiplyInPlace = function (q1) {
  1323. this.multiplyToRef(q1, this);
  1324. return this;
  1325. };
  1326. Quaternion.prototype.conjugateToRef = function (ref) {
  1327. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  1328. return this;
  1329. };
  1330. Quaternion.prototype.conjugateInPlace = function () {
  1331. this.x *= -1;
  1332. this.y *= -1;
  1333. this.z *= -1;
  1334. return this;
  1335. };
  1336. Quaternion.prototype.conjugate = function () {
  1337. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  1338. return result;
  1339. };
  1340. Quaternion.prototype.length = function () {
  1341. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1342. };
  1343. Quaternion.prototype.normalize = function () {
  1344. var length = 1.0 / this.length();
  1345. this.x *= length;
  1346. this.y *= length;
  1347. this.z *= length;
  1348. this.w *= length;
  1349. return this;
  1350. };
  1351. Quaternion.prototype.toEulerAngles = function (order) {
  1352. if (order === void 0) { order = "YZX"; }
  1353. var result = Vector3.Zero();
  1354. this.toEulerAnglesToRef(result, order);
  1355. return result;
  1356. };
  1357. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  1358. if (order === void 0) { order = "YZX"; }
  1359. var heading, attitude, bank;
  1360. var x = this.x, y = this.y, z = this.z, w = this.w;
  1361. switch (order) {
  1362. case "YZX":
  1363. var test = x * y + z * w;
  1364. if (test > 0.499) {
  1365. heading = 2 * Math.atan2(x, w);
  1366. attitude = Math.PI / 2;
  1367. bank = 0;
  1368. }
  1369. if (test < -0.499) {
  1370. heading = -2 * Math.atan2(x, w);
  1371. attitude = -Math.PI / 2;
  1372. bank = 0;
  1373. }
  1374. if (isNaN(heading)) {
  1375. var sqx = x * x;
  1376. var sqy = y * y;
  1377. var sqz = z * z;
  1378. heading = Math.atan2(2 * y * w - 2 * x * z, 1 - 2 * sqy - 2 * sqz); // Heading
  1379. attitude = Math.asin(2 * test); // attitude
  1380. bank = Math.atan2(2 * x * w - 2 * y * z, 1 - 2 * sqx - 2 * sqz); // bank
  1381. }
  1382. break;
  1383. default:
  1384. throw new Error("Euler order " + order + " not supported yet.");
  1385. }
  1386. result.y = heading;
  1387. result.z = attitude;
  1388. result.x = bank;
  1389. return this;
  1390. };
  1391. ;
  1392. Quaternion.prototype.toRotationMatrix = function (result) {
  1393. var xx = this.x * this.x;
  1394. var yy = this.y * this.y;
  1395. var zz = this.z * this.z;
  1396. var xy = this.x * this.y;
  1397. var zw = this.z * this.w;
  1398. var zx = this.z * this.x;
  1399. var yw = this.y * this.w;
  1400. var yz = this.y * this.z;
  1401. var xw = this.x * this.w;
  1402. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1403. result.m[1] = 2.0 * (xy + zw);
  1404. result.m[2] = 2.0 * (zx - yw);
  1405. result.m[3] = 0;
  1406. result.m[4] = 2.0 * (xy - zw);
  1407. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1408. result.m[6] = 2.0 * (yz + xw);
  1409. result.m[7] = 0;
  1410. result.m[8] = 2.0 * (zx + yw);
  1411. result.m[9] = 2.0 * (yz - xw);
  1412. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1413. result.m[11] = 0;
  1414. result.m[12] = 0;
  1415. result.m[13] = 0;
  1416. result.m[14] = 0;
  1417. result.m[15] = 1.0;
  1418. return this;
  1419. };
  1420. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1421. Quaternion.FromRotationMatrixToRef(matrix, this);
  1422. return this;
  1423. };
  1424. // Statics
  1425. Quaternion.FromRotationMatrix = function (matrix) {
  1426. var result = new Quaternion();
  1427. Quaternion.FromRotationMatrixToRef(matrix, result);
  1428. return result;
  1429. };
  1430. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1431. var data = matrix.m;
  1432. var m11 = data[0], m12 = data[4], m13 = data[8];
  1433. var m21 = data[1], m22 = data[5], m23 = data[9];
  1434. var m31 = data[2], m32 = data[6], m33 = data[10];
  1435. var trace = m11 + m22 + m33;
  1436. var s;
  1437. if (trace > 0) {
  1438. s = 0.5 / Math.sqrt(trace + 1.0);
  1439. result.w = 0.25 / s;
  1440. result.x = (m32 - m23) * s;
  1441. result.y = (m13 - m31) * s;
  1442. result.z = (m21 - m12) * s;
  1443. }
  1444. else if (m11 > m22 && m11 > m33) {
  1445. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1446. result.w = (m32 - m23) / s;
  1447. result.x = 0.25 * s;
  1448. result.y = (m12 + m21) / s;
  1449. result.z = (m13 + m31) / s;
  1450. }
  1451. else if (m22 > m33) {
  1452. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1453. result.w = (m13 - m31) / s;
  1454. result.x = (m12 + m21) / s;
  1455. result.y = 0.25 * s;
  1456. result.z = (m23 + m32) / s;
  1457. }
  1458. else {
  1459. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1460. result.w = (m21 - m12) / s;
  1461. result.x = (m13 + m31) / s;
  1462. result.y = (m23 + m32) / s;
  1463. result.z = 0.25 * s;
  1464. }
  1465. };
  1466. Quaternion.Inverse = function (q) {
  1467. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1468. };
  1469. Quaternion.Identity = function () {
  1470. return new Quaternion(0, 0, 0, 1);
  1471. };
  1472. Quaternion.RotationAxis = function (axis, angle) {
  1473. var result = new Quaternion();
  1474. var sin = Math.sin(angle / 2);
  1475. axis.normalize();
  1476. result.w = Math.cos(angle / 2);
  1477. result.x = axis.x * sin;
  1478. result.y = axis.y * sin;
  1479. result.z = axis.z * sin;
  1480. return result;
  1481. };
  1482. Quaternion.FromArray = function (array, offset) {
  1483. if (!offset) {
  1484. offset = 0;
  1485. }
  1486. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1487. };
  1488. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1489. var result = new Quaternion();
  1490. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1491. return result;
  1492. };
  1493. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1494. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1495. var halfRoll = roll * 0.5;
  1496. var halfPitch = pitch * 0.5;
  1497. var halfYaw = yaw * 0.5;
  1498. var sinRoll = Math.sin(halfRoll);
  1499. var cosRoll = Math.cos(halfRoll);
  1500. var sinPitch = Math.sin(halfPitch);
  1501. var cosPitch = Math.cos(halfPitch);
  1502. var sinYaw = Math.sin(halfYaw);
  1503. var cosYaw = Math.cos(halfYaw);
  1504. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1505. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1506. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1507. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1508. };
  1509. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1510. var result = new Quaternion();
  1511. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1512. return result;
  1513. };
  1514. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1515. // Produces a quaternion from Euler angles in the z-x-z orientation
  1516. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1517. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1518. var halfBeta = beta * 0.5;
  1519. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1520. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1521. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1522. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1523. };
  1524. Quaternion.Slerp = function (left, right, amount) {
  1525. var num2;
  1526. var num3;
  1527. var num = amount;
  1528. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1529. var flag = false;
  1530. if (num4 < 0) {
  1531. flag = true;
  1532. num4 = -num4;
  1533. }
  1534. if (num4 > 0.999999) {
  1535. num3 = 1 - num;
  1536. num2 = flag ? -num : num;
  1537. }
  1538. else {
  1539. var num5 = Math.acos(num4);
  1540. var num6 = (1.0 / Math.sin(num5));
  1541. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1542. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1543. }
  1544. 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));
  1545. };
  1546. return Quaternion;
  1547. })();
  1548. BABYLON.Quaternion = Quaternion;
  1549. var Matrix = (function () {
  1550. function Matrix() {
  1551. this.m = new Float32Array(16);
  1552. }
  1553. // Properties
  1554. Matrix.prototype.isIdentity = function () {
  1555. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1556. return false;
  1557. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  1558. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  1559. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  1560. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1561. return false;
  1562. return true;
  1563. };
  1564. Matrix.prototype.determinant = function () {
  1565. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1566. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1567. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1568. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1569. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1570. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1571. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  1572. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  1573. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1574. };
  1575. // Methods
  1576. Matrix.prototype.toArray = function () {
  1577. return this.m;
  1578. };
  1579. Matrix.prototype.asArray = function () {
  1580. return this.toArray();
  1581. };
  1582. Matrix.prototype.invert = function () {
  1583. this.invertToRef(this);
  1584. return this;
  1585. };
  1586. Matrix.prototype.reset = function () {
  1587. for (var index = 0; index < 16; index++) {
  1588. this.m[index] = 0;
  1589. }
  1590. return this;
  1591. };
  1592. Matrix.prototype.add = function (other) {
  1593. var result = new Matrix();
  1594. this.addToRef(other, result);
  1595. return result;
  1596. };
  1597. Matrix.prototype.addToRef = function (other, result) {
  1598. for (var index = 0; index < 16; index++) {
  1599. result.m[index] = this.m[index] + other.m[index];
  1600. }
  1601. return this;
  1602. };
  1603. Matrix.prototype.addToSelf = function (other) {
  1604. for (var index = 0; index < 16; index++) {
  1605. this.m[index] += other.m[index];
  1606. }
  1607. return this;
  1608. };
  1609. Matrix.prototype.invertToRef = function (other) {
  1610. var l1 = this.m[0];
  1611. var l2 = this.m[1];
  1612. var l3 = this.m[2];
  1613. var l4 = this.m[3];
  1614. var l5 = this.m[4];
  1615. var l6 = this.m[5];
  1616. var l7 = this.m[6];
  1617. var l8 = this.m[7];
  1618. var l9 = this.m[8];
  1619. var l10 = this.m[9];
  1620. var l11 = this.m[10];
  1621. var l12 = this.m[11];
  1622. var l13 = this.m[12];
  1623. var l14 = this.m[13];
  1624. var l15 = this.m[14];
  1625. var l16 = this.m[15];
  1626. var l17 = (l11 * l16) - (l12 * l15);
  1627. var l18 = (l10 * l16) - (l12 * l14);
  1628. var l19 = (l10 * l15) - (l11 * l14);
  1629. var l20 = (l9 * l16) - (l12 * l13);
  1630. var l21 = (l9 * l15) - (l11 * l13);
  1631. var l22 = (l9 * l14) - (l10 * l13);
  1632. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1633. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1634. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1635. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1636. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1637. var l28 = (l7 * l16) - (l8 * l15);
  1638. var l29 = (l6 * l16) - (l8 * l14);
  1639. var l30 = (l6 * l15) - (l7 * l14);
  1640. var l31 = (l5 * l16) - (l8 * l13);
  1641. var l32 = (l5 * l15) - (l7 * l13);
  1642. var l33 = (l5 * l14) - (l6 * l13);
  1643. var l34 = (l7 * l12) - (l8 * l11);
  1644. var l35 = (l6 * l12) - (l8 * l10);
  1645. var l36 = (l6 * l11) - (l7 * l10);
  1646. var l37 = (l5 * l12) - (l8 * l9);
  1647. var l38 = (l5 * l11) - (l7 * l9);
  1648. var l39 = (l5 * l10) - (l6 * l9);
  1649. other.m[0] = l23 * l27;
  1650. other.m[4] = l24 * l27;
  1651. other.m[8] = l25 * l27;
  1652. other.m[12] = l26 * l27;
  1653. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1654. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1655. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1656. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1657. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1658. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1659. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1660. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1661. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1662. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1663. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1664. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1665. return this;
  1666. };
  1667. Matrix.prototype.setTranslation = function (vector3) {
  1668. this.m[12] = vector3.x;
  1669. this.m[13] = vector3.y;
  1670. this.m[14] = vector3.z;
  1671. return this;
  1672. };
  1673. Matrix.prototype.multiply = function (other) {
  1674. var result = new Matrix();
  1675. this.multiplyToRef(other, result);
  1676. return result;
  1677. };
  1678. Matrix.prototype.copyFrom = function (other) {
  1679. for (var index = 0; index < 16; index++) {
  1680. this.m[index] = other.m[index];
  1681. }
  1682. return this;
  1683. };
  1684. Matrix.prototype.copyToArray = function (array, offset) {
  1685. if (offset === void 0) { offset = 0; }
  1686. for (var index = 0; index < 16; index++) {
  1687. array[offset + index] = this.m[index];
  1688. }
  1689. return this;
  1690. };
  1691. Matrix.prototype.multiplyToRef = function (other, result) {
  1692. this.multiplyToArray(other, result.m, 0);
  1693. return this;
  1694. };
  1695. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1696. var tm0 = this.m[0];
  1697. var tm1 = this.m[1];
  1698. var tm2 = this.m[2];
  1699. var tm3 = this.m[3];
  1700. var tm4 = this.m[4];
  1701. var tm5 = this.m[5];
  1702. var tm6 = this.m[6];
  1703. var tm7 = this.m[7];
  1704. var tm8 = this.m[8];
  1705. var tm9 = this.m[9];
  1706. var tm10 = this.m[10];
  1707. var tm11 = this.m[11];
  1708. var tm12 = this.m[12];
  1709. var tm13 = this.m[13];
  1710. var tm14 = this.m[14];
  1711. var tm15 = this.m[15];
  1712. var om0 = other.m[0];
  1713. var om1 = other.m[1];
  1714. var om2 = other.m[2];
  1715. var om3 = other.m[3];
  1716. var om4 = other.m[4];
  1717. var om5 = other.m[5];
  1718. var om6 = other.m[6];
  1719. var om7 = other.m[7];
  1720. var om8 = other.m[8];
  1721. var om9 = other.m[9];
  1722. var om10 = other.m[10];
  1723. var om11 = other.m[11];
  1724. var om12 = other.m[12];
  1725. var om13 = other.m[13];
  1726. var om14 = other.m[14];
  1727. var om15 = other.m[15];
  1728. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1729. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1730. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1731. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1732. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1733. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1734. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1735. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1736. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1737. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1738. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1739. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1740. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1741. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1742. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1743. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1744. return this;
  1745. };
  1746. Matrix.prototype.equals = function (value) {
  1747. return value &&
  1748. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  1749. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  1750. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  1751. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1752. };
  1753. Matrix.prototype.clone = function () {
  1754. 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]);
  1755. };
  1756. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1757. translation.x = this.m[12];
  1758. translation.y = this.m[13];
  1759. translation.z = this.m[14];
  1760. var xs = MathTools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1761. var ys = MathTools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1762. var zs = MathTools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1763. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1764. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1765. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1766. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1767. rotation.x = 0;
  1768. rotation.y = 0;
  1769. rotation.z = 0;
  1770. rotation.w = 1;
  1771. return false;
  1772. }
  1773. 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);
  1774. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1775. return true;
  1776. };
  1777. // Statics
  1778. Matrix.FromArray = function (array, offset) {
  1779. var result = new Matrix();
  1780. if (!offset) {
  1781. offset = 0;
  1782. }
  1783. Matrix.FromArrayToRef(array, offset, result);
  1784. return result;
  1785. };
  1786. Matrix.FromArrayToRef = function (array, offset, result) {
  1787. for (var index = 0; index < 16; index++) {
  1788. result.m[index] = array[index + offset];
  1789. }
  1790. };
  1791. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  1792. for (var index = 0; index < 16; index++) {
  1793. result.m[index] = array[index + offset] * scale;
  1794. }
  1795. };
  1796. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1797. result.m[0] = initialM11;
  1798. result.m[1] = initialM12;
  1799. result.m[2] = initialM13;
  1800. result.m[3] = initialM14;
  1801. result.m[4] = initialM21;
  1802. result.m[5] = initialM22;
  1803. result.m[6] = initialM23;
  1804. result.m[7] = initialM24;
  1805. result.m[8] = initialM31;
  1806. result.m[9] = initialM32;
  1807. result.m[10] = initialM33;
  1808. result.m[11] = initialM34;
  1809. result.m[12] = initialM41;
  1810. result.m[13] = initialM42;
  1811. result.m[14] = initialM43;
  1812. result.m[15] = initialM44;
  1813. };
  1814. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1815. var result = new Matrix();
  1816. result.m[0] = initialM11;
  1817. result.m[1] = initialM12;
  1818. result.m[2] = initialM13;
  1819. result.m[3] = initialM14;
  1820. result.m[4] = initialM21;
  1821. result.m[5] = initialM22;
  1822. result.m[6] = initialM23;
  1823. result.m[7] = initialM24;
  1824. result.m[8] = initialM31;
  1825. result.m[9] = initialM32;
  1826. result.m[10] = initialM33;
  1827. result.m[11] = initialM34;
  1828. result.m[12] = initialM41;
  1829. result.m[13] = initialM42;
  1830. result.m[14] = initialM43;
  1831. result.m[15] = initialM44;
  1832. return result;
  1833. };
  1834. Matrix.Compose = function (scale, rotation, translation) {
  1835. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1836. var rotationMatrix = Matrix.Identity();
  1837. rotation.toRotationMatrix(rotationMatrix);
  1838. result = result.multiply(rotationMatrix);
  1839. result.setTranslation(translation);
  1840. return result;
  1841. };
  1842. Matrix.Identity = function () {
  1843. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1844. };
  1845. Matrix.IdentityToRef = function (result) {
  1846. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1847. };
  1848. Matrix.Zero = function () {
  1849. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1850. };
  1851. Matrix.RotationX = function (angle) {
  1852. var result = new Matrix();
  1853. Matrix.RotationXToRef(angle, result);
  1854. return result;
  1855. };
  1856. Matrix.Invert = function (source) {
  1857. var result = new Matrix();
  1858. source.invertToRef(result);
  1859. return result;
  1860. };
  1861. Matrix.RotationXToRef = function (angle, result) {
  1862. var s = Math.sin(angle);
  1863. var c = Math.cos(angle);
  1864. result.m[0] = 1.0;
  1865. result.m[15] = 1.0;
  1866. result.m[5] = c;
  1867. result.m[10] = c;
  1868. result.m[9] = -s;
  1869. result.m[6] = s;
  1870. result.m[1] = 0;
  1871. result.m[2] = 0;
  1872. result.m[3] = 0;
  1873. result.m[4] = 0;
  1874. result.m[7] = 0;
  1875. result.m[8] = 0;
  1876. result.m[11] = 0;
  1877. result.m[12] = 0;
  1878. result.m[13] = 0;
  1879. result.m[14] = 0;
  1880. };
  1881. Matrix.RotationY = function (angle) {
  1882. var result = new Matrix();
  1883. Matrix.RotationYToRef(angle, result);
  1884. return result;
  1885. };
  1886. Matrix.RotationYToRef = function (angle, result) {
  1887. var s = Math.sin(angle);
  1888. var c = Math.cos(angle);
  1889. result.m[5] = 1.0;
  1890. result.m[15] = 1.0;
  1891. result.m[0] = c;
  1892. result.m[2] = -s;
  1893. result.m[8] = s;
  1894. result.m[10] = c;
  1895. result.m[1] = 0;
  1896. result.m[3] = 0;
  1897. result.m[4] = 0;
  1898. result.m[6] = 0;
  1899. result.m[7] = 0;
  1900. result.m[9] = 0;
  1901. result.m[11] = 0;
  1902. result.m[12] = 0;
  1903. result.m[13] = 0;
  1904. result.m[14] = 0;
  1905. };
  1906. Matrix.RotationZ = function (angle) {
  1907. var result = new Matrix();
  1908. Matrix.RotationZToRef(angle, result);
  1909. return result;
  1910. };
  1911. Matrix.RotationZToRef = function (angle, result) {
  1912. var s = Math.sin(angle);
  1913. var c = Math.cos(angle);
  1914. result.m[10] = 1.0;
  1915. result.m[15] = 1.0;
  1916. result.m[0] = c;
  1917. result.m[1] = s;
  1918. result.m[4] = -s;
  1919. result.m[5] = c;
  1920. result.m[2] = 0;
  1921. result.m[3] = 0;
  1922. result.m[6] = 0;
  1923. result.m[7] = 0;
  1924. result.m[8] = 0;
  1925. result.m[9] = 0;
  1926. result.m[11] = 0;
  1927. result.m[12] = 0;
  1928. result.m[13] = 0;
  1929. result.m[14] = 0;
  1930. };
  1931. Matrix.RotationAxis = function (axis, angle) {
  1932. var result = Matrix.Zero();
  1933. Matrix.RotationAxisToRef(axis, angle, result);
  1934. return result;
  1935. };
  1936. Matrix.RotationAxisToRef = function (axis, angle, result) {
  1937. var s = Math.sin(-angle);
  1938. var c = Math.cos(-angle);
  1939. var c1 = 1 - c;
  1940. axis.normalize();
  1941. result.m[0] = (axis.x * axis.x) * c1 + c;
  1942. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1943. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1944. result.m[3] = 0.0;
  1945. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1946. result.m[5] = (axis.y * axis.y) * c1 + c;
  1947. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1948. result.m[7] = 0.0;
  1949. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1950. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1951. result.m[10] = (axis.z * axis.z) * c1 + c;
  1952. result.m[11] = 0.0;
  1953. result.m[15] = 1.0;
  1954. };
  1955. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1956. var result = new Matrix();
  1957. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1958. return result;
  1959. };
  1960. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1961. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1962. this._tempQuaternion.toRotationMatrix(result);
  1963. };
  1964. Matrix.Scaling = function (x, y, z) {
  1965. var result = Matrix.Zero();
  1966. Matrix.ScalingToRef(x, y, z, result);
  1967. return result;
  1968. };
  1969. Matrix.ScalingToRef = function (x, y, z, result) {
  1970. result.m[0] = x;
  1971. result.m[1] = 0;
  1972. result.m[2] = 0;
  1973. result.m[3] = 0;
  1974. result.m[4] = 0;
  1975. result.m[5] = y;
  1976. result.m[6] = 0;
  1977. result.m[7] = 0;
  1978. result.m[8] = 0;
  1979. result.m[9] = 0;
  1980. result.m[10] = z;
  1981. result.m[11] = 0;
  1982. result.m[12] = 0;
  1983. result.m[13] = 0;
  1984. result.m[14] = 0;
  1985. result.m[15] = 1.0;
  1986. };
  1987. Matrix.Translation = function (x, y, z) {
  1988. var result = Matrix.Identity();
  1989. Matrix.TranslationToRef(x, y, z, result);
  1990. return result;
  1991. };
  1992. Matrix.TranslationToRef = function (x, y, z, result) {
  1993. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1994. };
  1995. Matrix.Lerp = function (startValue, endValue, gradient) {
  1996. var startScale = new Vector3(0, 0, 0);
  1997. var startRotation = new Quaternion();
  1998. var startTranslation = new Vector3(0, 0, 0);
  1999. startValue.decompose(startScale, startRotation, startTranslation);
  2000. var endScale = new Vector3(0, 0, 0);
  2001. var endRotation = new Quaternion();
  2002. var endTranslation = new Vector3(0, 0, 0);
  2003. endValue.decompose(endScale, endRotation, endTranslation);
  2004. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  2005. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  2006. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  2007. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  2008. };
  2009. Matrix.LookAtLH = function (eye, target, up) {
  2010. var result = Matrix.Zero();
  2011. Matrix.LookAtLHToRef(eye, target, up, result);
  2012. return result;
  2013. };
  2014. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  2015. // Z axis
  2016. target.subtractToRef(eye, this._zAxis);
  2017. this._zAxis.normalize();
  2018. // X axis
  2019. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  2020. if (this._xAxis.lengthSquared() === 0) {
  2021. this._xAxis.x = 1.0;
  2022. }
  2023. else {
  2024. this._xAxis.normalize();
  2025. }
  2026. // Y axis
  2027. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  2028. this._yAxis.normalize();
  2029. // Eye angles
  2030. var ex = -Vector3.Dot(this._xAxis, eye);
  2031. var ey = -Vector3.Dot(this._yAxis, eye);
  2032. var ez = -Vector3.Dot(this._zAxis, eye);
  2033. 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);
  2034. };
  2035. Matrix.OrthoLH = function (width, height, znear, zfar) {
  2036. var matrix = Matrix.Zero();
  2037. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  2038. return matrix;
  2039. };
  2040. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  2041. var hw = 2.0 / width;
  2042. var hh = 2.0 / height;
  2043. var id = 1.0 / (zfar - znear);
  2044. var nid = znear / (znear - zfar);
  2045. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  2046. };
  2047. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  2048. var matrix = Matrix.Zero();
  2049. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  2050. return matrix;
  2051. };
  2052. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2053. result.m[0] = 2.0 / (right - left);
  2054. result.m[1] = result.m[2] = result.m[3] = 0;
  2055. result.m[5] = 2.0 / (top - bottom);
  2056. result.m[4] = result.m[6] = result.m[7] = 0;
  2057. result.m[10] = -1.0 / (znear - zfar);
  2058. result.m[8] = result.m[9] = result.m[11] = 0;
  2059. result.m[12] = (left + right) / (left - right);
  2060. result.m[13] = (top + bottom) / (bottom - top);
  2061. result.m[14] = znear / (znear - zfar);
  2062. result.m[15] = 1.0;
  2063. };
  2064. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  2065. var matrix = Matrix.Zero();
  2066. matrix.m[0] = (2.0 * znear) / width;
  2067. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  2068. matrix.m[5] = (2.0 * znear) / height;
  2069. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  2070. matrix.m[10] = -zfar / (znear - zfar);
  2071. matrix.m[8] = matrix.m[9] = 0.0;
  2072. matrix.m[11] = 1.0;
  2073. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  2074. matrix.m[14] = (znear * zfar) / (znear - zfar);
  2075. return matrix;
  2076. };
  2077. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  2078. var matrix = Matrix.Zero();
  2079. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  2080. return matrix;
  2081. };
  2082. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  2083. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  2084. var tan = 1.0 / (Math.tan(fov * 0.5));
  2085. if (isVerticalFovFixed) {
  2086. result.m[0] = tan / aspect;
  2087. }
  2088. else {
  2089. result.m[0] = tan;
  2090. }
  2091. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2092. if (isVerticalFovFixed) {
  2093. result.m[5] = tan;
  2094. }
  2095. else {
  2096. result.m[5] = tan * aspect;
  2097. }
  2098. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2099. result.m[8] = result.m[9] = 0.0;
  2100. result.m[10] = -zfar / (znear - zfar);
  2101. result.m[11] = 1.0;
  2102. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2103. result.m[14] = (znear * zfar) / (znear - zfar);
  2104. };
  2105. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2106. var cw = viewport.width;
  2107. var ch = viewport.height;
  2108. var cx = viewport.x;
  2109. var cy = viewport.y;
  2110. 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);
  2111. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2112. };
  2113. Matrix.GetAsMatrix2x2 = function (matrix) {
  2114. return new Float32Array([
  2115. matrix.m[0], matrix.m[1],
  2116. matrix.m[4], matrix.m[5]
  2117. ]);
  2118. };
  2119. Matrix.GetAsMatrix3x3 = function (matrix) {
  2120. return new Float32Array([
  2121. matrix.m[0], matrix.m[1], matrix.m[2],
  2122. matrix.m[4], matrix.m[5], matrix.m[6],
  2123. matrix.m[8], matrix.m[9], matrix.m[10]
  2124. ]);
  2125. };
  2126. Matrix.Transpose = function (matrix) {
  2127. var result = new Matrix();
  2128. result.m[0] = matrix.m[0];
  2129. result.m[1] = matrix.m[4];
  2130. result.m[2] = matrix.m[8];
  2131. result.m[3] = matrix.m[12];
  2132. result.m[4] = matrix.m[1];
  2133. result.m[5] = matrix.m[5];
  2134. result.m[6] = matrix.m[9];
  2135. result.m[7] = matrix.m[13];
  2136. result.m[8] = matrix.m[2];
  2137. result.m[9] = matrix.m[6];
  2138. result.m[10] = matrix.m[10];
  2139. result.m[11] = matrix.m[14];
  2140. result.m[12] = matrix.m[3];
  2141. result.m[13] = matrix.m[7];
  2142. result.m[14] = matrix.m[11];
  2143. result.m[15] = matrix.m[15];
  2144. return result;
  2145. };
  2146. Matrix.Reflection = function (plane) {
  2147. var matrix = new Matrix();
  2148. Matrix.ReflectionToRef(plane, matrix);
  2149. return matrix;
  2150. };
  2151. Matrix.ReflectionToRef = function (plane, result) {
  2152. plane.normalize();
  2153. var x = plane.normal.x;
  2154. var y = plane.normal.y;
  2155. var z = plane.normal.z;
  2156. var temp = -2 * x;
  2157. var temp2 = -2 * y;
  2158. var temp3 = -2 * z;
  2159. result.m[0] = (temp * x) + 1;
  2160. result.m[1] = temp2 * x;
  2161. result.m[2] = temp3 * x;
  2162. result.m[3] = 0.0;
  2163. result.m[4] = temp * y;
  2164. result.m[5] = (temp2 * y) + 1;
  2165. result.m[6] = temp3 * y;
  2166. result.m[7] = 0.0;
  2167. result.m[8] = temp * z;
  2168. result.m[9] = temp2 * z;
  2169. result.m[10] = (temp3 * z) + 1;
  2170. result.m[11] = 0.0;
  2171. result.m[12] = temp * plane.d;
  2172. result.m[13] = temp2 * plane.d;
  2173. result.m[14] = temp3 * plane.d;
  2174. result.m[15] = 1.0;
  2175. };
  2176. Matrix._tempQuaternion = new Quaternion();
  2177. Matrix._xAxis = Vector3.Zero();
  2178. Matrix._yAxis = Vector3.Zero();
  2179. Matrix._zAxis = Vector3.Zero();
  2180. return Matrix;
  2181. })();
  2182. BABYLON.Matrix = Matrix;
  2183. var Plane = (function () {
  2184. function Plane(a, b, c, d) {
  2185. this.normal = new Vector3(a, b, c);
  2186. this.d = d;
  2187. }
  2188. Plane.prototype.asArray = function () {
  2189. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2190. };
  2191. // Methods
  2192. Plane.prototype.clone = function () {
  2193. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2194. };
  2195. Plane.prototype.normalize = function () {
  2196. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2197. var magnitude = 0;
  2198. if (norm !== 0) {
  2199. magnitude = 1.0 / norm;
  2200. }
  2201. this.normal.x *= magnitude;
  2202. this.normal.y *= magnitude;
  2203. this.normal.z *= magnitude;
  2204. this.d *= magnitude;
  2205. return this;
  2206. };
  2207. Plane.prototype.transform = function (transformation) {
  2208. var transposedMatrix = Matrix.Transpose(transformation);
  2209. var x = this.normal.x;
  2210. var y = this.normal.y;
  2211. var z = this.normal.z;
  2212. var d = this.d;
  2213. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2214. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2215. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2216. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2217. return new Plane(normalX, normalY, normalZ, finalD);
  2218. };
  2219. Plane.prototype.dotCoordinate = function (point) {
  2220. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2221. };
  2222. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2223. var x1 = point2.x - point1.x;
  2224. var y1 = point2.y - point1.y;
  2225. var z1 = point2.z - point1.z;
  2226. var x2 = point3.x - point1.x;
  2227. var y2 = point3.y - point1.y;
  2228. var z2 = point3.z - point1.z;
  2229. var yz = (y1 * z2) - (z1 * y2);
  2230. var xz = (z1 * x2) - (x1 * z2);
  2231. var xy = (x1 * y2) - (y1 * x2);
  2232. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2233. var invPyth;
  2234. if (pyth !== 0) {
  2235. invPyth = 1.0 / pyth;
  2236. }
  2237. else {
  2238. invPyth = 0;
  2239. }
  2240. this.normal.x = yz * invPyth;
  2241. this.normal.y = xz * invPyth;
  2242. this.normal.z = xy * invPyth;
  2243. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2244. return this;
  2245. };
  2246. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2247. var dot = Vector3.Dot(this.normal, direction);
  2248. return (dot <= epsilon);
  2249. };
  2250. Plane.prototype.signedDistanceTo = function (point) {
  2251. return Vector3.Dot(point, this.normal) + this.d;
  2252. };
  2253. // Statics
  2254. Plane.FromArray = function (array) {
  2255. return new Plane(array[0], array[1], array[2], array[3]);
  2256. };
  2257. Plane.FromPoints = function (point1, point2, point3) {
  2258. var result = new Plane(0, 0, 0, 0);
  2259. result.copyFromPoints(point1, point2, point3);
  2260. return result;
  2261. };
  2262. Plane.FromPositionAndNormal = function (origin, normal) {
  2263. var result = new Plane(0, 0, 0, 0);
  2264. normal.normalize();
  2265. result.normal = normal;
  2266. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2267. return result;
  2268. };
  2269. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2270. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2271. return Vector3.Dot(point, normal) + d;
  2272. };
  2273. return Plane;
  2274. })();
  2275. BABYLON.Plane = Plane;
  2276. var Viewport = (function () {
  2277. function Viewport(x, y, width, height) {
  2278. this.x = x;
  2279. this.y = y;
  2280. this.width = width;
  2281. this.height = height;
  2282. }
  2283. Viewport.prototype.toGlobal = function (renderWidth, renderHeight) {
  2284. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  2285. };
  2286. return Viewport;
  2287. })();
  2288. BABYLON.Viewport = Viewport;
  2289. var Frustum = (function () {
  2290. function Frustum() {
  2291. }
  2292. Frustum.GetPlanes = function (transform) {
  2293. var frustumPlanes = [];
  2294. for (var index = 0; index < 6; index++) {
  2295. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2296. }
  2297. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2298. return frustumPlanes;
  2299. };
  2300. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2301. // Near
  2302. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2303. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2304. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  2305. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2306. frustumPlanes[0].normalize();
  2307. // Far
  2308. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2309. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2310. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2311. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2312. frustumPlanes[1].normalize();
  2313. // Left
  2314. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2315. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2316. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2317. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2318. frustumPlanes[2].normalize();
  2319. // Right
  2320. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2321. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2322. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2323. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2324. frustumPlanes[3].normalize();
  2325. // Top
  2326. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2327. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2328. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2329. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2330. frustumPlanes[4].normalize();
  2331. // Bottom
  2332. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2333. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2334. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2335. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2336. frustumPlanes[5].normalize();
  2337. };
  2338. return Frustum;
  2339. })();
  2340. BABYLON.Frustum = Frustum;
  2341. (function (Space) {
  2342. Space[Space["LOCAL"] = 0] = "LOCAL";
  2343. Space[Space["WORLD"] = 1] = "WORLD";
  2344. })(BABYLON.Space || (BABYLON.Space = {}));
  2345. var Space = BABYLON.Space;
  2346. var Axis = (function () {
  2347. function Axis() {
  2348. }
  2349. Axis.X = new Vector3(1, 0, 0);
  2350. Axis.Y = new Vector3(0, 1, 0);
  2351. Axis.Z = new Vector3(0, 0, 1);
  2352. return Axis;
  2353. })();
  2354. BABYLON.Axis = Axis;
  2355. ;
  2356. var BezierCurve = (function () {
  2357. function BezierCurve() {
  2358. }
  2359. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2360. // Extract X (which is equal to time here)
  2361. var f0 = 1 - 3 * x2 + 3 * x1;
  2362. var f1 = 3 * x2 - 6 * x1;
  2363. var f2 = 3 * x1;
  2364. var refinedT = t;
  2365. for (var i = 0; i < 5; i++) {
  2366. var refinedT2 = refinedT * refinedT;
  2367. var refinedT3 = refinedT2 * refinedT;
  2368. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2369. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2370. refinedT -= (x - t) * slope;
  2371. refinedT = Math.min(1, Math.max(0, refinedT));
  2372. }
  2373. // Resolve cubic bezier for the given x
  2374. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2375. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2376. Math.pow(refinedT, 3);
  2377. };
  2378. return BezierCurve;
  2379. })();
  2380. BABYLON.BezierCurve = BezierCurve;
  2381. (function (Orientation) {
  2382. Orientation[Orientation["CW"] = 0] = "CW";
  2383. Orientation[Orientation["CCW"] = 1] = "CCW";
  2384. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2385. var Orientation = BABYLON.Orientation;
  2386. var Angle = (function () {
  2387. function Angle(radians) {
  2388. var _this = this;
  2389. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2390. this.radians = function () { return _this._radians; };
  2391. this._radians = radians;
  2392. if (this._radians < 0)
  2393. this._radians += (2 * Math.PI);
  2394. }
  2395. Angle.BetweenTwoPoints = function (a, b) {
  2396. var delta = b.subtract(a);
  2397. var theta = Math.atan2(delta.y, delta.x);
  2398. return new Angle(theta);
  2399. };
  2400. Angle.FromRadians = function (radians) {
  2401. return new Angle(radians);
  2402. };
  2403. Angle.FromDegrees = function (degrees) {
  2404. return new Angle(degrees * Math.PI / 180);
  2405. };
  2406. return Angle;
  2407. })();
  2408. BABYLON.Angle = Angle;
  2409. var Arc2 = (function () {
  2410. function Arc2(startPoint, midPoint, endPoint) {
  2411. this.startPoint = startPoint;
  2412. this.midPoint = midPoint;
  2413. this.endPoint = endPoint;
  2414. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2415. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2416. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2417. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2418. 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);
  2419. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2420. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2421. var a1 = this.startAngle.degrees();
  2422. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2423. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2424. // angles correction
  2425. if (a2 - a1 > +180.0)
  2426. a2 -= 360.0;
  2427. if (a2 - a1 < -180.0)
  2428. a2 += 360.0;
  2429. if (a3 - a2 > +180.0)
  2430. a3 -= 360.0;
  2431. if (a3 - a2 < -180.0)
  2432. a3 += 360.0;
  2433. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2434. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2435. }
  2436. return Arc2;
  2437. })();
  2438. BABYLON.Arc2 = Arc2;
  2439. var Path2 = (function () {
  2440. function Path2(x, y) {
  2441. this._points = new Array();
  2442. this._length = 0;
  2443. this.closed = false;
  2444. this._points.push(new Vector2(x, y));
  2445. }
  2446. Path2.prototype.addLineTo = function (x, y) {
  2447. if (closed) {
  2448. //Tools.Error("cannot add lines to closed paths");
  2449. return this;
  2450. }
  2451. var newPoint = new Vector2(x, y);
  2452. var previousPoint = this._points[this._points.length - 1];
  2453. this._points.push(newPoint);
  2454. this._length += newPoint.subtract(previousPoint).length();
  2455. return this;
  2456. };
  2457. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2458. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2459. if (closed) {
  2460. //Tools.Error("cannot add arcs to closed paths");
  2461. return this;
  2462. }
  2463. var startPoint = this._points[this._points.length - 1];
  2464. var midPoint = new Vector2(midX, midY);
  2465. var endPoint = new Vector2(endX, endY);
  2466. var arc = new Arc2(startPoint, midPoint, endPoint);
  2467. var increment = arc.angle.radians() / numberOfSegments;
  2468. if (arc.orientation === Orientation.CW)
  2469. increment *= -1;
  2470. var currentAngle = arc.startAngle.radians() + increment;
  2471. for (var i = 0; i < numberOfSegments; i++) {
  2472. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2473. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2474. this.addLineTo(x, y);
  2475. currentAngle += increment;
  2476. }
  2477. return this;
  2478. };
  2479. Path2.prototype.close = function () {
  2480. this.closed = true;
  2481. return this;
  2482. };
  2483. Path2.prototype.length = function () {
  2484. var result = this._length;
  2485. if (!this.closed) {
  2486. var lastPoint = this._points[this._points.length - 1];
  2487. var firstPoint = this._points[0];
  2488. result += (firstPoint.subtract(lastPoint).length());
  2489. }
  2490. return result;
  2491. };
  2492. Path2.prototype.getPoints = function () {
  2493. return this._points;
  2494. };
  2495. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2496. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2497. //Tools.Error("normalized length position should be between 0 and 1.");
  2498. return Vector2.Zero();
  2499. }
  2500. var lengthPosition = normalizedLengthPosition * this.length();
  2501. var previousOffset = 0;
  2502. for (var i = 0; i < this._points.length; i++) {
  2503. var j = (i + 1) % this._points.length;
  2504. var a = this._points[i];
  2505. var b = this._points[j];
  2506. var bToA = b.subtract(a);
  2507. var nextOffset = (bToA.length() + previousOffset);
  2508. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2509. var dir = bToA.normalize();
  2510. var localOffset = lengthPosition - previousOffset;
  2511. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2512. }
  2513. previousOffset = nextOffset;
  2514. }
  2515. //Tools.Error("internal error");
  2516. return Vector2.Zero();
  2517. };
  2518. Path2.StartingAt = function (x, y) {
  2519. return new Path2(x, y);
  2520. };
  2521. return Path2;
  2522. })();
  2523. BABYLON.Path2 = Path2;
  2524. var Path3D = (function () {
  2525. /**
  2526. * new Path3D(path, normal, raw)
  2527. * path : an array of Vector3, the curve axis of the Path3D
  2528. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  2529. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  2530. */
  2531. function Path3D(path, firstNormal, raw) {
  2532. this.path = path;
  2533. this._curve = new Array();
  2534. this._distances = new Array();
  2535. this._tangents = new Array();
  2536. this._normals = new Array();
  2537. this._binormals = new Array();
  2538. for (var p = 0; p < path.length; p++) {
  2539. this._curve[p] = path[p].clone(); // hard copy
  2540. }
  2541. this._raw = raw || false;
  2542. this._compute(firstNormal);
  2543. }
  2544. Path3D.prototype.getCurve = function () {
  2545. return this._curve;
  2546. };
  2547. Path3D.prototype.getTangents = function () {
  2548. return this._tangents;
  2549. };
  2550. Path3D.prototype.getNormals = function () {
  2551. return this._normals;
  2552. };
  2553. Path3D.prototype.getBinormals = function () {
  2554. return this._binormals;
  2555. };
  2556. Path3D.prototype.getDistances = function () {
  2557. return this._distances;
  2558. };
  2559. Path3D.prototype.update = function (path, firstNormal) {
  2560. for (var p = 0; p < path.length; p++) {
  2561. this._curve[p].x = path[p].x;
  2562. this._curve[p].y = path[p].y;
  2563. this._curve[p].z = path[p].z;
  2564. }
  2565. this._compute(firstNormal);
  2566. return this;
  2567. };
  2568. // private function compute() : computes tangents, normals and binormals
  2569. Path3D.prototype._compute = function (firstNormal) {
  2570. var l = this._curve.length;
  2571. // first and last tangents
  2572. this._tangents[0] = this._getFirstNonNullVector(0);
  2573. if (!this._raw) {
  2574. this._tangents[0].normalize();
  2575. }
  2576. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2577. if (!this._raw) {
  2578. this._tangents[l - 1].normalize();
  2579. }
  2580. // normals and binormals at first point : arbitrary vector with _normalVector()
  2581. var tg0 = this._tangents[0];
  2582. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2583. this._normals[0] = pp0;
  2584. if (!this._raw) {
  2585. this._normals[0].normalize();
  2586. }
  2587. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2588. if (!this._raw) {
  2589. this._binormals[0].normalize();
  2590. }
  2591. this._distances[0] = 0;
  2592. // normals and binormals : next points
  2593. var prev; // previous vector (segment)
  2594. var cur; // current vector (segment)
  2595. var curTang; // current tangent
  2596. // previous normal
  2597. var prevBinor; // previous binormal
  2598. for (var i = 1; i < l; i++) {
  2599. // tangents
  2600. prev = this._getLastNonNullVector(i);
  2601. if (i < l - 1) {
  2602. cur = this._getFirstNonNullVector(i);
  2603. this._tangents[i] = prev.add(cur);
  2604. this._tangents[i].normalize();
  2605. }
  2606. this._distances[i] = this._distances[i - 1] + prev.length();
  2607. // normals and binormals
  2608. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2609. curTang = this._tangents[i];
  2610. prevBinor = this._binormals[i - 1];
  2611. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2612. if (!this._raw) {
  2613. this._normals[i].normalize();
  2614. }
  2615. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2616. if (!this._raw) {
  2617. this._binormals[i].normalize();
  2618. }
  2619. }
  2620. };
  2621. // private function getFirstNonNullVector(index)
  2622. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  2623. Path3D.prototype._getFirstNonNullVector = function (index) {
  2624. var i = 1;
  2625. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  2626. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  2627. i++;
  2628. nNVector = this._curve[index + i].subtract(this._curve[index]);
  2629. }
  2630. return nNVector;
  2631. };
  2632. // private function getLastNonNullVector(index)
  2633. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  2634. Path3D.prototype._getLastNonNullVector = function (index) {
  2635. var i = 1;
  2636. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  2637. while (nLVector.length() === 0 && index > i + 1) {
  2638. i++;
  2639. nLVector = this._curve[index].subtract(this._curve[index - i]);
  2640. }
  2641. return nLVector;
  2642. };
  2643. // private function normalVector(v0, vt, va) :
  2644. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2645. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  2646. Path3D.prototype._normalVector = function (v0, vt, va) {
  2647. var normal0;
  2648. if (va === undefined || va === null) {
  2649. var point;
  2650. if (!MathTools.WithinEpsilon(vt.y, 1, BABYLON.Epsilon)) {
  2651. point = new Vector3(0, -1, 0);
  2652. }
  2653. else if (!MathTools.WithinEpsilon(vt.x, 1, BABYLON.Epsilon)) {
  2654. point = new Vector3(1, 0, 0);
  2655. }
  2656. else if (!MathTools.WithinEpsilon(vt.z, 1, BABYLON.Epsilon)) {
  2657. point = new Vector3(0, 0, 1);
  2658. }
  2659. normal0 = Vector3.Cross(vt, point);
  2660. }
  2661. else {
  2662. normal0 = Vector3.Cross(vt, va);
  2663. Vector3.CrossToRef(normal0, vt, normal0);
  2664. }
  2665. normal0.normalize();
  2666. return normal0;
  2667. };
  2668. return Path3D;
  2669. })();
  2670. BABYLON.Path3D = Path3D;
  2671. var Curve3 = (function () {
  2672. function Curve3(points) {
  2673. this._length = 0;
  2674. this._points = points;
  2675. this._length = this._computeLength(points);
  2676. }
  2677. // QuadraticBezier(origin_V3, control_V3, destination_V3, nbPoints)
  2678. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2679. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2680. var bez = new Array();
  2681. var equation = function (t, val0, val1, val2) {
  2682. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  2683. return res;
  2684. };
  2685. for (var i = 0; i <= nbPoints; i++) {
  2686. 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)));
  2687. }
  2688. return new Curve3(bez);
  2689. };
  2690. // CubicBezier(origin_V3, control1_V3, control2_V3, destination_V3, nbPoints)
  2691. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  2692. nbPoints = nbPoints > 3 ? nbPoints : 4;
  2693. var bez = new Array();
  2694. var equation = function (t, val0, val1, val2, val3) {
  2695. 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;
  2696. return res;
  2697. };
  2698. for (var i = 0; i <= nbPoints; i++) {
  2699. 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)));
  2700. }
  2701. return new Curve3(bez);
  2702. };
  2703. // HermiteSpline(origin_V3, originTangent_V3, destination_V3, destinationTangent_V3, nbPoints)
  2704. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  2705. var hermite = new Array();
  2706. var step = 1 / nbPoints;
  2707. for (var i = 0; i <= nbPoints; i++) {
  2708. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  2709. }
  2710. return new Curve3(hermite);
  2711. };
  2712. Curve3.prototype.getPoints = function () {
  2713. return this._points;
  2714. };
  2715. Curve3.prototype.length = function () {
  2716. return this._length;
  2717. };
  2718. Curve3.prototype.continue = function (curve) {
  2719. var lastPoint = this._points[this._points.length - 1];
  2720. var continuedPoints = this._points.slice();
  2721. var curvePoints = curve.getPoints();
  2722. for (var i = 1; i < curvePoints.length; i++) {
  2723. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  2724. }
  2725. var continuedCurve = new Curve3(continuedPoints);
  2726. return continuedCurve;
  2727. };
  2728. Curve3.prototype._computeLength = function (path) {
  2729. var l = 0;
  2730. for (var i = 1; i < path.length; i++) {
  2731. l += (path[i].subtract(path[i - 1])).length();
  2732. }
  2733. return l;
  2734. };
  2735. return Curve3;
  2736. })();
  2737. BABYLON.Curve3 = Curve3;
  2738. // SphericalHarmonics
  2739. var SphericalHarmonics = (function () {
  2740. function SphericalHarmonics() {
  2741. this.L00 = Vector3.Zero();
  2742. this.L1_1 = Vector3.Zero();
  2743. this.L10 = Vector3.Zero();
  2744. this.L11 = Vector3.Zero();
  2745. this.L2_2 = Vector3.Zero();
  2746. this.L2_1 = Vector3.Zero();
  2747. this.L20 = Vector3.Zero();
  2748. this.L21 = Vector3.Zero();
  2749. this.L22 = Vector3.Zero();
  2750. }
  2751. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  2752. var colorVector = new Vector3(color.r, color.g, color.b);
  2753. var c = colorVector.scale(deltaSolidAngle);
  2754. this.L00 = this.L00.add(c.scale(0.282095));
  2755. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  2756. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  2757. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  2758. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  2759. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  2760. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  2761. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  2762. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  2763. };
  2764. SphericalHarmonics.prototype.scale = function (scale) {
  2765. this.L00 = this.L00.scale(scale);
  2766. this.L1_1 = this.L1_1.scale(scale);
  2767. this.L10 = this.L10.scale(scale);
  2768. this.L11 = this.L11.scale(scale);
  2769. this.L2_2 = this.L2_2.scale(scale);
  2770. this.L2_1 = this.L2_1.scale(scale);
  2771. this.L20 = this.L20.scale(scale);
  2772. this.L21 = this.L21.scale(scale);
  2773. this.L22 = this.L22.scale(scale);
  2774. };
  2775. return SphericalHarmonics;
  2776. })();
  2777. BABYLON.SphericalHarmonics = SphericalHarmonics;
  2778. // SphericalPolynomial
  2779. var SphericalPolynomial = (function () {
  2780. function SphericalPolynomial() {
  2781. this.x = Vector3.Zero();
  2782. this.y = Vector3.Zero();
  2783. this.z = Vector3.Zero();
  2784. this.xx = Vector3.Zero();
  2785. this.yy = Vector3.Zero();
  2786. this.zz = Vector3.Zero();
  2787. this.xy = Vector3.Zero();
  2788. this.yz = Vector3.Zero();
  2789. this.zx = Vector3.Zero();
  2790. }
  2791. SphericalPolynomial.prototype.addAmbient = function (color) {
  2792. var colorVector = new Vector3(color.r, color.g, color.b);
  2793. this.xx = this.xx.add(colorVector);
  2794. this.yy = this.yy.add(colorVector);
  2795. this.zz = this.zz.add(colorVector);
  2796. };
  2797. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  2798. var result = new SphericalPolynomial();
  2799. result.x = harmonics.L11.scale(1.02333);
  2800. result.y = harmonics.L1_1.scale(1.02333);
  2801. result.z = harmonics.L10.scale(1.02333);
  2802. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  2803. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  2804. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  2805. result.yz = harmonics.L2_1.scale(0.858086);
  2806. result.zx = harmonics.L21.scale(0.858086);
  2807. result.xy = harmonics.L2_2.scale(0.858086);
  2808. return result;
  2809. };
  2810. return SphericalPolynomial;
  2811. })();
  2812. BABYLON.SphericalPolynomial = SphericalPolynomial;
  2813. // Vertex formats
  2814. var PositionNormalVertex = (function () {
  2815. function PositionNormalVertex(position, normal) {
  2816. if (position === void 0) { position = Vector3.Zero(); }
  2817. if (normal === void 0) { normal = Vector3.Up(); }
  2818. this.position = position;
  2819. this.normal = normal;
  2820. }
  2821. PositionNormalVertex.prototype.clone = function () {
  2822. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  2823. };
  2824. return PositionNormalVertex;
  2825. })();
  2826. BABYLON.PositionNormalVertex = PositionNormalVertex;
  2827. var PositionNormalTextureVertex = (function () {
  2828. function PositionNormalTextureVertex(position, normal, uv) {
  2829. if (position === void 0) { position = Vector3.Zero(); }
  2830. if (normal === void 0) { normal = Vector3.Up(); }
  2831. if (uv === void 0) { uv = Vector2.Zero(); }
  2832. this.position = position;
  2833. this.normal = normal;
  2834. this.uv = uv;
  2835. }
  2836. PositionNormalTextureVertex.prototype.clone = function () {
  2837. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  2838. };
  2839. return PositionNormalTextureVertex;
  2840. })();
  2841. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  2842. // Temporary pre-allocated objects for engine internal use
  2843. // usage in any internal function :
  2844. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  2845. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  2846. var Tmp = (function () {
  2847. function Tmp() {
  2848. }
  2849. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  2850. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  2851. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  2852. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  2853. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  2854. Tmp.Quaternion = [new Quaternion(0, 0, 0, 0)]; // 1 temp Quaternion at once should be enough
  2855. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  2856. Matrix.Zero(), Matrix.Zero(),
  2857. Matrix.Zero(), Matrix.Zero(),
  2858. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  2859. return Tmp;
  2860. })();
  2861. BABYLON.Tmp = Tmp;
  2862. })(BABYLON || (BABYLON = {}));
  2863. var BABYLON;
  2864. (function (BABYLON) {
  2865. function generateSerializableMember(type, sourceName) {
  2866. return function (target, propertyKey) {
  2867. if (!target.__serializableMembers) {
  2868. target.__serializableMembers = {};
  2869. }
  2870. target.__serializableMembers[propertyKey] = { type: type, sourceName: sourceName };
  2871. };
  2872. }
  2873. function serialize(sourceName) {
  2874. return generateSerializableMember(0, sourceName); // value member
  2875. }
  2876. BABYLON.serialize = serialize;
  2877. function serializeAsTexture(sourceName) {
  2878. return generateSerializableMember(1, sourceName); // texture member
  2879. }
  2880. BABYLON.serializeAsTexture = serializeAsTexture;
  2881. function serializeAsColor3(sourceName) {
  2882. return generateSerializableMember(2, sourceName); // color3 member
  2883. }
  2884. BABYLON.serializeAsColor3 = serializeAsColor3;
  2885. function serializeAsFresnelParameters(sourceName) {
  2886. return generateSerializableMember(3, sourceName); // fresnel parameters member
  2887. }
  2888. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  2889. function serializeAsVector2(sourceName) {
  2890. return generateSerializableMember(4, sourceName); // vector2 member
  2891. }
  2892. BABYLON.serializeAsVector2 = serializeAsVector2;
  2893. function serializeAsVector3(sourceName) {
  2894. return generateSerializableMember(5, sourceName); // vector3 member
  2895. }
  2896. BABYLON.serializeAsVector3 = serializeAsVector3;
  2897. function serializeAsMeshReference(sourceName) {
  2898. return generateSerializableMember(6, sourceName); // mesh reference member
  2899. }
  2900. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  2901. var SerializationHelper = (function () {
  2902. function SerializationHelper() {
  2903. }
  2904. SerializationHelper.Serialize = function (entity, serializationObject) {
  2905. if (!serializationObject) {
  2906. serializationObject = {};
  2907. }
  2908. // Tags
  2909. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  2910. // Properties
  2911. for (var property in entity.__serializableMembers) {
  2912. var propertyDescriptor = entity.__serializableMembers[property];
  2913. var targetPropertyName = propertyDescriptor.sourceName || property;
  2914. var propertyType = propertyDescriptor.type;
  2915. var sourceProperty = entity[property];
  2916. if (sourceProperty !== undefined && sourceProperty !== null) {
  2917. switch (propertyType) {
  2918. case 0:
  2919. serializationObject[targetPropertyName] = sourceProperty;
  2920. break;
  2921. case 1:
  2922. serializationObject[targetPropertyName] = sourceProperty.serialize();
  2923. break;
  2924. case 2:
  2925. serializationObject[targetPropertyName] = sourceProperty.asArray();
  2926. break;
  2927. case 3:
  2928. serializationObject[targetPropertyName] = sourceProperty.serialize();
  2929. break;
  2930. case 4:
  2931. serializationObject[targetPropertyName] = sourceProperty.asArray();
  2932. break;
  2933. case 5:
  2934. serializationObject[targetPropertyName] = sourceProperty.asArray();
  2935. break;
  2936. case 6:
  2937. serializationObject[targetPropertyName] = sourceProperty.id;
  2938. break;
  2939. }
  2940. }
  2941. }
  2942. return serializationObject;
  2943. };
  2944. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  2945. var destination = creationFunction();
  2946. // Tags
  2947. BABYLON.Tags.AddTagsTo(destination, source.tags);
  2948. // Properties
  2949. for (var property in destination.__serializableMembers) {
  2950. var propertyDescriptor = destination.__serializableMembers[property];
  2951. var sourceProperty = source[propertyDescriptor.sourceName || property];
  2952. var propertyType = propertyDescriptor.type;
  2953. if (sourceProperty !== undefined && sourceProperty !== null) {
  2954. switch (propertyType) {
  2955. case 0:
  2956. destination[property] = sourceProperty;
  2957. break;
  2958. case 1:
  2959. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  2960. break;
  2961. case 2:
  2962. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  2963. break;
  2964. case 3:
  2965. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  2966. break;
  2967. case 4:
  2968. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  2969. break;
  2970. case 5:
  2971. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  2972. break;
  2973. case 6:
  2974. destination[property] = scene.getLastMeshByID(sourceProperty);
  2975. break;
  2976. }
  2977. }
  2978. }
  2979. return destination;
  2980. };
  2981. SerializationHelper.Clone = function (creationFunction, source) {
  2982. var destination = creationFunction();
  2983. // Tags
  2984. BABYLON.Tags.AddTagsTo(destination, source.tags);
  2985. // Properties
  2986. for (var property in destination.__serializableMembers) {
  2987. var propertyDescriptor = destination.__serializableMembers[property];
  2988. var sourceProperty = source[property];
  2989. var propertyType = propertyDescriptor.type;
  2990. if (sourceProperty !== undefined && sourceProperty !== null) {
  2991. switch (propertyType) {
  2992. case 0: // Value
  2993. case 6:
  2994. destination[property] = sourceProperty;
  2995. break;
  2996. case 1: // Texture
  2997. case 2: // Color3
  2998. case 3: // FresnelParameters
  2999. case 4: // Vector2
  3000. case 5:
  3001. destination[property] = sourceProperty.clone();
  3002. break;
  3003. }
  3004. }
  3005. }
  3006. return destination;
  3007. };
  3008. return SerializationHelper;
  3009. })();
  3010. BABYLON.SerializationHelper = SerializationHelper;
  3011. })(BABYLON || (BABYLON = {}));
  3012. var BABYLON;
  3013. (function (BABYLON) {
  3014. var Database = (function () {
  3015. function Database(urlToScene, callbackManifestChecked) {
  3016. // Handling various flavors of prefixed version of IndexedDB
  3017. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  3018. this.callbackManifestChecked = callbackManifestChecked;
  3019. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  3020. this.db = null;
  3021. this.enableSceneOffline = false;
  3022. this.enableTexturesOffline = false;
  3023. this.manifestVersionFound = 0;
  3024. this.mustUpdateRessources = false;
  3025. this.hasReachedQuota = false;
  3026. if (!Database.IDBStorageEnabled) {
  3027. this.callbackManifestChecked(true);
  3028. }
  3029. else {
  3030. this.checkManifestFile();
  3031. }
  3032. }
  3033. Database.prototype.checkManifestFile = function () {
  3034. var _this = this;
  3035. function noManifestFile() {
  3036. that.enableSceneOffline = false;
  3037. that.enableTexturesOffline = false;
  3038. that.callbackManifestChecked(false);
  3039. }
  3040. var that = this;
  3041. var timeStampUsed = false;
  3042. var manifestURL = this.currentSceneUrl + ".manifest";
  3043. var xhr = new XMLHttpRequest();
  3044. if (navigator.onLine) {
  3045. // Adding a timestamp to by-pass browsers' cache
  3046. timeStampUsed = true;
  3047. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  3048. }
  3049. xhr.open("GET", manifestURL, true);
  3050. xhr.addEventListener("load", function () {
  3051. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  3052. try {
  3053. var manifestFile = JSON.parse(xhr.response);
  3054. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  3055. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  3056. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  3057. _this.manifestVersionFound = manifestFile.version;
  3058. }
  3059. if (_this.callbackManifestChecked) {
  3060. _this.callbackManifestChecked(true);
  3061. }
  3062. }
  3063. catch (ex) {
  3064. noManifestFile();
  3065. }
  3066. }
  3067. else {
  3068. noManifestFile();
  3069. }
  3070. }, false);
  3071. xhr.addEventListener("error", function (event) {
  3072. if (timeStampUsed) {
  3073. timeStampUsed = false;
  3074. // Let's retry without the timeStamp
  3075. // It could fail when coupled with HTML5 Offline API
  3076. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  3077. xhr.open("GET", retryManifestURL, true);
  3078. xhr.send();
  3079. }
  3080. else {
  3081. noManifestFile();
  3082. }
  3083. }, false);
  3084. try {
  3085. xhr.send();
  3086. }
  3087. catch (ex) {
  3088. BABYLON.Tools.Error("Error on XHR send request.");
  3089. that.callbackManifestChecked(false);
  3090. }
  3091. };
  3092. Database.prototype.openAsync = function (successCallback, errorCallback) {
  3093. var _this = this;
  3094. function handleError() {
  3095. that.isSupported = false;
  3096. if (errorCallback)
  3097. errorCallback();
  3098. }
  3099. var that = this;
  3100. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  3101. // Your browser doesn't support IndexedDB
  3102. this.isSupported = false;
  3103. if (errorCallback)
  3104. errorCallback();
  3105. }
  3106. else {
  3107. // If the DB hasn't been opened or created yet
  3108. if (!this.db) {
  3109. this.hasReachedQuota = false;
  3110. this.isSupported = true;
  3111. var request = this.idbFactory.open("babylonjs", 1);
  3112. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3113. request.onerror = function (event) {
  3114. handleError();
  3115. };
  3116. // executes when a version change transaction cannot complete due to other active transactions
  3117. request.onblocked = function (event) {
  3118. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3119. handleError();
  3120. };
  3121. // DB has been opened successfully
  3122. request.onsuccess = function (event) {
  3123. _this.db = request.result;
  3124. successCallback();
  3125. };
  3126. // Initialization of the DB. Creating Scenes & Textures stores
  3127. request.onupgradeneeded = function (event) {
  3128. _this.db = (event.target).result;
  3129. try {
  3130. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3131. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3132. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3133. }
  3134. catch (ex) {
  3135. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3136. handleError();
  3137. }
  3138. };
  3139. }
  3140. else {
  3141. if (successCallback)
  3142. successCallback();
  3143. }
  3144. }
  3145. };
  3146. Database.prototype.loadImageFromDB = function (url, image) {
  3147. var _this = this;
  3148. var completeURL = Database.ReturnFullUrlLocation(url);
  3149. var saveAndLoadImage = function () {
  3150. if (!_this.hasReachedQuota && _this.db !== null) {
  3151. // the texture is not yet in the DB, let's try to save it
  3152. _this._saveImageIntoDBAsync(completeURL, image);
  3153. }
  3154. else {
  3155. image.src = url;
  3156. }
  3157. };
  3158. if (!this.mustUpdateRessources) {
  3159. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3160. }
  3161. else {
  3162. saveAndLoadImage();
  3163. }
  3164. };
  3165. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3166. if (this.isSupported && this.db !== null) {
  3167. var texture;
  3168. var transaction = this.db.transaction(["textures"]);
  3169. transaction.onabort = function (event) {
  3170. image.src = url;
  3171. };
  3172. transaction.oncomplete = function (event) {
  3173. var blobTextureURL;
  3174. if (texture) {
  3175. var URL = window.URL || window.webkitURL;
  3176. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3177. image.onerror = function () {
  3178. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3179. image.src = url;
  3180. };
  3181. image.src = blobTextureURL;
  3182. }
  3183. else {
  3184. notInDBCallback();
  3185. }
  3186. };
  3187. var getRequest = transaction.objectStore("textures").get(url);
  3188. getRequest.onsuccess = function (event) {
  3189. texture = (event.target).result;
  3190. };
  3191. getRequest.onerror = function (event) {
  3192. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3193. image.src = url;
  3194. };
  3195. }
  3196. else {
  3197. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3198. image.src = url;
  3199. }
  3200. };
  3201. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3202. var _this = this;
  3203. if (this.isSupported) {
  3204. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3205. var generateBlobUrl = function () {
  3206. var blobTextureURL;
  3207. if (blob) {
  3208. var URL = window.URL || window.webkitURL;
  3209. try {
  3210. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3211. }
  3212. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3213. catch (ex) {
  3214. blobTextureURL = URL.createObjectURL(blob);
  3215. }
  3216. }
  3217. image.src = blobTextureURL;
  3218. };
  3219. if (Database.IsUASupportingBlobStorage) {
  3220. var xhr = new XMLHttpRequest(), blob;
  3221. xhr.open("GET", url, true);
  3222. xhr.responseType = "blob";
  3223. xhr.addEventListener("load", function () {
  3224. if (xhr.status === 200) {
  3225. // Blob as response (XHR2)
  3226. blob = xhr.response;
  3227. var transaction = _this.db.transaction(["textures"], "readwrite");
  3228. // the transaction could abort because of a QuotaExceededError error
  3229. transaction.onabort = function (event) {
  3230. try {
  3231. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3232. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3233. this.hasReachedQuota = true;
  3234. }
  3235. }
  3236. catch (ex) { }
  3237. generateBlobUrl();
  3238. };
  3239. transaction.oncomplete = function (event) {
  3240. generateBlobUrl();
  3241. };
  3242. var newTexture = { textureUrl: url, data: blob };
  3243. try {
  3244. // Put the blob into the dabase
  3245. var addRequest = transaction.objectStore("textures").put(newTexture);
  3246. addRequest.onsuccess = function (event) {
  3247. };
  3248. addRequest.onerror = function (event) {
  3249. generateBlobUrl();
  3250. };
  3251. }
  3252. catch (ex) {
  3253. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3254. if (ex.code === 25) {
  3255. Database.IsUASupportingBlobStorage = false;
  3256. }
  3257. image.src = url;
  3258. }
  3259. }
  3260. else {
  3261. image.src = url;
  3262. }
  3263. }, false);
  3264. xhr.addEventListener("error", function (event) {
  3265. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3266. image.src = url;
  3267. }, false);
  3268. xhr.send();
  3269. }
  3270. else {
  3271. image.src = url;
  3272. }
  3273. }
  3274. else {
  3275. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3276. image.src = url;
  3277. }
  3278. };
  3279. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3280. var _this = this;
  3281. var updateVersion = function (event) {
  3282. // the version is not yet in the DB or we need to update it
  3283. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3284. };
  3285. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3286. };
  3287. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3288. var _this = this;
  3289. if (this.isSupported) {
  3290. var version;
  3291. try {
  3292. var transaction = this.db.transaction(["versions"]);
  3293. transaction.oncomplete = function (event) {
  3294. if (version) {
  3295. // If the version in the JSON file is > than the version in DB
  3296. if (_this.manifestVersionFound > version.data) {
  3297. _this.mustUpdateRessources = true;
  3298. updateInDBCallback();
  3299. }
  3300. else {
  3301. callback(version.data);
  3302. }
  3303. }
  3304. else {
  3305. _this.mustUpdateRessources = true;
  3306. updateInDBCallback();
  3307. }
  3308. };
  3309. transaction.onabort = function (event) {
  3310. callback(-1);
  3311. };
  3312. var getRequest = transaction.objectStore("versions").get(url);
  3313. getRequest.onsuccess = function (event) {
  3314. version = (event.target).result;
  3315. };
  3316. getRequest.onerror = function (event) {
  3317. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3318. callback(-1);
  3319. };
  3320. }
  3321. catch (ex) {
  3322. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3323. callback(-1);
  3324. }
  3325. }
  3326. else {
  3327. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3328. callback(-1);
  3329. }
  3330. };
  3331. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3332. var _this = this;
  3333. if (this.isSupported && !this.hasReachedQuota) {
  3334. try {
  3335. // Open a transaction to the database
  3336. var transaction = this.db.transaction(["versions"], "readwrite");
  3337. // the transaction could abort because of a QuotaExceededError error
  3338. transaction.onabort = function (event) {
  3339. try {
  3340. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3341. _this.hasReachedQuota = true;
  3342. }
  3343. }
  3344. catch (ex) { }
  3345. callback(-1);
  3346. };
  3347. transaction.oncomplete = function (event) {
  3348. callback(_this.manifestVersionFound);
  3349. };
  3350. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3351. // Put the scene into the database
  3352. var addRequest = transaction.objectStore("versions").put(newVersion);
  3353. addRequest.onsuccess = function (event) {
  3354. };
  3355. addRequest.onerror = function (event) {
  3356. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3357. };
  3358. }
  3359. catch (ex) {
  3360. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3361. callback(-1);
  3362. }
  3363. }
  3364. else {
  3365. callback(-1);
  3366. }
  3367. };
  3368. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3369. var _this = this;
  3370. var completeUrl = Database.ReturnFullUrlLocation(url);
  3371. var saveAndLoadFile = function (event) {
  3372. // the scene is not yet in the DB, let's try to save it
  3373. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3374. };
  3375. this._checkVersionFromDB(completeUrl, function (version) {
  3376. if (version !== -1) {
  3377. if (!_this.mustUpdateRessources) {
  3378. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3379. }
  3380. else {
  3381. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3382. }
  3383. }
  3384. else {
  3385. errorCallback();
  3386. }
  3387. });
  3388. };
  3389. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3390. if (this.isSupported) {
  3391. var targetStore;
  3392. if (url.indexOf(".babylon") !== -1) {
  3393. targetStore = "scenes";
  3394. }
  3395. else {
  3396. targetStore = "textures";
  3397. }
  3398. var file;
  3399. var transaction = this.db.transaction([targetStore]);
  3400. transaction.oncomplete = function (event) {
  3401. if (file) {
  3402. callback(file.data);
  3403. }
  3404. else {
  3405. notInDBCallback();
  3406. }
  3407. };
  3408. transaction.onabort = function (event) {
  3409. notInDBCallback();
  3410. };
  3411. var getRequest = transaction.objectStore(targetStore).get(url);
  3412. getRequest.onsuccess = function (event) {
  3413. file = (event.target).result;
  3414. };
  3415. getRequest.onerror = function (event) {
  3416. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3417. notInDBCallback();
  3418. };
  3419. }
  3420. else {
  3421. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3422. callback();
  3423. }
  3424. };
  3425. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3426. var _this = this;
  3427. if (this.isSupported) {
  3428. var targetStore;
  3429. if (url.indexOf(".babylon") !== -1) {
  3430. targetStore = "scenes";
  3431. }
  3432. else {
  3433. targetStore = "textures";
  3434. }
  3435. // Create XHR
  3436. var xhr = new XMLHttpRequest(), fileData;
  3437. xhr.open("GET", url, true);
  3438. if (useArrayBuffer) {
  3439. xhr.responseType = "arraybuffer";
  3440. }
  3441. xhr.onprogress = progressCallback;
  3442. xhr.addEventListener("load", function () {
  3443. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  3444. // Blob as response (XHR2)
  3445. //fileData = xhr.responseText;
  3446. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  3447. if (!_this.hasReachedQuota) {
  3448. // Open a transaction to the database
  3449. var transaction = _this.db.transaction([targetStore], "readwrite");
  3450. // the transaction could abort because of a QuotaExceededError error
  3451. transaction.onabort = function (event) {
  3452. try {
  3453. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3454. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3455. this.hasReachedQuota = true;
  3456. }
  3457. }
  3458. catch (ex) { }
  3459. callback(fileData);
  3460. };
  3461. transaction.oncomplete = function (event) {
  3462. callback(fileData);
  3463. };
  3464. var newFile;
  3465. if (targetStore === "scenes") {
  3466. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  3467. }
  3468. else {
  3469. newFile = { textureUrl: url, data: fileData };
  3470. }
  3471. try {
  3472. // Put the scene into the database
  3473. var addRequest = transaction.objectStore(targetStore).put(newFile);
  3474. addRequest.onsuccess = function (event) {
  3475. };
  3476. addRequest.onerror = function (event) {
  3477. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  3478. };
  3479. }
  3480. catch (ex) {
  3481. callback(fileData);
  3482. }
  3483. }
  3484. else {
  3485. callback(fileData);
  3486. }
  3487. }
  3488. else {
  3489. callback();
  3490. }
  3491. }, false);
  3492. xhr.addEventListener("error", function (event) {
  3493. BABYLON.Tools.Error("error on XHR request.");
  3494. callback();
  3495. }, false);
  3496. xhr.send();
  3497. }
  3498. else {
  3499. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3500. callback();
  3501. }
  3502. };
  3503. Database.IsUASupportingBlobStorage = true;
  3504. Database.IDBStorageEnabled = true;
  3505. Database.parseURL = function (url) {
  3506. var a = document.createElement('a');
  3507. a.href = url;
  3508. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  3509. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  3510. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  3511. return absLocation;
  3512. };
  3513. Database.ReturnFullUrlLocation = function (url) {
  3514. if (url.indexOf("http:/") === -1) {
  3515. return (Database.parseURL(window.location.href) + url);
  3516. }
  3517. else {
  3518. return url;
  3519. }
  3520. };
  3521. return Database;
  3522. })();
  3523. BABYLON.Database = Database;
  3524. })(BABYLON || (BABYLON = {}));
  3525. var BABYLON;
  3526. (function (BABYLON) {
  3527. var Internals;
  3528. (function (Internals) {
  3529. /*
  3530. * Based on jsTGALoader - Javascript loader for TGA file
  3531. * By Vincent Thibault
  3532. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  3533. */
  3534. var TGATools = (function () {
  3535. function TGATools() {
  3536. }
  3537. TGATools.GetTGAHeader = function (data) {
  3538. var offset = 0;
  3539. var header = {
  3540. id_length: data[offset++],
  3541. colormap_type: data[offset++],
  3542. image_type: data[offset++],
  3543. colormap_index: data[offset++] | data[offset++] << 8,
  3544. colormap_length: data[offset++] | data[offset++] << 8,
  3545. colormap_size: data[offset++],
  3546. origin: [
  3547. data[offset++] | data[offset++] << 8,
  3548. data[offset++] | data[offset++] << 8
  3549. ],
  3550. width: data[offset++] | data[offset++] << 8,
  3551. height: data[offset++] | data[offset++] << 8,
  3552. pixel_size: data[offset++],
  3553. flags: data[offset++]
  3554. };
  3555. return header;
  3556. };
  3557. TGATools.UploadContent = function (gl, data) {
  3558. // Not enough data to contain header ?
  3559. if (data.length < 19) {
  3560. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  3561. return;
  3562. }
  3563. // Read Header
  3564. var offset = 18;
  3565. var header = TGATools.GetTGAHeader(data);
  3566. // Assume it's a valid Targa file.
  3567. if (header.id_length + offset > data.length) {
  3568. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  3569. return;
  3570. }
  3571. // Skip not needed data
  3572. offset += header.id_length;
  3573. var use_rle = false;
  3574. var use_pal = false;
  3575. var use_rgb = false;
  3576. var use_grey = false;
  3577. // Get some informations.
  3578. switch (header.image_type) {
  3579. case TGATools._TYPE_RLE_INDEXED:
  3580. use_rle = true;
  3581. case TGATools._TYPE_INDEXED:
  3582. use_pal = true;
  3583. break;
  3584. case TGATools._TYPE_RLE_RGB:
  3585. use_rle = true;
  3586. case TGATools._TYPE_RGB:
  3587. use_rgb = true;
  3588. break;
  3589. case TGATools._TYPE_RLE_GREY:
  3590. use_rle = true;
  3591. case TGATools._TYPE_GREY:
  3592. use_grey = true;
  3593. break;
  3594. }
  3595. var pixel_data;
  3596. var numAlphaBits = header.flags & 0xf;
  3597. var pixel_size = header.pixel_size >> 3;
  3598. var pixel_total = header.width * header.height * pixel_size;
  3599. // Read palettes
  3600. var palettes;
  3601. if (use_pal) {
  3602. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  3603. }
  3604. // Read LRE
  3605. if (use_rle) {
  3606. pixel_data = new Uint8Array(pixel_total);
  3607. var c, count, i;
  3608. var localOffset = 0;
  3609. var pixels = new Uint8Array(pixel_size);
  3610. while (offset < pixel_total && localOffset < pixel_total) {
  3611. c = data[offset++];
  3612. count = (c & 0x7f) + 1;
  3613. // RLE pixels
  3614. if (c & 0x80) {
  3615. // Bind pixel tmp array
  3616. for (i = 0; i < pixel_size; ++i) {
  3617. pixels[i] = data[offset++];
  3618. }
  3619. // Copy pixel array
  3620. for (i = 0; i < count; ++i) {
  3621. pixel_data.set(pixels, localOffset + i * pixel_size);
  3622. }
  3623. localOffset += pixel_size * count;
  3624. }
  3625. else {
  3626. count *= pixel_size;
  3627. for (i = 0; i < count; ++i) {
  3628. pixel_data[localOffset + i] = data[offset++];
  3629. }
  3630. localOffset += count;
  3631. }
  3632. }
  3633. }
  3634. else {
  3635. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  3636. }
  3637. // Load to texture
  3638. var x_start, y_start, x_step, y_step, y_end, x_end;
  3639. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  3640. default:
  3641. case TGATools._ORIGIN_UL:
  3642. x_start = 0;
  3643. x_step = 1;
  3644. x_end = header.width;
  3645. y_start = 0;
  3646. y_step = 1;
  3647. y_end = header.height;
  3648. break;
  3649. case TGATools._ORIGIN_BL:
  3650. x_start = 0;
  3651. x_step = 1;
  3652. x_end = header.width;
  3653. y_start = header.height - 1;
  3654. y_step = -1;
  3655. y_end = -1;
  3656. break;
  3657. case TGATools._ORIGIN_UR:
  3658. x_start = header.width - 1;
  3659. x_step = -1;
  3660. x_end = -1;
  3661. y_start = 0;
  3662. y_step = 1;
  3663. y_end = header.height;
  3664. break;
  3665. case TGATools._ORIGIN_BR:
  3666. x_start = header.width - 1;
  3667. x_step = -1;
  3668. x_end = -1;
  3669. y_start = header.height - 1;
  3670. y_step = -1;
  3671. y_end = -1;
  3672. break;
  3673. }
  3674. // Load the specify method
  3675. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  3676. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  3677. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  3678. };
  3679. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3680. var image = pixel_data, colormap = palettes;
  3681. var width = header.width, height = header.height;
  3682. var color, i = 0, x, y;
  3683. var imageData = new Uint8Array(width * height * 4);
  3684. for (y = y_start; y !== y_end; y += y_step) {
  3685. for (x = x_start; x !== x_end; x += x_step, i++) {
  3686. color = image[i];
  3687. imageData[(x + width * y) * 4 + 3] = 255;
  3688. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  3689. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  3690. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  3691. }
  3692. }
  3693. return imageData;
  3694. };
  3695. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3696. var image = pixel_data;
  3697. var width = header.width, height = header.height;
  3698. var color, i = 0, x, y;
  3699. var imageData = new Uint8Array(width * height * 4);
  3700. for (y = y_start; y !== y_end; y += y_step) {
  3701. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3702. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  3703. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  3704. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  3705. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  3706. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  3707. }
  3708. }
  3709. return imageData;
  3710. };
  3711. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3712. var image = pixel_data;
  3713. var width = header.width, height = header.height;
  3714. var i = 0, x, y;
  3715. var imageData = new Uint8Array(width * height * 4);
  3716. for (y = y_start; y !== y_end; y += y_step) {
  3717. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  3718. imageData[(x + width * y) * 4 + 3] = 255;
  3719. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3720. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3721. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3722. }
  3723. }
  3724. return imageData;
  3725. };
  3726. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3727. var image = pixel_data;
  3728. var width = header.width, height = header.height;
  3729. var i = 0, x, y;
  3730. var imageData = new Uint8Array(width * height * 4);
  3731. for (y = y_start; y !== y_end; y += y_step) {
  3732. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  3733. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3734. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3735. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3736. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  3737. }
  3738. }
  3739. return imageData;
  3740. };
  3741. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3742. var image = pixel_data;
  3743. var width = header.width, height = header.height;
  3744. var color, i = 0, x, y;
  3745. var imageData = new Uint8Array(width * height * 4);
  3746. for (y = y_start; y !== y_end; y += y_step) {
  3747. for (x = x_start; x !== x_end; x += x_step, i++) {
  3748. color = image[i];
  3749. imageData[(x + width * y) * 4 + 0] = color;
  3750. imageData[(x + width * y) * 4 + 1] = color;
  3751. imageData[(x + width * y) * 4 + 2] = color;
  3752. imageData[(x + width * y) * 4 + 3] = 255;
  3753. }
  3754. }
  3755. return imageData;
  3756. };
  3757. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3758. var image = pixel_data;
  3759. var width = header.width, height = header.height;
  3760. var i = 0, x, y;
  3761. var imageData = new Uint8Array(width * height * 4);
  3762. for (y = y_start; y !== y_end; y += y_step) {
  3763. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3764. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  3765. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  3766. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3767. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  3768. }
  3769. }
  3770. return imageData;
  3771. };
  3772. TGATools._TYPE_NO_DATA = 0;
  3773. TGATools._TYPE_INDEXED = 1;
  3774. TGATools._TYPE_RGB = 2;
  3775. TGATools._TYPE_GREY = 3;
  3776. TGATools._TYPE_RLE_INDEXED = 9;
  3777. TGATools._TYPE_RLE_RGB = 10;
  3778. TGATools._TYPE_RLE_GREY = 11;
  3779. TGATools._ORIGIN_MASK = 0x30;
  3780. TGATools._ORIGIN_SHIFT = 0x04;
  3781. TGATools._ORIGIN_BL = 0x00;
  3782. TGATools._ORIGIN_BR = 0x01;
  3783. TGATools._ORIGIN_UL = 0x02;
  3784. TGATools._ORIGIN_UR = 0x03;
  3785. return TGATools;
  3786. })();
  3787. Internals.TGATools = TGATools;
  3788. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  3789. })(BABYLON || (BABYLON = {}));
  3790. var BABYLON;
  3791. (function (BABYLON) {
  3792. var SmartArray = (function () {
  3793. function SmartArray(capacity) {
  3794. this.length = 0;
  3795. this._duplicateId = 0;
  3796. this.data = new Array(capacity);
  3797. this._id = SmartArray._GlobalId++;
  3798. }
  3799. SmartArray.prototype.push = function (value) {
  3800. this.data[this.length++] = value;
  3801. if (this.length > this.data.length) {
  3802. this.data.length *= 2;
  3803. }
  3804. if (!value.__smartArrayFlags) {
  3805. value.__smartArrayFlags = {};
  3806. }
  3807. value.__smartArrayFlags[this._id] = this._duplicateId;
  3808. };
  3809. SmartArray.prototype.pushNoDuplicate = function (value) {
  3810. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  3811. return;
  3812. }
  3813. this.push(value);
  3814. };
  3815. SmartArray.prototype.sort = function (compareFn) {
  3816. this.data.sort(compareFn);
  3817. };
  3818. SmartArray.prototype.reset = function () {
  3819. this.length = 0;
  3820. this._duplicateId++;
  3821. };
  3822. SmartArray.prototype.concat = function (array) {
  3823. if (array.length === 0) {
  3824. return;
  3825. }
  3826. if (this.length + array.length > this.data.length) {
  3827. this.data.length = (this.length + array.length) * 2;
  3828. }
  3829. for (var index = 0; index < array.length; index++) {
  3830. this.data[this.length++] = (array.data || array)[index];
  3831. }
  3832. };
  3833. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  3834. if (array.length === 0) {
  3835. return;
  3836. }
  3837. if (this.length + array.length > this.data.length) {
  3838. this.data.length = (this.length + array.length) * 2;
  3839. }
  3840. for (var index = 0; index < array.length; index++) {
  3841. var item = (array.data || array)[index];
  3842. this.pushNoDuplicate(item);
  3843. }
  3844. };
  3845. SmartArray.prototype.indexOf = function (value) {
  3846. var position = this.data.indexOf(value);
  3847. if (position >= this.length) {
  3848. return -1;
  3849. }
  3850. return position;
  3851. };
  3852. // Statics
  3853. SmartArray._GlobalId = 0;
  3854. return SmartArray;
  3855. })();
  3856. BABYLON.SmartArray = SmartArray;
  3857. })(BABYLON || (BABYLON = {}));
  3858. var BABYLON;
  3859. (function (BABYLON) {
  3860. var SmartCollection = (function () {
  3861. function SmartCollection(capacity) {
  3862. if (capacity === void 0) { capacity = 10; }
  3863. this.count = 0;
  3864. this._initialCapacity = capacity;
  3865. this.items = {};
  3866. this._keys = new Array(this._initialCapacity);
  3867. }
  3868. SmartCollection.prototype.add = function (key, item) {
  3869. if (this.items[key] != undefined) {
  3870. return -1;
  3871. }
  3872. this.items[key] = item;
  3873. //literal keys are always strings, but we keep source type of key in _keys array
  3874. this._keys[this.count++] = key;
  3875. if (this.count > this._keys.length) {
  3876. this._keys.length *= 2;
  3877. }
  3878. return this.count;
  3879. };
  3880. SmartCollection.prototype.remove = function (key) {
  3881. if (this.items[key] == undefined) {
  3882. return -1;
  3883. }
  3884. return this.removeItemOfIndex(this.indexOf(key));
  3885. };
  3886. SmartCollection.prototype.removeItemOfIndex = function (index) {
  3887. if (index < this.count && index > -1) {
  3888. delete this.items[this._keys[index]];
  3889. //here, shifting by hand is better optimised than .splice
  3890. while (index < this.count) {
  3891. this._keys[index] = this._keys[index + 1];
  3892. index++;
  3893. }
  3894. }
  3895. else {
  3896. return -1;
  3897. }
  3898. return --this.count;
  3899. };
  3900. SmartCollection.prototype.indexOf = function (key) {
  3901. for (var i = 0; i !== this.count; i++) {
  3902. if (this._keys[i] === key) {
  3903. return i;
  3904. }
  3905. }
  3906. return -1;
  3907. };
  3908. SmartCollection.prototype.item = function (key) {
  3909. return this.items[key];
  3910. };
  3911. SmartCollection.prototype.getAllKeys = function () {
  3912. if (this.count > 0) {
  3913. var keys = new Array(this.count);
  3914. for (var i = 0; i < this.count; i++) {
  3915. keys[i] = this._keys[i];
  3916. }
  3917. return keys;
  3918. }
  3919. else {
  3920. return undefined;
  3921. }
  3922. };
  3923. SmartCollection.prototype.getKeyByIndex = function (index) {
  3924. if (index < this.count && index > -1) {
  3925. return this._keys[index];
  3926. }
  3927. else {
  3928. return undefined;
  3929. }
  3930. };
  3931. SmartCollection.prototype.getItemByIndex = function (index) {
  3932. if (index < this.count && index > -1) {
  3933. return this.items[this._keys[index]];
  3934. }
  3935. else {
  3936. return undefined;
  3937. }
  3938. };
  3939. SmartCollection.prototype.empty = function () {
  3940. if (this.count > 0) {
  3941. this.count = 0;
  3942. this.items = {};
  3943. this._keys = new Array(this._initialCapacity);
  3944. }
  3945. };
  3946. SmartCollection.prototype.forEach = function (block) {
  3947. var key;
  3948. for (key in this.items) {
  3949. if (this.items.hasOwnProperty(key)) {
  3950. block(this.items[key]);
  3951. }
  3952. }
  3953. };
  3954. return SmartCollection;
  3955. })();
  3956. BABYLON.SmartCollection = SmartCollection;
  3957. })(BABYLON || (BABYLON = {}));
  3958. var BABYLON;
  3959. (function (BABYLON) {
  3960. // Screenshots
  3961. var screenshotCanvas;
  3962. var cloneValue = function (source, destinationObject) {
  3963. if (!source)
  3964. return null;
  3965. if (source instanceof BABYLON.Mesh) {
  3966. return null;
  3967. }
  3968. if (source instanceof BABYLON.SubMesh) {
  3969. return source.clone(destinationObject);
  3970. }
  3971. else if (source.clone) {
  3972. return source.clone();
  3973. }
  3974. return null;
  3975. };
  3976. var Tools = (function () {
  3977. function Tools() {
  3978. }
  3979. Tools.Instantiate = function (className) {
  3980. var arr = className.split(".");
  3981. var fn = (window || this);
  3982. for (var i = 0, len = arr.length; i < len; i++) {
  3983. fn = fn[arr[i]];
  3984. }
  3985. if (typeof fn !== "function") {
  3986. return null;
  3987. }
  3988. return fn;
  3989. };
  3990. Tools.SetImmediate = function (action) {
  3991. if (window.setImmediate) {
  3992. window.setImmediate(action);
  3993. }
  3994. else {
  3995. setTimeout(action, 1);
  3996. }
  3997. };
  3998. Tools.IsExponentOfTwo = function (value) {
  3999. var count = 1;
  4000. do {
  4001. count *= 2;
  4002. } while (count < value);
  4003. return count === value;
  4004. };
  4005. Tools.GetExponentOfTwo = function (value, max) {
  4006. var count = 1;
  4007. do {
  4008. count *= 2;
  4009. } while (count < value);
  4010. if (count > max)
  4011. count = max;
  4012. return count;
  4013. };
  4014. Tools.GetFilename = function (path) {
  4015. var index = path.lastIndexOf("/");
  4016. if (index < 0)
  4017. return path;
  4018. return path.substring(index + 1);
  4019. };
  4020. Tools.GetDOMTextContent = function (element) {
  4021. var result = "";
  4022. var child = element.firstChild;
  4023. while (child) {
  4024. if (child.nodeType === 3) {
  4025. result += child.textContent;
  4026. }
  4027. child = child.nextSibling;
  4028. }
  4029. return result;
  4030. };
  4031. Tools.ToDegrees = function (angle) {
  4032. return angle * 180 / Math.PI;
  4033. };
  4034. Tools.ToRadians = function (angle) {
  4035. return angle * Math.PI / 180;
  4036. };
  4037. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  4038. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  4039. var output = "";
  4040. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  4041. var i = 0;
  4042. var bytes = new Uint8Array(buffer);
  4043. while (i < bytes.length) {
  4044. chr1 = bytes[i++];
  4045. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  4046. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  4047. enc1 = chr1 >> 2;
  4048. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  4049. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  4050. enc4 = chr3 & 63;
  4051. if (isNaN(chr2)) {
  4052. enc3 = enc4 = 64;
  4053. }
  4054. else if (isNaN(chr3)) {
  4055. enc4 = 64;
  4056. }
  4057. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  4058. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  4059. }
  4060. return "data:image/png;base64," + output;
  4061. };
  4062. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  4063. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4064. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4065. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4066. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4067. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4068. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4069. }
  4070. return {
  4071. minimum: minimum,
  4072. maximum: maximum
  4073. };
  4074. };
  4075. Tools.ExtractMinAndMax = function (positions, start, count) {
  4076. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4077. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4078. for (var index = start; index < start + count; index++) {
  4079. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  4080. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4081. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4082. }
  4083. return {
  4084. minimum: minimum,
  4085. maximum: maximum
  4086. };
  4087. };
  4088. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4089. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4090. return undefined;
  4091. return Array.isArray(obj) ? obj : [obj];
  4092. };
  4093. // Misc.
  4094. Tools.GetPointerPrefix = function () {
  4095. var eventPrefix = "pointer";
  4096. // Check if pointer events are supported
  4097. if (!window.PointerEvent && !navigator.pointerEnabled) {
  4098. eventPrefix = "mouse";
  4099. }
  4100. return eventPrefix;
  4101. };
  4102. Tools.QueueNewFrame = function (func) {
  4103. if (window.requestAnimationFrame)
  4104. window.requestAnimationFrame(func);
  4105. else if (window.msRequestAnimationFrame)
  4106. window.msRequestAnimationFrame(func);
  4107. else if (window.webkitRequestAnimationFrame)
  4108. window.webkitRequestAnimationFrame(func);
  4109. else if (window.mozRequestAnimationFrame)
  4110. window.mozRequestAnimationFrame(func);
  4111. else if (window.oRequestAnimationFrame)
  4112. window.oRequestAnimationFrame(func);
  4113. else {
  4114. window.setTimeout(func, 16);
  4115. }
  4116. };
  4117. Tools.RequestFullscreen = function (element) {
  4118. if (element.requestFullscreen)
  4119. element.requestFullscreen();
  4120. else if (element.msRequestFullscreen)
  4121. element.msRequestFullscreen();
  4122. else if (element.webkitRequestFullscreen)
  4123. element.webkitRequestFullscreen();
  4124. else if (element.mozRequestFullScreen)
  4125. element.mozRequestFullScreen();
  4126. };
  4127. Tools.ExitFullscreen = function () {
  4128. if (document.exitFullscreen) {
  4129. document.exitFullscreen();
  4130. }
  4131. else if (document.mozCancelFullScreen) {
  4132. document.mozCancelFullScreen();
  4133. }
  4134. else if (document.webkitCancelFullScreen) {
  4135. document.webkitCancelFullScreen();
  4136. }
  4137. else if (document.msCancelFullScreen) {
  4138. document.msCancelFullScreen();
  4139. }
  4140. };
  4141. // External files
  4142. Tools.CleanUrl = function (url) {
  4143. url = url.replace(/#/mg, "%23");
  4144. return url;
  4145. };
  4146. Tools.LoadImage = function (url, onload, onerror, database) {
  4147. if (url instanceof ArrayBuffer) {
  4148. url = Tools.EncodeArrayBufferTobase64(url);
  4149. }
  4150. url = Tools.CleanUrl(url);
  4151. var img = new Image();
  4152. if (url.substr(0, 5) !== "data:") {
  4153. if (Tools.CorsBehavior) {
  4154. switch (typeof (Tools.CorsBehavior)) {
  4155. case "function":
  4156. var result = Tools.CorsBehavior(url);
  4157. if (result) {
  4158. img.crossOrigin = result;
  4159. }
  4160. break;
  4161. case "string":
  4162. default:
  4163. img.crossOrigin = Tools.CorsBehavior;
  4164. break;
  4165. }
  4166. }
  4167. }
  4168. img.onload = function () {
  4169. onload(img);
  4170. };
  4171. img.onerror = function (err) {
  4172. Tools.Error("Error while trying to load texture: " + url);
  4173. if (Tools.UseFallbackTexture) {
  4174. 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";
  4175. onload(img);
  4176. }
  4177. else {
  4178. onerror();
  4179. }
  4180. };
  4181. var noIndexedDB = function () {
  4182. img.src = url;
  4183. };
  4184. var loadFromIndexedDB = function () {
  4185. database.loadImageFromDB(url, img);
  4186. };
  4187. //ANY database to do!
  4188. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4189. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4190. }
  4191. else {
  4192. if (url.indexOf("file:") === -1) {
  4193. noIndexedDB();
  4194. }
  4195. else {
  4196. try {
  4197. var textureName = url.substring(5);
  4198. var blobURL;
  4199. try {
  4200. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4201. }
  4202. catch (ex) {
  4203. // Chrome doesn't support oneTimeOnly parameter
  4204. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4205. }
  4206. img.src = blobURL;
  4207. }
  4208. catch (e) {
  4209. img.src = null;
  4210. }
  4211. }
  4212. }
  4213. return img;
  4214. };
  4215. //ANY
  4216. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4217. url = Tools.CleanUrl(url);
  4218. var noIndexedDB = function () {
  4219. var request = new XMLHttpRequest();
  4220. var loadUrl = Tools.BaseUrl + url;
  4221. request.open('GET', loadUrl, true);
  4222. if (useArrayBuffer) {
  4223. request.responseType = "arraybuffer";
  4224. }
  4225. request.onprogress = progressCallBack;
  4226. request.onreadystatechange = function () {
  4227. if (request.readyState === 4) {
  4228. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  4229. callback(!useArrayBuffer ? request.responseText : request.response);
  4230. }
  4231. else {
  4232. if (onError) {
  4233. onError();
  4234. }
  4235. else {
  4236. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4237. }
  4238. }
  4239. }
  4240. };
  4241. request.send(null);
  4242. };
  4243. var loadFromIndexedDB = function () {
  4244. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4245. };
  4246. if (url.indexOf("file:") !== -1) {
  4247. var fileName = url.substring(5);
  4248. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  4249. }
  4250. else {
  4251. // Caching all files
  4252. if (database && database.enableSceneOffline) {
  4253. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4254. }
  4255. else {
  4256. noIndexedDB();
  4257. }
  4258. }
  4259. };
  4260. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4261. var reader = new FileReader();
  4262. reader.onload = function (e) {
  4263. //target doesn't have result from ts 1.3
  4264. callback(e.target['result']);
  4265. };
  4266. reader.onprogress = progressCallback;
  4267. reader.readAsDataURL(fileToLoad);
  4268. };
  4269. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4270. var reader = new FileReader();
  4271. reader.onerror = function (e) {
  4272. Tools.Log("Error while reading file: " + fileToLoad.name);
  4273. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  4274. };
  4275. reader.onload = function (e) {
  4276. //target doesn't have result from ts 1.3
  4277. callback(e.target['result']);
  4278. };
  4279. reader.onprogress = progressCallBack;
  4280. if (!useArrayBuffer) {
  4281. // Asynchronous read
  4282. reader.readAsText(fileToLoad);
  4283. }
  4284. else {
  4285. reader.readAsArrayBuffer(fileToLoad);
  4286. }
  4287. };
  4288. //returns a downloadable url to a file content.
  4289. Tools.FileAsURL = function (content) {
  4290. var fileBlob = new Blob([content]);
  4291. var url = window.URL || window.webkitURL;
  4292. var link = url.createObjectURL(fileBlob);
  4293. return link;
  4294. };
  4295. // Misc.
  4296. Tools.Format = function (value, decimals) {
  4297. if (decimals === void 0) { decimals = 2; }
  4298. return value.toFixed(decimals);
  4299. };
  4300. Tools.CheckExtends = function (v, min, max) {
  4301. if (v.x < min.x)
  4302. min.x = v.x;
  4303. if (v.y < min.y)
  4304. min.y = v.y;
  4305. if (v.z < min.z)
  4306. min.z = v.z;
  4307. if (v.x > max.x)
  4308. max.x = v.x;
  4309. if (v.y > max.y)
  4310. max.y = v.y;
  4311. if (v.z > max.z)
  4312. max.z = v.z;
  4313. };
  4314. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4315. for (var prop in source) {
  4316. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4317. continue;
  4318. }
  4319. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4320. continue;
  4321. }
  4322. var sourceValue = source[prop];
  4323. var typeOfSourceValue = typeof sourceValue;
  4324. if (typeOfSourceValue === "function") {
  4325. continue;
  4326. }
  4327. if (typeOfSourceValue === "object") {
  4328. if (sourceValue instanceof Array) {
  4329. destination[prop] = [];
  4330. if (sourceValue.length > 0) {
  4331. if (typeof sourceValue[0] == "object") {
  4332. for (var index = 0; index < sourceValue.length; index++) {
  4333. var clonedValue = cloneValue(sourceValue[index], destination);
  4334. if (destination[prop].indexOf(clonedValue) === -1) {
  4335. destination[prop].push(clonedValue);
  4336. }
  4337. }
  4338. }
  4339. else {
  4340. destination[prop] = sourceValue.slice(0);
  4341. }
  4342. }
  4343. }
  4344. else {
  4345. destination[prop] = cloneValue(sourceValue, destination);
  4346. }
  4347. }
  4348. else {
  4349. destination[prop] = sourceValue;
  4350. }
  4351. }
  4352. };
  4353. Tools.IsEmpty = function (obj) {
  4354. for (var i in obj) {
  4355. return false;
  4356. }
  4357. return true;
  4358. };
  4359. Tools.RegisterTopRootEvents = function (events) {
  4360. for (var index = 0; index < events.length; index++) {
  4361. var event = events[index];
  4362. window.addEventListener(event.name, event.handler, false);
  4363. try {
  4364. if (window.parent) {
  4365. window.parent.addEventListener(event.name, event.handler, false);
  4366. }
  4367. }
  4368. catch (e) {
  4369. }
  4370. }
  4371. };
  4372. Tools.UnregisterTopRootEvents = function (events) {
  4373. for (var index = 0; index < events.length; index++) {
  4374. var event = events[index];
  4375. window.removeEventListener(event.name, event.handler);
  4376. try {
  4377. if (window.parent) {
  4378. window.parent.removeEventListener(event.name, event.handler);
  4379. }
  4380. }
  4381. catch (e) {
  4382. }
  4383. }
  4384. };
  4385. Tools.DumpFramebuffer = function (width, height, engine, successCallback) {
  4386. // Read the contents of the framebuffer
  4387. var numberOfChannelsByLine = width * 4;
  4388. var halfHeight = height / 2;
  4389. //Reading datas from WebGL
  4390. var data = engine.readPixels(0, 0, width, height);
  4391. //To flip image on Y axis.
  4392. for (var i = 0; i < halfHeight; i++) {
  4393. for (var j = 0; j < numberOfChannelsByLine; j++) {
  4394. var currentCell = j + i * numberOfChannelsByLine;
  4395. var targetLine = height - i - 1;
  4396. var targetCell = j + targetLine * numberOfChannelsByLine;
  4397. var temp = data[currentCell];
  4398. data[currentCell] = data[targetCell];
  4399. data[targetCell] = temp;
  4400. }
  4401. }
  4402. // Create a 2D canvas to store the result
  4403. if (!screenshotCanvas) {
  4404. screenshotCanvas = document.createElement('canvas');
  4405. }
  4406. screenshotCanvas.width = width;
  4407. screenshotCanvas.height = height;
  4408. var context = screenshotCanvas.getContext('2d');
  4409. // Copy the pixels to a 2D canvas
  4410. var imageData = context.createImageData(width, height);
  4411. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  4412. var castData = imageData.data;
  4413. castData.set(data);
  4414. context.putImageData(imageData, 0, 0);
  4415. var base64Image = screenshotCanvas.toDataURL();
  4416. if (successCallback) {
  4417. successCallback(base64Image);
  4418. }
  4419. else {
  4420. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  4421. if (("download" in document.createElement("a"))) {
  4422. var a = window.document.createElement("a");
  4423. a.href = base64Image;
  4424. var date = new Date();
  4425. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  4426. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  4427. window.document.body.appendChild(a);
  4428. a.addEventListener("click", function () {
  4429. a.parentElement.removeChild(a);
  4430. });
  4431. a.click();
  4432. }
  4433. else {
  4434. var newWindow = window.open("");
  4435. var img = newWindow.document.createElement("img");
  4436. img.src = base64Image;
  4437. newWindow.document.body.appendChild(img);
  4438. }
  4439. }
  4440. };
  4441. Tools.CreateScreenshot = function (engine, camera, size, successCallback) {
  4442. var width;
  4443. var height;
  4444. //If a precision value is specified
  4445. if (size.precision) {
  4446. width = Math.round(engine.getRenderWidth() * size.precision);
  4447. height = Math.round(width / engine.getAspectRatio(camera));
  4448. size = { width: width, height: height };
  4449. }
  4450. else if (size.width && size.height) {
  4451. width = size.width;
  4452. height = size.height;
  4453. }
  4454. else if (size.width && !size.height) {
  4455. width = size.width;
  4456. height = Math.round(width / engine.getAspectRatio(camera));
  4457. size = { width: width, height: height };
  4458. }
  4459. else if (size.height && !size.width) {
  4460. height = size.height;
  4461. width = Math.round(height * engine.getAspectRatio(camera));
  4462. size = { width: width, height: height };
  4463. }
  4464. else if (!isNaN(size)) {
  4465. height = size;
  4466. width = size;
  4467. }
  4468. else {
  4469. Tools.Error("Invalid 'size' parameter !");
  4470. return;
  4471. }
  4472. var scene = camera.getScene();
  4473. var previousCamera = null;
  4474. if (scene.activeCamera !== camera) {
  4475. previousCamera = scene.activeCamera;
  4476. scene.activeCamera = camera;
  4477. }
  4478. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  4479. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  4480. texture.renderList = scene.meshes;
  4481. texture.onAfterRender = function () {
  4482. Tools.DumpFramebuffer(width, height, engine, successCallback);
  4483. };
  4484. scene.incrementRenderId();
  4485. texture.render(true);
  4486. texture.dispose();
  4487. if (previousCamera) {
  4488. scene.activeCamera = previousCamera;
  4489. }
  4490. camera.getProjectionMatrix(true); // Force cache refresh;
  4491. };
  4492. // XHR response validator for local file scenario
  4493. Tools.ValidateXHRData = function (xhr, dataType) {
  4494. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  4495. if (dataType === void 0) { dataType = 7; }
  4496. try {
  4497. if (dataType & 1) {
  4498. if (xhr.responseText && xhr.responseText.length > 0) {
  4499. return true;
  4500. }
  4501. else if (dataType === 1) {
  4502. return false;
  4503. }
  4504. }
  4505. if (dataType & 2) {
  4506. // Check header width and height since there is no "TGA" magic number
  4507. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  4508. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  4509. return true;
  4510. }
  4511. else if (dataType === 2) {
  4512. return false;
  4513. }
  4514. }
  4515. if (dataType & 4) {
  4516. // Check for the "DDS" magic number
  4517. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  4518. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  4519. return true;
  4520. }
  4521. else {
  4522. return false;
  4523. }
  4524. }
  4525. }
  4526. catch (e) {
  4527. }
  4528. return false;
  4529. };
  4530. Object.defineProperty(Tools, "NoneLogLevel", {
  4531. get: function () {
  4532. return Tools._NoneLogLevel;
  4533. },
  4534. enumerable: true,
  4535. configurable: true
  4536. });
  4537. Object.defineProperty(Tools, "MessageLogLevel", {
  4538. get: function () {
  4539. return Tools._MessageLogLevel;
  4540. },
  4541. enumerable: true,
  4542. configurable: true
  4543. });
  4544. Object.defineProperty(Tools, "WarningLogLevel", {
  4545. get: function () {
  4546. return Tools._WarningLogLevel;
  4547. },
  4548. enumerable: true,
  4549. configurable: true
  4550. });
  4551. Object.defineProperty(Tools, "ErrorLogLevel", {
  4552. get: function () {
  4553. return Tools._ErrorLogLevel;
  4554. },
  4555. enumerable: true,
  4556. configurable: true
  4557. });
  4558. Object.defineProperty(Tools, "AllLogLevel", {
  4559. get: function () {
  4560. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  4561. },
  4562. enumerable: true,
  4563. configurable: true
  4564. });
  4565. Tools._AddLogEntry = function (entry) {
  4566. Tools._LogCache = entry + Tools._LogCache;
  4567. if (Tools.OnNewCacheEntry) {
  4568. Tools.OnNewCacheEntry(entry);
  4569. }
  4570. };
  4571. Tools._FormatMessage = function (message) {
  4572. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  4573. var date = new Date();
  4574. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  4575. };
  4576. Tools._LogDisabled = function (message) {
  4577. // nothing to do
  4578. };
  4579. Tools._LogEnabled = function (message) {
  4580. var formattedMessage = Tools._FormatMessage(message);
  4581. console.log("BJS - " + formattedMessage);
  4582. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  4583. Tools._AddLogEntry(entry);
  4584. };
  4585. Tools._WarnDisabled = function (message) {
  4586. // nothing to do
  4587. };
  4588. Tools._WarnEnabled = function (message) {
  4589. var formattedMessage = Tools._FormatMessage(message);
  4590. console.warn("BJS - " + formattedMessage);
  4591. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  4592. Tools._AddLogEntry(entry);
  4593. };
  4594. Tools._ErrorDisabled = function (message) {
  4595. // nothing to do
  4596. };
  4597. Tools._ErrorEnabled = function (message) {
  4598. Tools.errorsCount++;
  4599. var formattedMessage = Tools._FormatMessage(message);
  4600. console.error("BJS - " + formattedMessage);
  4601. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  4602. Tools._AddLogEntry(entry);
  4603. };
  4604. Object.defineProperty(Tools, "LogCache", {
  4605. get: function () {
  4606. return Tools._LogCache;
  4607. },
  4608. enumerable: true,
  4609. configurable: true
  4610. });
  4611. Tools.ClearLogCache = function () {
  4612. Tools._LogCache = "";
  4613. Tools.errorsCount = 0;
  4614. };
  4615. Object.defineProperty(Tools, "LogLevels", {
  4616. set: function (level) {
  4617. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  4618. Tools.Log = Tools._LogEnabled;
  4619. }
  4620. else {
  4621. Tools.Log = Tools._LogDisabled;
  4622. }
  4623. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  4624. Tools.Warn = Tools._WarnEnabled;
  4625. }
  4626. else {
  4627. Tools.Warn = Tools._WarnDisabled;
  4628. }
  4629. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  4630. Tools.Error = Tools._ErrorEnabled;
  4631. }
  4632. else {
  4633. Tools.Error = Tools._ErrorDisabled;
  4634. }
  4635. },
  4636. enumerable: true,
  4637. configurable: true
  4638. });
  4639. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  4640. get: function () {
  4641. return Tools._PerformanceNoneLogLevel;
  4642. },
  4643. enumerable: true,
  4644. configurable: true
  4645. });
  4646. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  4647. get: function () {
  4648. return Tools._PerformanceUserMarkLogLevel;
  4649. },
  4650. enumerable: true,
  4651. configurable: true
  4652. });
  4653. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  4654. get: function () {
  4655. return Tools._PerformanceConsoleLogLevel;
  4656. },
  4657. enumerable: true,
  4658. configurable: true
  4659. });
  4660. Object.defineProperty(Tools, "PerformanceLogLevel", {
  4661. set: function (level) {
  4662. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  4663. Tools.StartPerformanceCounter = Tools._StartUserMark;
  4664. Tools.EndPerformanceCounter = Tools._EndUserMark;
  4665. return;
  4666. }
  4667. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  4668. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  4669. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  4670. return;
  4671. }
  4672. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4673. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4674. },
  4675. enumerable: true,
  4676. configurable: true
  4677. });
  4678. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  4679. };
  4680. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  4681. };
  4682. Tools._StartUserMark = function (counterName, condition) {
  4683. if (condition === void 0) { condition = true; }
  4684. if (!condition || !Tools._performance.mark) {
  4685. return;
  4686. }
  4687. Tools._performance.mark(counterName + "-Begin");
  4688. };
  4689. Tools._EndUserMark = function (counterName, condition) {
  4690. if (condition === void 0) { condition = true; }
  4691. if (!condition || !Tools._performance.mark) {
  4692. return;
  4693. }
  4694. Tools._performance.mark(counterName + "-End");
  4695. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  4696. };
  4697. Tools._StartPerformanceConsole = function (counterName, condition) {
  4698. if (condition === void 0) { condition = true; }
  4699. if (!condition) {
  4700. return;
  4701. }
  4702. Tools._StartUserMark(counterName, condition);
  4703. if (console.time) {
  4704. console.time(counterName);
  4705. }
  4706. };
  4707. Tools._EndPerformanceConsole = function (counterName, condition) {
  4708. if (condition === void 0) { condition = true; }
  4709. if (!condition) {
  4710. return;
  4711. }
  4712. Tools._EndUserMark(counterName, condition);
  4713. if (console.time) {
  4714. console.timeEnd(counterName);
  4715. }
  4716. };
  4717. Object.defineProperty(Tools, "Now", {
  4718. get: function () {
  4719. if (window.performance && window.performance.now) {
  4720. return window.performance.now();
  4721. }
  4722. return new Date().getTime();
  4723. },
  4724. enumerable: true,
  4725. configurable: true
  4726. });
  4727. Tools.BaseUrl = "";
  4728. Tools.CorsBehavior = "anonymous";
  4729. Tools.UseFallbackTexture = true;
  4730. // Logs
  4731. Tools._NoneLogLevel = 0;
  4732. Tools._MessageLogLevel = 1;
  4733. Tools._WarningLogLevel = 2;
  4734. Tools._ErrorLogLevel = 4;
  4735. Tools._LogCache = "";
  4736. Tools.errorsCount = 0;
  4737. Tools.Log = Tools._LogEnabled;
  4738. Tools.Warn = Tools._WarnEnabled;
  4739. Tools.Error = Tools._ErrorEnabled;
  4740. // Performances
  4741. Tools._PerformanceNoneLogLevel = 0;
  4742. Tools._PerformanceUserMarkLogLevel = 1;
  4743. Tools._PerformanceConsoleLogLevel = 2;
  4744. Tools._performance = window.performance;
  4745. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4746. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4747. return Tools;
  4748. })();
  4749. BABYLON.Tools = Tools;
  4750. /**
  4751. * An implementation of a loop for asynchronous functions.
  4752. */
  4753. var AsyncLoop = (function () {
  4754. /**
  4755. * Constroctor.
  4756. * @param iterations the number of iterations.
  4757. * @param _fn the function to run each iteration
  4758. * @param _successCallback the callback that will be called upon succesful execution
  4759. * @param offset starting offset.
  4760. */
  4761. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  4762. if (offset === void 0) { offset = 0; }
  4763. this.iterations = iterations;
  4764. this._fn = _fn;
  4765. this._successCallback = _successCallback;
  4766. this.index = offset - 1;
  4767. this._done = false;
  4768. }
  4769. /**
  4770. * Execute the next iteration. Must be called after the last iteration was finished.
  4771. */
  4772. AsyncLoop.prototype.executeNext = function () {
  4773. if (!this._done) {
  4774. if (this.index + 1 < this.iterations) {
  4775. ++this.index;
  4776. this._fn(this);
  4777. }
  4778. else {
  4779. this.breakLoop();
  4780. }
  4781. }
  4782. };
  4783. /**
  4784. * Break the loop and run the success callback.
  4785. */
  4786. AsyncLoop.prototype.breakLoop = function () {
  4787. this._done = true;
  4788. this._successCallback();
  4789. };
  4790. /**
  4791. * Helper function
  4792. */
  4793. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  4794. if (offset === void 0) { offset = 0; }
  4795. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  4796. loop.executeNext();
  4797. return loop;
  4798. };
  4799. /**
  4800. * A for-loop that will run a given number of iterations synchronous and the rest async.
  4801. * @param iterations total number of iterations
  4802. * @param syncedIterations number of synchronous iterations in each async iteration.
  4803. * @param fn the function to call each iteration.
  4804. * @param callback a success call back that will be called when iterating stops.
  4805. * @param breakFunction a break condition (optional)
  4806. * @param timeout timeout settings for the setTimeout function. default - 0.
  4807. * @constructor
  4808. */
  4809. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  4810. if (timeout === void 0) { timeout = 0; }
  4811. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  4812. if (breakFunction && breakFunction())
  4813. loop.breakLoop();
  4814. else {
  4815. setTimeout(function () {
  4816. for (var i = 0; i < syncedIterations; ++i) {
  4817. var iteration = (loop.index * syncedIterations) + i;
  4818. if (iteration >= iterations)
  4819. break;
  4820. fn(iteration);
  4821. if (breakFunction && breakFunction()) {
  4822. loop.breakLoop();
  4823. break;
  4824. }
  4825. }
  4826. loop.executeNext();
  4827. }, timeout);
  4828. }
  4829. }, callback);
  4830. };
  4831. return AsyncLoop;
  4832. })();
  4833. BABYLON.AsyncLoop = AsyncLoop;
  4834. })(BABYLON || (BABYLON = {}));
  4835. var BABYLON;
  4836. (function (BABYLON) {
  4837. var Internals;
  4838. (function (Internals) {
  4839. var _AlphaState = (function () {
  4840. function _AlphaState() {
  4841. this._isAlphaBlendDirty = false;
  4842. this._isBlendFunctionParametersDirty = false;
  4843. this._alphaBlend = false;
  4844. this._blendFunctionParameters = new Array(4);
  4845. }
  4846. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  4847. get: function () {
  4848. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  4849. },
  4850. enumerable: true,
  4851. configurable: true
  4852. });
  4853. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  4854. get: function () {
  4855. return this._alphaBlend;
  4856. },
  4857. set: function (value) {
  4858. if (this._alphaBlend === value) {
  4859. return;
  4860. }
  4861. this._alphaBlend = value;
  4862. this._isAlphaBlendDirty = true;
  4863. },
  4864. enumerable: true,
  4865. configurable: true
  4866. });
  4867. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  4868. if (this._blendFunctionParameters[0] === value0 &&
  4869. this._blendFunctionParameters[1] === value1 &&
  4870. this._blendFunctionParameters[2] === value2 &&
  4871. this._blendFunctionParameters[3] === value3) {
  4872. return;
  4873. }
  4874. this._blendFunctionParameters[0] = value0;
  4875. this._blendFunctionParameters[1] = value1;
  4876. this._blendFunctionParameters[2] = value2;
  4877. this._blendFunctionParameters[3] = value3;
  4878. this._isBlendFunctionParametersDirty = true;
  4879. };
  4880. _AlphaState.prototype.reset = function () {
  4881. this._alphaBlend = false;
  4882. this._blendFunctionParameters[0] = null;
  4883. this._blendFunctionParameters[1] = null;
  4884. this._blendFunctionParameters[2] = null;
  4885. this._blendFunctionParameters[3] = null;
  4886. this._isAlphaBlendDirty = true;
  4887. this._isBlendFunctionParametersDirty = false;
  4888. };
  4889. _AlphaState.prototype.apply = function (gl) {
  4890. if (!this.isDirty) {
  4891. return;
  4892. }
  4893. // Alpha blend
  4894. if (this._isAlphaBlendDirty) {
  4895. if (this._alphaBlend) {
  4896. gl.enable(gl.BLEND);
  4897. }
  4898. else {
  4899. gl.disable(gl.BLEND);
  4900. }
  4901. this._isAlphaBlendDirty = false;
  4902. }
  4903. // Alpha function
  4904. if (this._isBlendFunctionParametersDirty) {
  4905. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  4906. this._isBlendFunctionParametersDirty = false;
  4907. }
  4908. };
  4909. return _AlphaState;
  4910. })();
  4911. Internals._AlphaState = _AlphaState;
  4912. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  4913. })(BABYLON || (BABYLON = {}));
  4914. var BABYLON;
  4915. (function (BABYLON) {
  4916. var Internals;
  4917. (function (Internals) {
  4918. var _DepthCullingState = (function () {
  4919. function _DepthCullingState() {
  4920. this._isDepthTestDirty = false;
  4921. this._isDepthMaskDirty = false;
  4922. this._isDepthFuncDirty = false;
  4923. this._isCullFaceDirty = false;
  4924. this._isCullDirty = false;
  4925. this._isZOffsetDirty = false;
  4926. }
  4927. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  4928. get: function () {
  4929. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  4930. },
  4931. enumerable: true,
  4932. configurable: true
  4933. });
  4934. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  4935. get: function () {
  4936. return this._zOffset;
  4937. },
  4938. set: function (value) {
  4939. if (this._zOffset === value) {
  4940. return;
  4941. }
  4942. this._zOffset = value;
  4943. this._isZOffsetDirty = true;
  4944. },
  4945. enumerable: true,
  4946. configurable: true
  4947. });
  4948. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  4949. get: function () {
  4950. return this._cullFace;
  4951. },
  4952. set: function (value) {
  4953. if (this._cullFace === value) {
  4954. return;
  4955. }
  4956. this._cullFace = value;
  4957. this._isCullFaceDirty = true;
  4958. },
  4959. enumerable: true,
  4960. configurable: true
  4961. });
  4962. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  4963. get: function () {
  4964. return this._cull;
  4965. },
  4966. set: function (value) {
  4967. if (this._cull === value) {
  4968. return;
  4969. }
  4970. this._cull = value;
  4971. this._isCullDirty = true;
  4972. },
  4973. enumerable: true,
  4974. configurable: true
  4975. });
  4976. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  4977. get: function () {
  4978. return this._depthFunc;
  4979. },
  4980. set: function (value) {
  4981. if (this._depthFunc === value) {
  4982. return;
  4983. }
  4984. this._depthFunc = value;
  4985. this._isDepthFuncDirty = true;
  4986. },
  4987. enumerable: true,
  4988. configurable: true
  4989. });
  4990. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  4991. get: function () {
  4992. return this._depthMask;
  4993. },
  4994. set: function (value) {
  4995. if (this._depthMask === value) {
  4996. return;
  4997. }
  4998. this._depthMask = value;
  4999. this._isDepthMaskDirty = true;
  5000. },
  5001. enumerable: true,
  5002. configurable: true
  5003. });
  5004. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  5005. get: function () {
  5006. return this._depthTest;
  5007. },
  5008. set: function (value) {
  5009. if (this._depthTest === value) {
  5010. return;
  5011. }
  5012. this._depthTest = value;
  5013. this._isDepthTestDirty = true;
  5014. },
  5015. enumerable: true,
  5016. configurable: true
  5017. });
  5018. _DepthCullingState.prototype.reset = function () {
  5019. this._depthMask = true;
  5020. this._depthTest = true;
  5021. this._depthFunc = null;
  5022. this._cull = null;
  5023. this._cullFace = null;
  5024. this._zOffset = 0;
  5025. this._isDepthTestDirty = true;
  5026. this._isDepthMaskDirty = true;
  5027. this._isDepthFuncDirty = false;
  5028. this._isCullFaceDirty = false;
  5029. this._isCullDirty = false;
  5030. this._isZOffsetDirty = false;
  5031. };
  5032. _DepthCullingState.prototype.apply = function (gl) {
  5033. if (!this.isDirty) {
  5034. return;
  5035. }
  5036. // Cull
  5037. if (this._isCullDirty) {
  5038. if (this.cull) {
  5039. gl.enable(gl.CULL_FACE);
  5040. }
  5041. else {
  5042. gl.disable(gl.CULL_FACE);
  5043. }
  5044. this._isCullDirty = false;
  5045. }
  5046. // Cull face
  5047. if (this._isCullFaceDirty) {
  5048. gl.cullFace(this.cullFace);
  5049. this._isCullFaceDirty = false;
  5050. }
  5051. // Depth mask
  5052. if (this._isDepthMaskDirty) {
  5053. gl.depthMask(this.depthMask);
  5054. this._isDepthMaskDirty = false;
  5055. }
  5056. // Depth test
  5057. if (this._isDepthTestDirty) {
  5058. if (this.depthTest) {
  5059. gl.enable(gl.DEPTH_TEST);
  5060. }
  5061. else {
  5062. gl.disable(gl.DEPTH_TEST);
  5063. }
  5064. this._isDepthTestDirty = false;
  5065. }
  5066. // Depth func
  5067. if (this._isDepthFuncDirty) {
  5068. gl.depthFunc(this.depthFunc);
  5069. this._isDepthFuncDirty = false;
  5070. }
  5071. // zOffset
  5072. if (this._isZOffsetDirty) {
  5073. if (this.zOffset) {
  5074. gl.enable(gl.POLYGON_OFFSET_FILL);
  5075. gl.polygonOffset(this.zOffset, 0);
  5076. }
  5077. else {
  5078. gl.disable(gl.POLYGON_OFFSET_FILL);
  5079. }
  5080. this._isZOffsetDirty = false;
  5081. }
  5082. };
  5083. return _DepthCullingState;
  5084. })();
  5085. Internals._DepthCullingState = _DepthCullingState;
  5086. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5087. })(BABYLON || (BABYLON = {}));
  5088. var BABYLON;
  5089. (function (BABYLON) {
  5090. var compileShader = function (gl, source, type, defines) {
  5091. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  5092. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  5093. gl.compileShader(shader);
  5094. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  5095. throw new Error(gl.getShaderInfoLog(shader));
  5096. }
  5097. return shader;
  5098. };
  5099. var getWebGLTextureType = function (gl, type) {
  5100. var textureType = gl.UNSIGNED_BYTE;
  5101. if (type === Engine.TEXTURETYPE_FLOAT)
  5102. textureType = gl.FLOAT;
  5103. return textureType;
  5104. };
  5105. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  5106. var magFilter = gl.NEAREST;
  5107. var minFilter = gl.NEAREST;
  5108. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  5109. magFilter = gl.LINEAR;
  5110. if (generateMipMaps) {
  5111. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  5112. }
  5113. else {
  5114. minFilter = gl.LINEAR;
  5115. }
  5116. }
  5117. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  5118. magFilter = gl.LINEAR;
  5119. if (generateMipMaps) {
  5120. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  5121. }
  5122. else {
  5123. minFilter = gl.LINEAR;
  5124. }
  5125. }
  5126. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5127. magFilter = gl.NEAREST;
  5128. if (generateMipMaps) {
  5129. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  5130. }
  5131. else {
  5132. minFilter = gl.NEAREST;
  5133. }
  5134. }
  5135. return {
  5136. min: minFilter,
  5137. mag: magFilter
  5138. };
  5139. };
  5140. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, onLoad, samplingMode) {
  5141. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  5142. var engine = scene.getEngine();
  5143. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  5144. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  5145. gl.bindTexture(gl.TEXTURE_2D, texture);
  5146. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  5147. texture._baseWidth = width;
  5148. texture._baseHeight = height;
  5149. texture._width = potWidth;
  5150. texture._height = potHeight;
  5151. texture.isReady = true;
  5152. processFunction(potWidth, potHeight);
  5153. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  5154. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5155. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5156. if (!noMipmap && !isCompressed) {
  5157. gl.generateMipmap(gl.TEXTURE_2D);
  5158. }
  5159. gl.bindTexture(gl.TEXTURE_2D, null);
  5160. engine.resetTextureCache();
  5161. scene._removePendingData(texture);
  5162. if (onLoad) {
  5163. onLoad();
  5164. }
  5165. };
  5166. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  5167. var img;
  5168. var onload = function () {
  5169. loadedImages[index] = img;
  5170. loadedImages._internalCount++;
  5171. scene._removePendingData(img);
  5172. if (loadedImages._internalCount === 6) {
  5173. onfinish(loadedImages);
  5174. }
  5175. };
  5176. var onerror = function () {
  5177. scene._removePendingData(img);
  5178. };
  5179. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  5180. scene._addPendingData(img);
  5181. };
  5182. var cascadeLoad = function (rootUrl, scene, onfinish, files) {
  5183. var loadedImages = [];
  5184. loadedImages._internalCount = 0;
  5185. for (var index = 0; index < 6; index++) {
  5186. partialLoad(files[index], index, loadedImages, scene, onfinish);
  5187. }
  5188. };
  5189. var EngineCapabilities = (function () {
  5190. function EngineCapabilities() {
  5191. }
  5192. return EngineCapabilities;
  5193. })();
  5194. BABYLON.EngineCapabilities = EngineCapabilities;
  5195. /**
  5196. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  5197. */
  5198. var Engine = (function () {
  5199. /**
  5200. * @constructor
  5201. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  5202. * @param {boolean} [antialias] - enable antialias
  5203. * @param options - further options to be sent to the getContext function
  5204. */
  5205. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  5206. var _this = this;
  5207. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = true; }
  5208. // Public members
  5209. this.isFullscreen = false;
  5210. this.isPointerLock = false;
  5211. this.cullBackFaces = true;
  5212. this.renderEvenInBackground = true;
  5213. // To enable/disable IDB support and avoid XHR on .manifest
  5214. this.enableOfflineSupport = true;
  5215. this.scenes = new Array();
  5216. this._windowIsBackground = false;
  5217. this._webGLVersion = "1.0";
  5218. this._drawCalls = 0;
  5219. this._renderingQueueLaunched = false;
  5220. this._activeRenderLoops = [];
  5221. // FPS
  5222. this.fpsRange = 60;
  5223. this.previousFramesDuration = [];
  5224. this.fps = 60;
  5225. this.deltaTime = 0;
  5226. // States
  5227. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  5228. this._alphaState = new BABYLON.Internals._AlphaState();
  5229. this._alphaMode = Engine.ALPHA_DISABLE;
  5230. // Cache
  5231. this._loadedTexturesCache = new Array();
  5232. this._maxTextureChannels = 16;
  5233. this._activeTexturesCache = new Array(this._maxTextureChannels);
  5234. this._compiledEffects = {};
  5235. this._uintIndicesCurrentlySet = false;
  5236. this._renderingCanvas = canvas;
  5237. options = options || {};
  5238. options.antialias = antialias;
  5239. if (options.preserveDrawingBuffer === undefined) {
  5240. options.preserveDrawingBuffer = false;
  5241. }
  5242. // GL
  5243. //try {
  5244. // this._gl = <WebGLRenderingContext>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  5245. // if (this._gl) {
  5246. // this._webGLVersion = "2.0";
  5247. // }
  5248. //} catch (e) {
  5249. // // Do nothing
  5250. //}
  5251. if (!this._gl) {
  5252. try {
  5253. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  5254. }
  5255. catch (e) {
  5256. throw new Error("WebGL not supported");
  5257. }
  5258. }
  5259. if (!this._gl) {
  5260. throw new Error("WebGL not supported");
  5261. }
  5262. this._onBlur = function () {
  5263. _this._windowIsBackground = true;
  5264. };
  5265. this._onFocus = function () {
  5266. _this._windowIsBackground = false;
  5267. };
  5268. window.addEventListener("blur", this._onBlur);
  5269. window.addEventListener("focus", this._onFocus);
  5270. // Viewport
  5271. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  5272. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  5273. this.resize();
  5274. // Caps
  5275. this._caps = new EngineCapabilities();
  5276. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  5277. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  5278. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  5279. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  5280. // Infos
  5281. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  5282. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  5283. if (rendererInfo != null) {
  5284. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  5285. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  5286. }
  5287. if (!this._glVendor) {
  5288. this._glVendor = "Unknown vendor";
  5289. }
  5290. if (!this._glRenderer) {
  5291. this._glRenderer = "Unknown renderer";
  5292. }
  5293. // Extensions
  5294. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  5295. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  5296. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  5297. 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');
  5298. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  5299. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  5300. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  5301. this._caps.fragmentDepthSupported = this._gl.getExtension('EXT_frag_depth') !== null;
  5302. this._caps.highPrecisionShaderSupported = true;
  5303. this._caps.drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  5304. this._caps.textureFloatLinearFiltering = this._gl.getExtension('OES_texture_float_linear');
  5305. this._caps.textureLOD = this._gl.getExtension('EXT_shader_texture_lod');
  5306. if (this._gl.getShaderPrecisionFormat) {
  5307. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  5308. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  5309. }
  5310. // Depth buffer
  5311. this.setDepthBuffer(true);
  5312. this.setDepthFunctionToLessOrEqual();
  5313. this.setDepthWrite(true);
  5314. // Fullscreen
  5315. this._onFullscreenChange = function () {
  5316. if (document.fullscreen !== undefined) {
  5317. _this.isFullscreen = document.fullscreen;
  5318. }
  5319. else if (document.mozFullScreen !== undefined) {
  5320. _this.isFullscreen = document.mozFullScreen;
  5321. }
  5322. else if (document.webkitIsFullScreen !== undefined) {
  5323. _this.isFullscreen = document.webkitIsFullScreen;
  5324. }
  5325. else if (document.msIsFullScreen !== undefined) {
  5326. _this.isFullscreen = document.msIsFullScreen;
  5327. }
  5328. // Pointer lock
  5329. if (_this.isFullscreen && _this._pointerLockRequested) {
  5330. canvas.requestPointerLock = canvas.requestPointerLock ||
  5331. canvas.msRequestPointerLock ||
  5332. canvas.mozRequestPointerLock ||
  5333. canvas.webkitRequestPointerLock;
  5334. if (canvas.requestPointerLock) {
  5335. canvas.requestPointerLock();
  5336. }
  5337. }
  5338. };
  5339. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  5340. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  5341. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  5342. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  5343. // Pointer lock
  5344. this._onPointerLockChange = function () {
  5345. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  5346. document.webkitPointerLockElement === canvas ||
  5347. document.msPointerLockElement === canvas ||
  5348. document.pointerLockElement === canvas);
  5349. };
  5350. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  5351. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  5352. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  5353. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  5354. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  5355. Engine.audioEngine = new BABYLON.AudioEngine();
  5356. }
  5357. //default loading screen
  5358. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  5359. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  5360. }
  5361. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  5362. get: function () {
  5363. return Engine._ALPHA_DISABLE;
  5364. },
  5365. enumerable: true,
  5366. configurable: true
  5367. });
  5368. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  5369. get: function () {
  5370. return Engine._ALPHA_ONEONE;
  5371. },
  5372. enumerable: true,
  5373. configurable: true
  5374. });
  5375. Object.defineProperty(Engine, "ALPHA_ADD", {
  5376. get: function () {
  5377. return Engine._ALPHA_ADD;
  5378. },
  5379. enumerable: true,
  5380. configurable: true
  5381. });
  5382. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  5383. get: function () {
  5384. return Engine._ALPHA_COMBINE;
  5385. },
  5386. enumerable: true,
  5387. configurable: true
  5388. });
  5389. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  5390. get: function () {
  5391. return Engine._ALPHA_SUBTRACT;
  5392. },
  5393. enumerable: true,
  5394. configurable: true
  5395. });
  5396. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  5397. get: function () {
  5398. return Engine._ALPHA_MULTIPLY;
  5399. },
  5400. enumerable: true,
  5401. configurable: true
  5402. });
  5403. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  5404. get: function () {
  5405. return Engine._ALPHA_MAXIMIZED;
  5406. },
  5407. enumerable: true,
  5408. configurable: true
  5409. });
  5410. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  5411. get: function () {
  5412. return Engine._DELAYLOADSTATE_NONE;
  5413. },
  5414. enumerable: true,
  5415. configurable: true
  5416. });
  5417. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  5418. get: function () {
  5419. return Engine._DELAYLOADSTATE_LOADED;
  5420. },
  5421. enumerable: true,
  5422. configurable: true
  5423. });
  5424. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  5425. get: function () {
  5426. return Engine._DELAYLOADSTATE_LOADING;
  5427. },
  5428. enumerable: true,
  5429. configurable: true
  5430. });
  5431. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  5432. get: function () {
  5433. return Engine._DELAYLOADSTATE_NOTLOADED;
  5434. },
  5435. enumerable: true,
  5436. configurable: true
  5437. });
  5438. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  5439. get: function () {
  5440. return Engine._TEXTUREFORMAT_ALPHA;
  5441. },
  5442. enumerable: true,
  5443. configurable: true
  5444. });
  5445. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  5446. get: function () {
  5447. return Engine._TEXTUREFORMAT_LUMINANCE;
  5448. },
  5449. enumerable: true,
  5450. configurable: true
  5451. });
  5452. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  5453. get: function () {
  5454. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  5455. },
  5456. enumerable: true,
  5457. configurable: true
  5458. });
  5459. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  5460. get: function () {
  5461. return Engine._TEXTUREFORMAT_RGB;
  5462. },
  5463. enumerable: true,
  5464. configurable: true
  5465. });
  5466. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  5467. get: function () {
  5468. return Engine._TEXTUREFORMAT_RGBA;
  5469. },
  5470. enumerable: true,
  5471. configurable: true
  5472. });
  5473. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  5474. get: function () {
  5475. return Engine._TEXTURETYPE_UNSIGNED_INT;
  5476. },
  5477. enumerable: true,
  5478. configurable: true
  5479. });
  5480. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  5481. get: function () {
  5482. return Engine._TEXTURETYPE_FLOAT;
  5483. },
  5484. enumerable: true,
  5485. configurable: true
  5486. });
  5487. Object.defineProperty(Engine, "Version", {
  5488. get: function () {
  5489. return "2.4.0-alpha";
  5490. },
  5491. enumerable: true,
  5492. configurable: true
  5493. });
  5494. Object.defineProperty(Engine.prototype, "webGLVersion", {
  5495. get: function () {
  5496. return this._webGLVersion;
  5497. },
  5498. enumerable: true,
  5499. configurable: true
  5500. });
  5501. Engine.prototype._prepareWorkingCanvas = function () {
  5502. if (this._workingCanvas) {
  5503. return;
  5504. }
  5505. this._workingCanvas = document.createElement("canvas");
  5506. this._workingContext = this._workingCanvas.getContext("2d");
  5507. };
  5508. Engine.prototype.resetTextureCache = function () {
  5509. for (var index = 0; index < this._maxTextureChannels; index++) {
  5510. this._activeTexturesCache[index] = null;
  5511. }
  5512. };
  5513. Engine.prototype.getGlInfo = function () {
  5514. return {
  5515. vendor: this._glVendor,
  5516. renderer: this._glRenderer,
  5517. version: this._glVersion
  5518. };
  5519. };
  5520. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  5521. if (useScreen === void 0) { useScreen = false; }
  5522. var viewport = camera.viewport;
  5523. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  5524. };
  5525. Engine.prototype.getRenderWidth = function (useScreen) {
  5526. if (useScreen === void 0) { useScreen = false; }
  5527. if (!useScreen && this._currentRenderTarget) {
  5528. return this._currentRenderTarget._width;
  5529. }
  5530. return this._renderingCanvas.width;
  5531. };
  5532. Engine.prototype.getRenderHeight = function (useScreen) {
  5533. if (useScreen === void 0) { useScreen = false; }
  5534. if (!useScreen && this._currentRenderTarget) {
  5535. return this._currentRenderTarget._height;
  5536. }
  5537. return this._renderingCanvas.height;
  5538. };
  5539. Engine.prototype.getRenderingCanvas = function () {
  5540. return this._renderingCanvas;
  5541. };
  5542. Engine.prototype.getRenderingCanvasClientRect = function () {
  5543. return this._renderingCanvas.getBoundingClientRect();
  5544. };
  5545. Engine.prototype.setHardwareScalingLevel = function (level) {
  5546. this._hardwareScalingLevel = level;
  5547. this.resize();
  5548. };
  5549. Engine.prototype.getHardwareScalingLevel = function () {
  5550. return this._hardwareScalingLevel;
  5551. };
  5552. Engine.prototype.getLoadedTexturesCache = function () {
  5553. return this._loadedTexturesCache;
  5554. };
  5555. Engine.prototype.getCaps = function () {
  5556. return this._caps;
  5557. };
  5558. Object.defineProperty(Engine.prototype, "drawCalls", {
  5559. get: function () {
  5560. return this._drawCalls;
  5561. },
  5562. enumerable: true,
  5563. configurable: true
  5564. });
  5565. // Methods
  5566. Engine.prototype.resetDrawCalls = function () {
  5567. this._drawCalls = 0;
  5568. };
  5569. Engine.prototype.setDepthFunctionToGreater = function () {
  5570. this._depthCullingState.depthFunc = this._gl.GREATER;
  5571. };
  5572. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  5573. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  5574. };
  5575. Engine.prototype.setDepthFunctionToLess = function () {
  5576. this._depthCullingState.depthFunc = this._gl.LESS;
  5577. };
  5578. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  5579. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  5580. };
  5581. /**
  5582. * stop executing a render loop function and remove it from the execution array
  5583. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  5584. */
  5585. Engine.prototype.stopRenderLoop = function (renderFunction) {
  5586. if (!renderFunction) {
  5587. this._activeRenderLoops = [];
  5588. return;
  5589. }
  5590. var index = this._activeRenderLoops.indexOf(renderFunction);
  5591. if (index >= 0) {
  5592. this._activeRenderLoops.splice(index, 1);
  5593. }
  5594. };
  5595. Engine.prototype._renderLoop = function () {
  5596. var shouldRender = true;
  5597. if (!this.renderEvenInBackground && this._windowIsBackground) {
  5598. shouldRender = false;
  5599. }
  5600. if (shouldRender) {
  5601. // Start new frame
  5602. this.beginFrame();
  5603. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  5604. var renderFunction = this._activeRenderLoops[index];
  5605. renderFunction();
  5606. }
  5607. // Present
  5608. this.endFrame();
  5609. }
  5610. if (this._activeRenderLoops.length > 0) {
  5611. // Register new frame
  5612. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5613. }
  5614. else {
  5615. this._renderingQueueLaunched = false;
  5616. }
  5617. };
  5618. /**
  5619. * Register and execute a render loop. The engine can have more than one render function.
  5620. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  5621. * @example
  5622. * engine.runRenderLoop(function () {
  5623. * scene.render()
  5624. * })
  5625. */
  5626. Engine.prototype.runRenderLoop = function (renderFunction) {
  5627. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  5628. return;
  5629. }
  5630. this._activeRenderLoops.push(renderFunction);
  5631. if (!this._renderingQueueLaunched) {
  5632. this._renderingQueueLaunched = true;
  5633. this._bindedRenderFunction = this._renderLoop.bind(this);
  5634. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5635. }
  5636. };
  5637. /**
  5638. * Toggle full screen mode.
  5639. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  5640. */
  5641. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  5642. if (this.isFullscreen) {
  5643. BABYLON.Tools.ExitFullscreen();
  5644. }
  5645. else {
  5646. this._pointerLockRequested = requestPointerLock;
  5647. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  5648. }
  5649. };
  5650. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  5651. this.applyStates();
  5652. if (backBuffer) {
  5653. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  5654. }
  5655. if (depthStencil && this._depthCullingState.depthMask) {
  5656. this._gl.clearDepth(1.0);
  5657. }
  5658. var mode = 0;
  5659. if (backBuffer) {
  5660. mode |= this._gl.COLOR_BUFFER_BIT;
  5661. }
  5662. if (depthStencil && this._depthCullingState.depthMask) {
  5663. mode |= this._gl.DEPTH_BUFFER_BIT;
  5664. }
  5665. this._gl.clear(mode);
  5666. };
  5667. /**
  5668. * Set the WebGL's viewport
  5669. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  5670. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  5671. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  5672. */
  5673. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  5674. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  5675. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  5676. var x = viewport.x || 0;
  5677. var y = viewport.y || 0;
  5678. this._cachedViewport = viewport;
  5679. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  5680. };
  5681. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  5682. this._cachedViewport = null;
  5683. this._gl.viewport(x, y, width, height);
  5684. };
  5685. Engine.prototype.beginFrame = function () {
  5686. this._measureFps();
  5687. };
  5688. Engine.prototype.endFrame = function () {
  5689. //this.flushFramebuffer();
  5690. };
  5691. /**
  5692. * resize the view according to the canvas' size.
  5693. * @example
  5694. * window.addEventListener("resize", function () {
  5695. * engine.resize();
  5696. * });
  5697. */
  5698. Engine.prototype.resize = function () {
  5699. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  5700. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  5701. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  5702. for (var index = 0; index < this.scenes.length; index++) {
  5703. var scene = this.scenes[index];
  5704. if (scene.debugLayer.isVisible()) {
  5705. scene.debugLayer._syncPositions();
  5706. }
  5707. }
  5708. };
  5709. /**
  5710. * force a specific size of the canvas
  5711. * @param {number} width - the new canvas' width
  5712. * @param {number} height - the new canvas' height
  5713. */
  5714. Engine.prototype.setSize = function (width, height) {
  5715. this._renderingCanvas.width = width;
  5716. this._renderingCanvas.height = height;
  5717. for (var index = 0; index < this.scenes.length; index++) {
  5718. var scene = this.scenes[index];
  5719. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  5720. var cam = scene.cameras[camIndex];
  5721. cam._currentRenderId = 0;
  5722. }
  5723. }
  5724. };
  5725. Engine.prototype.bindFramebuffer = function (texture, faceIndex) {
  5726. this._currentRenderTarget = texture;
  5727. var gl = this._gl;
  5728. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  5729. if (texture.isCube) {
  5730. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  5731. }
  5732. else {
  5733. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  5734. }
  5735. this._gl.viewport(0, 0, texture._width, texture._height);
  5736. this.wipeCaches();
  5737. };
  5738. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  5739. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  5740. this._currentRenderTarget = null;
  5741. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  5742. var gl = this._gl;
  5743. gl.bindTexture(gl.TEXTURE_2D, texture);
  5744. gl.generateMipmap(gl.TEXTURE_2D);
  5745. gl.bindTexture(gl.TEXTURE_2D, null);
  5746. }
  5747. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5748. };
  5749. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  5750. if (texture.generateMipMaps) {
  5751. var gl = this._gl;
  5752. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  5753. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  5754. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  5755. }
  5756. };
  5757. Engine.prototype.flushFramebuffer = function () {
  5758. this._gl.flush();
  5759. };
  5760. Engine.prototype.restoreDefaultFramebuffer = function () {
  5761. this._currentRenderTarget = null;
  5762. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5763. this.setViewport(this._cachedViewport);
  5764. this.wipeCaches();
  5765. };
  5766. // VBOs
  5767. Engine.prototype._resetVertexBufferBinding = function () {
  5768. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  5769. this._cachedVertexBuffers = null;
  5770. };
  5771. Engine.prototype.createVertexBuffer = function (vertices) {
  5772. var vbo = this._gl.createBuffer();
  5773. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5774. if (vertices instanceof Float32Array) {
  5775. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  5776. }
  5777. else {
  5778. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  5779. }
  5780. this._resetVertexBufferBinding();
  5781. vbo.references = 1;
  5782. return vbo;
  5783. };
  5784. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  5785. var vbo = this._gl.createBuffer();
  5786. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5787. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5788. this._resetVertexBufferBinding();
  5789. vbo.references = 1;
  5790. return vbo;
  5791. };
  5792. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  5793. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5794. if (offset === undefined) {
  5795. offset = 0;
  5796. }
  5797. if (vertices instanceof Float32Array) {
  5798. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  5799. }
  5800. else {
  5801. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  5802. }
  5803. this._resetVertexBufferBinding();
  5804. };
  5805. Engine.prototype._resetIndexBufferBinding = function () {
  5806. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  5807. this._cachedIndexBuffer = null;
  5808. };
  5809. Engine.prototype.createIndexBuffer = function (indices) {
  5810. var vbo = this._gl.createBuffer();
  5811. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  5812. // Check for 32 bits indices
  5813. var arrayBuffer;
  5814. var need32Bits = false;
  5815. if (this._caps.uintIndices) {
  5816. for (var index = 0; index < indices.length; index++) {
  5817. if (indices[index] > 65535) {
  5818. need32Bits = true;
  5819. break;
  5820. }
  5821. }
  5822. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  5823. }
  5824. else {
  5825. arrayBuffer = new Uint16Array(indices);
  5826. }
  5827. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  5828. this._resetIndexBufferBinding();
  5829. vbo.references = 1;
  5830. vbo.is32Bits = need32Bits;
  5831. return vbo;
  5832. };
  5833. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  5834. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  5835. this._cachedVertexBuffers = vertexBuffer;
  5836. this._cachedEffectForVertexBuffers = effect;
  5837. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5838. var offset = 0;
  5839. for (var index = 0; index < vertexDeclaration.length; index++) {
  5840. var order = effect.getAttributeLocation(index);
  5841. if (order >= 0) {
  5842. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  5843. }
  5844. offset += vertexDeclaration[index] * 4;
  5845. }
  5846. }
  5847. if (this._cachedIndexBuffer !== indexBuffer) {
  5848. this._cachedIndexBuffer = indexBuffer;
  5849. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  5850. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  5851. }
  5852. };
  5853. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  5854. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  5855. this._cachedVertexBuffers = vertexBuffers;
  5856. this._cachedEffectForVertexBuffers = effect;
  5857. var attributes = effect.getAttributesNames();
  5858. for (var index = 0; index < attributes.length; index++) {
  5859. var order = effect.getAttributeLocation(index);
  5860. if (order >= 0) {
  5861. var vertexBuffer = vertexBuffers[attributes[index]];
  5862. if (!vertexBuffer) {
  5863. continue;
  5864. }
  5865. var stride = vertexBuffer.getStrideSize();
  5866. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  5867. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  5868. }
  5869. }
  5870. }
  5871. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  5872. this._cachedIndexBuffer = indexBuffer;
  5873. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  5874. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  5875. }
  5876. };
  5877. Engine.prototype._releaseBuffer = function (buffer) {
  5878. buffer.references--;
  5879. if (buffer.references === 0) {
  5880. this._gl.deleteBuffer(buffer);
  5881. return true;
  5882. }
  5883. return false;
  5884. };
  5885. Engine.prototype.createInstancesBuffer = function (capacity) {
  5886. var buffer = this._gl.createBuffer();
  5887. buffer.capacity = capacity;
  5888. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  5889. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5890. return buffer;
  5891. };
  5892. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  5893. this._gl.deleteBuffer(buffer);
  5894. };
  5895. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  5896. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  5897. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  5898. for (var index = 0; index < 4; index++) {
  5899. var offsetLocation = offsetLocations[index];
  5900. this._gl.enableVertexAttribArray(offsetLocation);
  5901. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  5902. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  5903. }
  5904. };
  5905. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  5906. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  5907. for (var index = 0; index < 4; index++) {
  5908. var offsetLocation = offsetLocations[index];
  5909. this._gl.disableVertexAttribArray(offsetLocation);
  5910. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  5911. }
  5912. };
  5913. Engine.prototype.applyStates = function () {
  5914. this._depthCullingState.apply(this._gl);
  5915. this._alphaState.apply(this._gl);
  5916. };
  5917. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  5918. // Apply states
  5919. this.applyStates();
  5920. this._drawCalls++;
  5921. // Render
  5922. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  5923. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  5924. if (instancesCount) {
  5925. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  5926. return;
  5927. }
  5928. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  5929. };
  5930. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  5931. // Apply states
  5932. this.applyStates();
  5933. this._drawCalls++;
  5934. if (instancesCount) {
  5935. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  5936. return;
  5937. }
  5938. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  5939. };
  5940. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  5941. // Apply states
  5942. this.applyStates();
  5943. this._drawCalls++;
  5944. if (instancesCount) {
  5945. this._caps.instancedArrays.drawArraysInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  5946. return;
  5947. }
  5948. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  5949. };
  5950. // Shaders
  5951. Engine.prototype._releaseEffect = function (effect) {
  5952. if (this._compiledEffects[effect._key]) {
  5953. delete this._compiledEffects[effect._key];
  5954. if (effect.getProgram()) {
  5955. this._gl.deleteProgram(effect.getProgram());
  5956. }
  5957. }
  5958. };
  5959. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  5960. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  5961. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  5962. var name = vertex + "+" + fragment + "@" + defines;
  5963. if (this._compiledEffects[name]) {
  5964. return this._compiledEffects[name];
  5965. }
  5966. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  5967. effect._key = name;
  5968. this._compiledEffects[name] = effect;
  5969. return effect;
  5970. };
  5971. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  5972. if (uniformsNames === void 0) { uniformsNames = []; }
  5973. if (samplers === void 0) { samplers = []; }
  5974. if (defines === void 0) { defines = ""; }
  5975. return this.createEffect({
  5976. vertex: "particles",
  5977. fragmentElement: fragmentName
  5978. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  5979. };
  5980. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  5981. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  5982. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  5983. var shaderProgram = this._gl.createProgram();
  5984. this._gl.attachShader(shaderProgram, vertexShader);
  5985. this._gl.attachShader(shaderProgram, fragmentShader);
  5986. this._gl.linkProgram(shaderProgram);
  5987. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  5988. if (!linked) {
  5989. var error = this._gl.getProgramInfoLog(shaderProgram);
  5990. if (error) {
  5991. throw new Error(error);
  5992. }
  5993. }
  5994. this._gl.deleteShader(vertexShader);
  5995. this._gl.deleteShader(fragmentShader);
  5996. return shaderProgram;
  5997. };
  5998. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  5999. var results = [];
  6000. for (var index = 0; index < uniformsNames.length; index++) {
  6001. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  6002. }
  6003. return results;
  6004. };
  6005. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  6006. var results = [];
  6007. for (var index = 0; index < attributesNames.length; index++) {
  6008. try {
  6009. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  6010. }
  6011. catch (e) {
  6012. results.push(-1);
  6013. }
  6014. }
  6015. return results;
  6016. };
  6017. Engine.prototype.enableEffect = function (effect) {
  6018. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  6019. if (effect && effect.onBind) {
  6020. effect.onBind(effect);
  6021. }
  6022. return;
  6023. }
  6024. this._vertexAttribArrays = this._vertexAttribArrays || [];
  6025. // Use program
  6026. this._gl.useProgram(effect.getProgram());
  6027. for (var i in this._vertexAttribArrays) {
  6028. //make sure this is a number)
  6029. var iAsNumber = +i;
  6030. if (iAsNumber > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[iAsNumber]) {
  6031. continue;
  6032. }
  6033. this._vertexAttribArrays[iAsNumber] = false;
  6034. this._gl.disableVertexAttribArray(iAsNumber);
  6035. }
  6036. var attributesCount = effect.getAttributesCount();
  6037. for (var index = 0; index < attributesCount; index++) {
  6038. // Attributes
  6039. var order = effect.getAttributeLocation(index);
  6040. if (order >= 0) {
  6041. this._vertexAttribArrays[order] = true;
  6042. this._gl.enableVertexAttribArray(order);
  6043. }
  6044. }
  6045. this._currentEffect = effect;
  6046. if (effect.onBind) {
  6047. effect.onBind(effect);
  6048. }
  6049. };
  6050. Engine.prototype.setArray = function (uniform, array) {
  6051. if (!uniform)
  6052. return;
  6053. this._gl.uniform1fv(uniform, array);
  6054. };
  6055. Engine.prototype.setArray2 = function (uniform, array) {
  6056. if (!uniform || array.length % 2 !== 0)
  6057. return;
  6058. this._gl.uniform2fv(uniform, array);
  6059. };
  6060. Engine.prototype.setArray3 = function (uniform, array) {
  6061. if (!uniform || array.length % 3 !== 0)
  6062. return;
  6063. this._gl.uniform3fv(uniform, array);
  6064. };
  6065. Engine.prototype.setArray4 = function (uniform, array) {
  6066. if (!uniform || array.length % 4 !== 0)
  6067. return;
  6068. this._gl.uniform4fv(uniform, array);
  6069. };
  6070. Engine.prototype.setMatrices = function (uniform, matrices) {
  6071. if (!uniform)
  6072. return;
  6073. this._gl.uniformMatrix4fv(uniform, false, matrices);
  6074. };
  6075. Engine.prototype.setMatrix = function (uniform, matrix) {
  6076. if (!uniform)
  6077. return;
  6078. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  6079. };
  6080. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  6081. if (!uniform)
  6082. return;
  6083. this._gl.uniformMatrix3fv(uniform, false, matrix);
  6084. };
  6085. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  6086. if (!uniform)
  6087. return;
  6088. this._gl.uniformMatrix2fv(uniform, false, matrix);
  6089. };
  6090. Engine.prototype.setFloat = function (uniform, value) {
  6091. if (!uniform)
  6092. return;
  6093. this._gl.uniform1f(uniform, value);
  6094. };
  6095. Engine.prototype.setFloat2 = function (uniform, x, y) {
  6096. if (!uniform)
  6097. return;
  6098. this._gl.uniform2f(uniform, x, y);
  6099. };
  6100. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  6101. if (!uniform)
  6102. return;
  6103. this._gl.uniform3f(uniform, x, y, z);
  6104. };
  6105. Engine.prototype.setBool = function (uniform, bool) {
  6106. if (!uniform)
  6107. return;
  6108. this._gl.uniform1i(uniform, bool);
  6109. };
  6110. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  6111. if (!uniform)
  6112. return;
  6113. this._gl.uniform4f(uniform, x, y, z, w);
  6114. };
  6115. Engine.prototype.setColor3 = function (uniform, color3) {
  6116. if (!uniform)
  6117. return;
  6118. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  6119. };
  6120. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  6121. if (!uniform)
  6122. return;
  6123. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  6124. };
  6125. // States
  6126. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  6127. if (zOffset === void 0) { zOffset = 0; }
  6128. if (reverseSide === void 0) { reverseSide = false; }
  6129. // Culling
  6130. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  6131. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  6132. var cullFace = this.cullBackFaces ? showSide : hideSide;
  6133. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  6134. if (culling) {
  6135. this._depthCullingState.cullFace = cullFace;
  6136. this._depthCullingState.cull = true;
  6137. }
  6138. else {
  6139. this._depthCullingState.cull = false;
  6140. }
  6141. }
  6142. // Z offset
  6143. this._depthCullingState.zOffset = zOffset;
  6144. };
  6145. Engine.prototype.setDepthBuffer = function (enable) {
  6146. this._depthCullingState.depthTest = enable;
  6147. };
  6148. Engine.prototype.getDepthWrite = function () {
  6149. return this._depthCullingState.depthMask;
  6150. };
  6151. Engine.prototype.setDepthWrite = function (enable) {
  6152. this._depthCullingState.depthMask = enable;
  6153. };
  6154. Engine.prototype.setColorWrite = function (enable) {
  6155. this._gl.colorMask(enable, enable, enable, enable);
  6156. };
  6157. Engine.prototype.setAlphaMode = function (mode) {
  6158. if (this._alphaMode === mode) {
  6159. return;
  6160. }
  6161. switch (mode) {
  6162. case Engine.ALPHA_DISABLE:
  6163. this.setDepthWrite(true);
  6164. this._alphaState.alphaBlend = false;
  6165. break;
  6166. case Engine.ALPHA_COMBINE:
  6167. this.setDepthWrite(false);
  6168. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  6169. this._alphaState.alphaBlend = true;
  6170. break;
  6171. case Engine.ALPHA_ONEONE:
  6172. this.setDepthWrite(false);
  6173. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6174. this._alphaState.alphaBlend = true;
  6175. break;
  6176. case Engine.ALPHA_ADD:
  6177. this.setDepthWrite(false);
  6178. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6179. this._alphaState.alphaBlend = true;
  6180. break;
  6181. case Engine.ALPHA_SUBTRACT:
  6182. this.setDepthWrite(false);
  6183. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6184. this._alphaState.alphaBlend = true;
  6185. break;
  6186. case Engine.ALPHA_MULTIPLY:
  6187. this.setDepthWrite(false);
  6188. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  6189. this._alphaState.alphaBlend = true;
  6190. break;
  6191. case Engine.ALPHA_MAXIMIZED:
  6192. this.setDepthWrite(false);
  6193. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6194. this._alphaState.alphaBlend = true;
  6195. break;
  6196. }
  6197. this._alphaMode = mode;
  6198. };
  6199. Engine.prototype.getAlphaMode = function () {
  6200. return this._alphaMode;
  6201. };
  6202. Engine.prototype.setAlphaTesting = function (enable) {
  6203. this._alphaTest = enable;
  6204. };
  6205. Engine.prototype.getAlphaTesting = function () {
  6206. return this._alphaTest;
  6207. };
  6208. // Textures
  6209. Engine.prototype.wipeCaches = function () {
  6210. this.resetTextureCache();
  6211. this._currentEffect = null;
  6212. this._depthCullingState.reset();
  6213. this._alphaState.reset();
  6214. this._cachedVertexBuffers = null;
  6215. this._cachedIndexBuffer = null;
  6216. this._cachedEffectForVertexBuffers = null;
  6217. };
  6218. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  6219. var gl = this._gl;
  6220. gl.bindTexture(gl.TEXTURE_2D, texture);
  6221. var magFilter = gl.NEAREST;
  6222. var minFilter = gl.NEAREST;
  6223. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6224. magFilter = gl.LINEAR;
  6225. minFilter = gl.LINEAR;
  6226. }
  6227. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6228. magFilter = gl.LINEAR;
  6229. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6230. }
  6231. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  6232. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  6233. gl.bindTexture(gl.TEXTURE_2D, null);
  6234. texture.samplingMode = samplingMode;
  6235. };
  6236. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  6237. var _this = this;
  6238. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6239. if (onLoad === void 0) { onLoad = null; }
  6240. if (onError === void 0) { onError = null; }
  6241. if (buffer === void 0) { buffer = null; }
  6242. var texture = this._gl.createTexture();
  6243. var extension;
  6244. var fromData = false;
  6245. if (url.substr(0, 5) === "data:") {
  6246. fromData = true;
  6247. }
  6248. if (!fromData)
  6249. extension = url.substr(url.length - 4, 4).toLowerCase();
  6250. else {
  6251. var oldUrl = url;
  6252. fromData = oldUrl.split(':');
  6253. url = oldUrl;
  6254. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  6255. }
  6256. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6257. var isTGA = (extension === ".tga");
  6258. scene._addPendingData(texture);
  6259. texture.url = url;
  6260. texture.noMipmap = noMipmap;
  6261. texture.references = 1;
  6262. texture.samplingMode = samplingMode;
  6263. this._loadedTexturesCache.push(texture);
  6264. var onerror = function () {
  6265. scene._removePendingData(texture);
  6266. if (onError) {
  6267. onError();
  6268. }
  6269. };
  6270. var callback;
  6271. if (isTGA) {
  6272. callback = function (arrayBuffer) {
  6273. var data = new Uint8Array(arrayBuffer);
  6274. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  6275. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  6276. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  6277. }, onLoad, samplingMode);
  6278. };
  6279. if (!(fromData instanceof Array))
  6280. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  6281. callback(arrayBuffer);
  6282. }, onerror, scene.database, true);
  6283. else
  6284. callback(buffer);
  6285. }
  6286. else if (isDDS) {
  6287. callback = function (data) {
  6288. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6289. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  6290. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  6291. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  6292. }, onLoad, samplingMode);
  6293. };
  6294. if (!(fromData instanceof Array))
  6295. BABYLON.Tools.LoadFile(url, function (data) {
  6296. callback(data);
  6297. }, onerror, scene.database, true);
  6298. else
  6299. callback(buffer);
  6300. }
  6301. else {
  6302. var onload = function (img) {
  6303. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  6304. var isPot = (img.width === potWidth && img.height === potHeight);
  6305. if (!isPot) {
  6306. _this._prepareWorkingCanvas();
  6307. _this._workingCanvas.width = potWidth;
  6308. _this._workingCanvas.height = potHeight;
  6309. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6310. _this._workingContext.imageSmoothingEnabled = false;
  6311. _this._workingContext.mozImageSmoothingEnabled = false;
  6312. _this._workingContext.oImageSmoothingEnabled = false;
  6313. _this._workingContext.webkitImageSmoothingEnabled = false;
  6314. _this._workingContext.msImageSmoothingEnabled = false;
  6315. }
  6316. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  6317. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6318. _this._workingContext.imageSmoothingEnabled = true;
  6319. _this._workingContext.mozImageSmoothingEnabled = true;
  6320. _this._workingContext.oImageSmoothingEnabled = true;
  6321. _this._workingContext.webkitImageSmoothingEnabled = true;
  6322. _this._workingContext.msImageSmoothingEnabled = true;
  6323. }
  6324. }
  6325. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  6326. }, onLoad, samplingMode);
  6327. };
  6328. if (!(fromData instanceof Array))
  6329. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6330. else
  6331. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  6332. }
  6333. return texture;
  6334. };
  6335. Engine.prototype._getInternalFormat = function (format) {
  6336. var internalFormat = this._gl.RGBA;
  6337. switch (format) {
  6338. case Engine.TEXTUREFORMAT_ALPHA:
  6339. internalFormat = this._gl.ALPHA;
  6340. break;
  6341. case Engine.TEXTUREFORMAT_LUMINANCE:
  6342. internalFormat = this._gl.LUMINANCE;
  6343. break;
  6344. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  6345. internalFormat = this._gl.LUMINANCE_ALPHA;
  6346. break;
  6347. case Engine.TEXTUREFORMAT_RGB:
  6348. internalFormat = this._gl.RGB;
  6349. break;
  6350. case Engine.TEXTUREFORMAT_RGBA:
  6351. internalFormat = this._gl.RGBA;
  6352. break;
  6353. }
  6354. return internalFormat;
  6355. };
  6356. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  6357. if (compression === void 0) { compression = null; }
  6358. var internalFormat = this._getInternalFormat(format);
  6359. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6360. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6361. if (compression) {
  6362. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  6363. }
  6364. else {
  6365. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  6366. }
  6367. if (texture.generateMipMaps) {
  6368. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6369. }
  6370. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6371. this.resetTextureCache();
  6372. texture.isReady = true;
  6373. };
  6374. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  6375. if (compression === void 0) { compression = null; }
  6376. var texture = this._gl.createTexture();
  6377. texture._baseWidth = width;
  6378. texture._baseHeight = height;
  6379. texture._width = width;
  6380. texture._height = height;
  6381. texture.references = 1;
  6382. this.updateRawTexture(texture, data, format, invertY, compression);
  6383. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6384. // Filters
  6385. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  6386. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6387. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6388. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6389. texture.samplingMode = samplingMode;
  6390. this._loadedTexturesCache.push(texture);
  6391. return texture;
  6392. };
  6393. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode, forceExponantOfTwo) {
  6394. if (forceExponantOfTwo === void 0) { forceExponantOfTwo = true; }
  6395. var texture = this._gl.createTexture();
  6396. texture._baseWidth = width;
  6397. texture._baseHeight = height;
  6398. if (forceExponantOfTwo) {
  6399. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  6400. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  6401. }
  6402. this.resetTextureCache();
  6403. texture._width = width;
  6404. texture._height = height;
  6405. texture.isReady = false;
  6406. texture.generateMipMaps = generateMipMaps;
  6407. texture.references = 1;
  6408. texture.samplingMode = samplingMode;
  6409. this.updateTextureSamplingMode(samplingMode, texture);
  6410. this._loadedTexturesCache.push(texture);
  6411. return texture;
  6412. };
  6413. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  6414. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  6415. if (texture.isCube) {
  6416. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, texture);
  6417. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6418. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6419. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6420. }
  6421. else {
  6422. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6423. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6424. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6425. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6426. }
  6427. };
  6428. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  6429. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6430. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  6431. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  6432. if (texture.generateMipMaps) {
  6433. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6434. }
  6435. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6436. this.resetTextureCache();
  6437. texture.isReady = true;
  6438. };
  6439. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  6440. if (texture._isDisabled) {
  6441. return;
  6442. }
  6443. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6444. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  6445. try {
  6446. // Testing video texture support
  6447. if (this._videoTextureSupported === undefined) {
  6448. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6449. if (this._gl.getError() !== 0) {
  6450. this._videoTextureSupported = false;
  6451. }
  6452. else {
  6453. this._videoTextureSupported = true;
  6454. }
  6455. }
  6456. // Copy video through the current working canvas if video texture is not supported
  6457. if (!this._videoTextureSupported) {
  6458. if (!texture._workingCanvas) {
  6459. texture._workingCanvas = document.createElement("canvas");
  6460. texture._workingContext = texture._workingCanvas.getContext("2d");
  6461. texture._workingCanvas.width = texture._width;
  6462. texture._workingCanvas.height = texture._height;
  6463. }
  6464. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  6465. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  6466. }
  6467. else {
  6468. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6469. }
  6470. if (texture.generateMipMaps) {
  6471. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6472. }
  6473. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6474. this.resetTextureCache();
  6475. texture.isReady = true;
  6476. }
  6477. catch (ex) {
  6478. // Something unexpected
  6479. // Let's disable the texture
  6480. texture._isDisabled = true;
  6481. }
  6482. };
  6483. Engine.prototype.createRenderTargetTexture = function (size, options) {
  6484. // old version had a "generateMipMaps" arg instead of options.
  6485. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  6486. // in the same way, generateDepthBuffer is defaulted to true
  6487. var generateMipMaps = false;
  6488. var generateDepthBuffer = true;
  6489. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6490. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6491. if (options !== undefined) {
  6492. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6493. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  6494. type = options.type === undefined ? type : options.type;
  6495. if (options.samplingMode !== undefined) {
  6496. samplingMode = options.samplingMode;
  6497. }
  6498. if (type === Engine.TEXTURETYPE_FLOAT) {
  6499. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  6500. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  6501. }
  6502. }
  6503. var gl = this._gl;
  6504. var texture = gl.createTexture();
  6505. gl.bindTexture(gl.TEXTURE_2D, texture);
  6506. var width = size.width || size;
  6507. var height = size.height || size;
  6508. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6509. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  6510. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6511. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  6512. }
  6513. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6514. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6515. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6516. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6517. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  6518. var depthBuffer;
  6519. // Create the depth buffer
  6520. if (generateDepthBuffer) {
  6521. depthBuffer = gl.createRenderbuffer();
  6522. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6523. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  6524. }
  6525. // Create the framebuffer
  6526. var framebuffer = gl.createFramebuffer();
  6527. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6528. if (generateDepthBuffer) {
  6529. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6530. }
  6531. if (generateMipMaps) {
  6532. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6533. }
  6534. // Unbind
  6535. gl.bindTexture(gl.TEXTURE_2D, null);
  6536. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6537. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6538. texture._framebuffer = framebuffer;
  6539. if (generateDepthBuffer) {
  6540. texture._depthBuffer = depthBuffer;
  6541. }
  6542. texture._width = width;
  6543. texture._height = height;
  6544. texture.isReady = true;
  6545. texture.generateMipMaps = generateMipMaps;
  6546. texture.references = 1;
  6547. texture.samplingMode = samplingMode;
  6548. this.resetTextureCache();
  6549. this._loadedTexturesCache.push(texture);
  6550. return texture;
  6551. };
  6552. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  6553. var gl = this._gl;
  6554. var texture = gl.createTexture();
  6555. var generateMipMaps = true;
  6556. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6557. if (options !== undefined) {
  6558. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6559. if (options.samplingMode !== undefined) {
  6560. samplingMode = options.samplingMode;
  6561. }
  6562. }
  6563. texture.isCube = true;
  6564. texture.references = 1;
  6565. texture.generateMipMaps = generateMipMaps;
  6566. texture.references = 1;
  6567. texture.samplingMode = samplingMode;
  6568. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6569. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6570. for (var face = 0; face < 6; face++) {
  6571. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  6572. }
  6573. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  6574. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  6575. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6576. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6577. // Create the depth buffer
  6578. var depthBuffer = gl.createRenderbuffer();
  6579. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6580. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  6581. // Create the framebuffer
  6582. var framebuffer = gl.createFramebuffer();
  6583. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6584. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6585. // Mipmaps
  6586. if (texture.generateMipMaps) {
  6587. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6588. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6589. }
  6590. // Unbind
  6591. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6592. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6593. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6594. texture._framebuffer = framebuffer;
  6595. texture._depthBuffer = depthBuffer;
  6596. this.resetTextureCache();
  6597. texture._width = size;
  6598. texture._height = size;
  6599. texture.isReady = true;
  6600. return texture;
  6601. };
  6602. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap) {
  6603. var _this = this;
  6604. var gl = this._gl;
  6605. var texture = gl.createTexture();
  6606. texture.isCube = true;
  6607. texture.url = rootUrl;
  6608. texture.references = 1;
  6609. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  6610. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6611. if (isDDS) {
  6612. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  6613. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6614. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  6615. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6616. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  6617. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  6618. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  6619. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6620. }
  6621. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6622. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  6623. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6624. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6625. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6626. _this.resetTextureCache();
  6627. texture._width = info.width;
  6628. texture._height = info.height;
  6629. texture.isReady = true;
  6630. }, null, null, true);
  6631. }
  6632. else {
  6633. cascadeLoad(rootUrl, scene, function (imgs) {
  6634. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  6635. var height = width;
  6636. _this._prepareWorkingCanvas();
  6637. _this._workingCanvas.width = width;
  6638. _this._workingCanvas.height = height;
  6639. var faces = [
  6640. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6641. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6642. ];
  6643. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6644. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6645. for (var index = 0; index < faces.length; index++) {
  6646. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  6647. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  6648. }
  6649. if (!noMipmap) {
  6650. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6651. }
  6652. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6653. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6654. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6655. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6656. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6657. _this.resetTextureCache();
  6658. texture._width = width;
  6659. texture._height = height;
  6660. texture.isReady = true;
  6661. }, files);
  6662. }
  6663. return texture;
  6664. };
  6665. Engine.prototype.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator) {
  6666. var _this = this;
  6667. var gl = this._gl;
  6668. var texture = gl.createTexture();
  6669. scene._addPendingData(texture);
  6670. texture.isCube = true;
  6671. texture.references = 1;
  6672. texture.url = url;
  6673. var internalFormat = this._getInternalFormat(format);
  6674. var textureType = gl.UNSIGNED_BYTE;
  6675. if (type === Engine.TEXTURETYPE_FLOAT) {
  6676. textureType = gl.FLOAT;
  6677. }
  6678. var width = size;
  6679. var height = width;
  6680. var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  6681. texture._width = width;
  6682. texture._height = height;
  6683. var onerror = function () {
  6684. scene._removePendingData(texture);
  6685. };
  6686. var internalCallback = function (data) {
  6687. var rgbeDataArrays = callback(data);
  6688. var facesIndex = [
  6689. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6690. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6691. ];
  6692. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6693. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6694. if (!noMipmap && isPot) {
  6695. if (mipmmapGenerator) {
  6696. var arrayTemp = [];
  6697. // Data are known to be in +X +Y +Z -X -Y -Z
  6698. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  6699. arrayTemp.push(rgbeDataArrays[0]); // +X
  6700. arrayTemp.push(rgbeDataArrays[3]); // -X
  6701. arrayTemp.push(rgbeDataArrays[1]); // +Y
  6702. arrayTemp.push(rgbeDataArrays[4]); // -Y
  6703. arrayTemp.push(rgbeDataArrays[2]); // +Z
  6704. arrayTemp.push(rgbeDataArrays[5]); // -Z
  6705. var mipData = mipmmapGenerator(arrayTemp);
  6706. for (var level = 0; level < mipData.length; level++) {
  6707. var mipSize = width >> level;
  6708. // mipData is order in +X -X +Y -Y +Z -Z
  6709. gl.texImage2D(facesIndex[0], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][0]);
  6710. gl.texImage2D(facesIndex[1], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][2]);
  6711. gl.texImage2D(facesIndex[2], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][4]);
  6712. gl.texImage2D(facesIndex[3], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][1]);
  6713. gl.texImage2D(facesIndex[4], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][3]);
  6714. gl.texImage2D(facesIndex[5], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][5]);
  6715. }
  6716. }
  6717. else {
  6718. // Data are known to be in +X +Y +Z -X -Y -Z
  6719. for (var index = 0; index < facesIndex.length; index++) {
  6720. var faceData = rgbeDataArrays[index];
  6721. gl.texImage2D(facesIndex[index], 0, internalFormat, width, height, 0, internalFormat, textureType, faceData);
  6722. }
  6723. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6724. }
  6725. }
  6726. else {
  6727. noMipmap = true;
  6728. }
  6729. if (textureType == gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
  6730. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  6731. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  6732. }
  6733. else {
  6734. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6735. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6736. }
  6737. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6738. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6739. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6740. texture.isReady = true;
  6741. _this.resetTextureCache();
  6742. scene._removePendingData(texture);
  6743. };
  6744. BABYLON.Tools.LoadFile(url, function (data) {
  6745. internalCallback(data);
  6746. }, onerror, scene.database, true);
  6747. return texture;
  6748. };
  6749. ;
  6750. Engine.prototype._releaseTexture = function (texture) {
  6751. var gl = this._gl;
  6752. if (texture._framebuffer) {
  6753. gl.deleteFramebuffer(texture._framebuffer);
  6754. }
  6755. if (texture._depthBuffer) {
  6756. gl.deleteRenderbuffer(texture._depthBuffer);
  6757. }
  6758. gl.deleteTexture(texture);
  6759. // Unbind channels
  6760. this.unbindAllTextures();
  6761. var index = this._loadedTexturesCache.indexOf(texture);
  6762. if (index !== -1) {
  6763. this._loadedTexturesCache.splice(index, 1);
  6764. }
  6765. };
  6766. Engine.prototype.bindSamplers = function (effect) {
  6767. this._gl.useProgram(effect.getProgram());
  6768. var samplers = effect.getSamplers();
  6769. for (var index = 0; index < samplers.length; index++) {
  6770. var uniform = effect.getUniform(samplers[index]);
  6771. this._gl.uniform1i(uniform, index);
  6772. }
  6773. this._currentEffect = null;
  6774. };
  6775. Engine.prototype._bindTexture = function (channel, texture) {
  6776. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6777. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6778. this._activeTexturesCache[channel] = null;
  6779. };
  6780. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  6781. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  6782. };
  6783. Engine.prototype.unbindAllTextures = function () {
  6784. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  6785. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6786. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6787. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6788. this._activeTexturesCache[channel] = null;
  6789. }
  6790. };
  6791. Engine.prototype.setTexture = function (channel, texture) {
  6792. if (channel < 0) {
  6793. return;
  6794. }
  6795. // Not ready?
  6796. if (!texture || !texture.isReady()) {
  6797. if (this._activeTexturesCache[channel] != null) {
  6798. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6799. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6800. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6801. this._activeTexturesCache[channel] = null;
  6802. }
  6803. return;
  6804. }
  6805. // Video
  6806. var alreadyActivated = false;
  6807. if (texture instanceof BABYLON.VideoTexture) {
  6808. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6809. alreadyActivated = true;
  6810. texture.update();
  6811. }
  6812. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  6813. texture.delayLoad();
  6814. return;
  6815. }
  6816. if (this._activeTexturesCache[channel] === texture) {
  6817. return;
  6818. }
  6819. this._activeTexturesCache[channel] = texture;
  6820. var internalTexture = texture.getInternalTexture();
  6821. if (!alreadyActivated) {
  6822. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6823. }
  6824. if (internalTexture.isCube) {
  6825. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  6826. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  6827. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  6828. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  6829. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  6830. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  6831. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  6832. }
  6833. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  6834. }
  6835. else {
  6836. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  6837. if (internalTexture._cachedWrapU !== texture.wrapU) {
  6838. internalTexture._cachedWrapU = texture.wrapU;
  6839. switch (texture.wrapU) {
  6840. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6841. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  6842. break;
  6843. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6844. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  6845. break;
  6846. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6847. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  6848. break;
  6849. }
  6850. }
  6851. if (internalTexture._cachedWrapV !== texture.wrapV) {
  6852. internalTexture._cachedWrapV = texture.wrapV;
  6853. switch (texture.wrapV) {
  6854. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6855. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  6856. break;
  6857. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6858. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  6859. break;
  6860. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6861. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  6862. break;
  6863. }
  6864. }
  6865. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  6866. }
  6867. };
  6868. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  6869. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  6870. var value = texture.anisotropicFilteringLevel;
  6871. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6872. value = 1;
  6873. }
  6874. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  6875. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  6876. texture._cachedAnisotropicFilteringLevel = value;
  6877. }
  6878. };
  6879. Engine.prototype.readPixels = function (x, y, width, height) {
  6880. var data = new Uint8Array(height * width * 4);
  6881. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  6882. return data;
  6883. };
  6884. Engine.prototype.releaseInternalTexture = function (texture) {
  6885. if (!texture) {
  6886. return;
  6887. }
  6888. texture.references--;
  6889. // Final reference ?
  6890. if (texture.references === 0) {
  6891. var texturesCache = this.getLoadedTexturesCache();
  6892. var index = texturesCache.indexOf(texture);
  6893. if (index > -1) {
  6894. texturesCache.splice(index, 1);
  6895. }
  6896. this._releaseTexture(texture);
  6897. }
  6898. };
  6899. // Dispose
  6900. Engine.prototype.dispose = function () {
  6901. this.hideLoadingUI();
  6902. this.stopRenderLoop();
  6903. // Release scenes
  6904. while (this.scenes.length) {
  6905. this.scenes[0].dispose();
  6906. }
  6907. // Release audio engine
  6908. Engine.audioEngine.dispose();
  6909. // Release effects
  6910. for (var name in this._compiledEffects) {
  6911. this._gl.deleteProgram(this._compiledEffects[name]._program);
  6912. }
  6913. // Unbind
  6914. for (var i in this._vertexAttribArrays) {
  6915. //making sure this is a string
  6916. var iAsNumber = +i;
  6917. if (iAsNumber > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[iAsNumber]) {
  6918. continue;
  6919. }
  6920. this._gl.disableVertexAttribArray(iAsNumber);
  6921. }
  6922. this._gl = null;
  6923. // Events
  6924. window.removeEventListener("blur", this._onBlur);
  6925. window.removeEventListener("focus", this._onFocus);
  6926. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  6927. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  6928. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  6929. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  6930. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  6931. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  6932. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  6933. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  6934. };
  6935. // Loading screen
  6936. Engine.prototype.displayLoadingUI = function () {
  6937. this._loadingScreen.displayLoadingUI();
  6938. };
  6939. Engine.prototype.hideLoadingUI = function () {
  6940. this._loadingScreen.hideLoadingUI();
  6941. };
  6942. Object.defineProperty(Engine.prototype, "loadingScreen", {
  6943. get: function () {
  6944. return this._loadingScreen;
  6945. },
  6946. set: function (loadingScreen) {
  6947. this._loadingScreen = loadingScreen;
  6948. },
  6949. enumerable: true,
  6950. configurable: true
  6951. });
  6952. Object.defineProperty(Engine.prototype, "loadingUIText", {
  6953. set: function (text) {
  6954. this._loadingScreen.loadingUIText = text;
  6955. },
  6956. enumerable: true,
  6957. configurable: true
  6958. });
  6959. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  6960. set: function (color) {
  6961. this._loadingScreen.loadingUIBackgroundColor = color;
  6962. },
  6963. enumerable: true,
  6964. configurable: true
  6965. });
  6966. // FPS
  6967. Engine.prototype.getFps = function () {
  6968. return this.fps;
  6969. };
  6970. Engine.prototype.getDeltaTime = function () {
  6971. return this.deltaTime;
  6972. };
  6973. Engine.prototype._measureFps = function () {
  6974. this.previousFramesDuration.push(BABYLON.Tools.Now);
  6975. var length = this.previousFramesDuration.length;
  6976. if (length >= 2) {
  6977. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  6978. }
  6979. if (length >= this.fpsRange) {
  6980. if (length > this.fpsRange) {
  6981. this.previousFramesDuration.splice(0, 1);
  6982. length = this.previousFramesDuration.length;
  6983. }
  6984. var sum = 0;
  6985. for (var id = 0; id < length - 1; id++) {
  6986. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  6987. }
  6988. this.fps = 1000.0 / (sum / (length - 1));
  6989. }
  6990. };
  6991. // Statics
  6992. Engine.isSupported = function () {
  6993. try {
  6994. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  6995. if (navigator.isCocoonJS) {
  6996. return true;
  6997. }
  6998. var tempcanvas = document.createElement("canvas");
  6999. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  7000. return gl != null && !!window.WebGLRenderingContext;
  7001. }
  7002. catch (e) {
  7003. return false;
  7004. }
  7005. };
  7006. // Const statics
  7007. Engine._ALPHA_DISABLE = 0;
  7008. Engine._ALPHA_ADD = 1;
  7009. Engine._ALPHA_COMBINE = 2;
  7010. Engine._ALPHA_SUBTRACT = 3;
  7011. Engine._ALPHA_MULTIPLY = 4;
  7012. Engine._ALPHA_MAXIMIZED = 5;
  7013. Engine._ALPHA_ONEONE = 6;
  7014. Engine._DELAYLOADSTATE_NONE = 0;
  7015. Engine._DELAYLOADSTATE_LOADED = 1;
  7016. Engine._DELAYLOADSTATE_LOADING = 2;
  7017. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  7018. Engine._TEXTUREFORMAT_ALPHA = 0;
  7019. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  7020. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  7021. Engine._TEXTUREFORMAT_RGB = 4;
  7022. Engine._TEXTUREFORMAT_RGBA = 5;
  7023. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  7024. Engine._TEXTURETYPE_FLOAT = 1;
  7025. // Updatable statics so stick with vars here
  7026. Engine.CollisionsEpsilon = 0.001;
  7027. Engine.CodeRepository = "src/";
  7028. Engine.ShadersRepository = "src/Shaders/";
  7029. return Engine;
  7030. })();
  7031. BABYLON.Engine = Engine;
  7032. })(BABYLON || (BABYLON = {}));
  7033. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  7034. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  7035. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  7036. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  7037. return c > 3 && r && Object.defineProperty(target, key, r), r;
  7038. };
  7039. var BABYLON;
  7040. (function (BABYLON) {
  7041. /**
  7042. * Node is the basic class for all scene objects (Mesh, Light Camera).
  7043. */
  7044. var Node = (function () {
  7045. /**
  7046. * @constructor
  7047. * @param {string} name - the name and id to be given to this node
  7048. * @param {BABYLON.Scene} the scene this node will be added to
  7049. */
  7050. function Node(name, scene) {
  7051. this.state = "";
  7052. this.animations = new Array();
  7053. this._ranges = {};
  7054. this._childrenFlag = -1;
  7055. this._isEnabled = true;
  7056. this._isReady = true;
  7057. this._currentRenderId = -1;
  7058. this._parentRenderId = -1;
  7059. this.name = name;
  7060. this.id = name;
  7061. this._scene = scene;
  7062. this._initCache();
  7063. }
  7064. Node.prototype.getScene = function () {
  7065. return this._scene;
  7066. };
  7067. Node.prototype.getEngine = function () {
  7068. return this._scene.getEngine();
  7069. };
  7070. // override it in derived class
  7071. Node.prototype.getWorldMatrix = function () {
  7072. return BABYLON.Matrix.Identity();
  7073. };
  7074. // override it in derived class if you add new variables to the cache
  7075. // and call the parent class method
  7076. Node.prototype._initCache = function () {
  7077. this._cache = {};
  7078. this._cache.parent = undefined;
  7079. };
  7080. Node.prototype.updateCache = function (force) {
  7081. if (!force && this.isSynchronized())
  7082. return;
  7083. this._cache.parent = this.parent;
  7084. this._updateCache();
  7085. };
  7086. // override it in derived class if you add new variables to the cache
  7087. // and call the parent class method if !ignoreParentClass
  7088. Node.prototype._updateCache = function (ignoreParentClass) {
  7089. };
  7090. // override it in derived class if you add new variables to the cache
  7091. Node.prototype._isSynchronized = function () {
  7092. return true;
  7093. };
  7094. Node.prototype._markSyncedWithParent = function () {
  7095. this._parentRenderId = this.parent._currentRenderId;
  7096. };
  7097. Node.prototype.isSynchronizedWithParent = function () {
  7098. if (!this.parent) {
  7099. return true;
  7100. }
  7101. if (this._parentRenderId !== this.parent._currentRenderId) {
  7102. return false;
  7103. }
  7104. return this.parent.isSynchronized();
  7105. };
  7106. Node.prototype.isSynchronized = function (updateCache) {
  7107. var check = this.hasNewParent();
  7108. check = check || !this.isSynchronizedWithParent();
  7109. check = check || !this._isSynchronized();
  7110. if (updateCache)
  7111. this.updateCache(true);
  7112. return !check;
  7113. };
  7114. Node.prototype.hasNewParent = function (update) {
  7115. if (this._cache.parent === this.parent)
  7116. return false;
  7117. if (update)
  7118. this._cache.parent = this.parent;
  7119. return true;
  7120. };
  7121. /**
  7122. * Is this node ready to be used/rendered
  7123. * @return {boolean} is it ready
  7124. */
  7125. Node.prototype.isReady = function () {
  7126. return this._isReady;
  7127. };
  7128. /**
  7129. * Is this node enabled.
  7130. * If the node has a parent and is enabled, the parent will be inspected as well.
  7131. * @return {boolean} whether this node (and its parent) is enabled.
  7132. * @see setEnabled
  7133. */
  7134. Node.prototype.isEnabled = function () {
  7135. if (!this._isEnabled) {
  7136. return false;
  7137. }
  7138. if (this.parent) {
  7139. return this.parent.isEnabled();
  7140. }
  7141. return true;
  7142. };
  7143. /**
  7144. * Set the enabled state of this node.
  7145. * @param {boolean} value - the new enabled state
  7146. * @see isEnabled
  7147. */
  7148. Node.prototype.setEnabled = function (value) {
  7149. this._isEnabled = value;
  7150. };
  7151. /**
  7152. * Is this node a descendant of the given node.
  7153. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  7154. * @param {BABYLON.Node} ancestor - The parent node to inspect
  7155. * @see parent
  7156. */
  7157. Node.prototype.isDescendantOf = function (ancestor) {
  7158. if (this.parent) {
  7159. if (this.parent === ancestor) {
  7160. return true;
  7161. }
  7162. return this.parent.isDescendantOf(ancestor);
  7163. }
  7164. return false;
  7165. };
  7166. Node.prototype._getDescendants = function (list, results, directDecendantsOnly) {
  7167. if (directDecendantsOnly === void 0) { directDecendantsOnly = false; }
  7168. for (var index = 0; index < list.length; index++) {
  7169. var item = list[index];
  7170. if ((directDecendantsOnly && item.parent === this) || (!directDecendantsOnly && item.isDescendantOf(this))) {
  7171. results.push(item);
  7172. }
  7173. }
  7174. };
  7175. /**
  7176. * Will return all nodes that have this node as parent.
  7177. * @return {BABYLON.Node[]} all children nodes of all types.
  7178. */
  7179. Node.prototype.getDescendants = function (directDecendantsOnly) {
  7180. var results = [];
  7181. this._getDescendants(this._scene.meshes, results, directDecendantsOnly);
  7182. this._getDescendants(this._scene.lights, results, directDecendantsOnly);
  7183. this._getDescendants(this._scene.cameras, results, directDecendantsOnly);
  7184. return results;
  7185. };
  7186. /**
  7187. * @Deprecated, legacy support.
  7188. * use getDecendants instead.
  7189. */
  7190. Node.prototype.getChildren = function () {
  7191. return this.getDescendants(true);
  7192. };
  7193. /**
  7194. * Get all child-meshes of this node.
  7195. */
  7196. Node.prototype.getChildMeshes = function (directDecendantsOnly) {
  7197. var results = [];
  7198. this._getDescendants(this._scene.meshes, results, directDecendantsOnly);
  7199. return results;
  7200. };
  7201. Node.prototype._setReady = function (state) {
  7202. if (state === this._isReady) {
  7203. return;
  7204. }
  7205. if (!state) {
  7206. this._isReady = false;
  7207. return;
  7208. }
  7209. this._isReady = true;
  7210. if (this.onReady) {
  7211. this.onReady(this);
  7212. }
  7213. };
  7214. Node.prototype.getAnimationByName = function (name) {
  7215. for (var i = 0; i < this.animations.length; i++) {
  7216. var animation = this.animations[i];
  7217. if (animation.name === name) {
  7218. return animation;
  7219. }
  7220. }
  7221. return null;
  7222. };
  7223. Node.prototype.createAnimationRange = function (name, from, to) {
  7224. // check name not already in use
  7225. if (!this._ranges[name]) {
  7226. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  7227. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  7228. if (this.animations[i]) {
  7229. this.animations[i].createRange(name, from, to);
  7230. }
  7231. }
  7232. }
  7233. };
  7234. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  7235. if (deleteFrames === void 0) { deleteFrames = true; }
  7236. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  7237. if (this.animations[i]) {
  7238. this.animations[i].deleteRange(name, deleteFrames);
  7239. }
  7240. }
  7241. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  7242. };
  7243. Node.prototype.getAnimationRange = function (name) {
  7244. return this._ranges[name];
  7245. };
  7246. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  7247. var range = this.getAnimationRange(name);
  7248. if (!range) {
  7249. return null;
  7250. }
  7251. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  7252. };
  7253. Node.prototype.serializeAnimationRanges = function () {
  7254. var serializationRanges = [];
  7255. for (var name in this._ranges) {
  7256. var range = {};
  7257. range.name = name;
  7258. range.from = this._ranges[name].from;
  7259. range.to = this._ranges[name].to;
  7260. serializationRanges.push(range);
  7261. }
  7262. return serializationRanges;
  7263. };
  7264. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  7265. if (parsedNode.ranges) {
  7266. for (var index = 0; index < parsedNode.ranges.length; index++) {
  7267. var data = parsedNode.ranges[index];
  7268. node.createAnimationRange(data.name, data.from, data.to);
  7269. }
  7270. }
  7271. };
  7272. __decorate([
  7273. BABYLON.serialize()
  7274. ], Node.prototype, "name", void 0);
  7275. __decorate([
  7276. BABYLON.serialize()
  7277. ], Node.prototype, "id", void 0);
  7278. __decorate([
  7279. BABYLON.serialize()
  7280. ], Node.prototype, "uniqueId", void 0);
  7281. __decorate([
  7282. BABYLON.serialize()
  7283. ], Node.prototype, "state", void 0);
  7284. return Node;
  7285. })();
  7286. BABYLON.Node = Node;
  7287. })(BABYLON || (BABYLON = {}));
  7288. var BABYLON;
  7289. (function (BABYLON) {
  7290. var FilesInput = (function () {
  7291. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  7292. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  7293. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  7294. this._engine = p_engine;
  7295. this._canvas = p_canvas;
  7296. this._currentScene = p_scene;
  7297. this._sceneLoadedCallback = p_sceneLoadedCallback;
  7298. this._progressCallback = p_progressCallback;
  7299. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  7300. this._textureLoadingCallback = p_textureLoadingCallback;
  7301. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  7302. }
  7303. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  7304. var _this = this;
  7305. if (p_elementToMonitor) {
  7306. this._elementToMonitor = p_elementToMonitor;
  7307. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  7308. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  7309. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  7310. }
  7311. };
  7312. FilesInput.prototype.renderFunction = function () {
  7313. if (this._additionnalRenderLoopLogicCallback) {
  7314. this._additionnalRenderLoopLogicCallback();
  7315. }
  7316. if (this._currentScene) {
  7317. if (this._textureLoadingCallback) {
  7318. var remaining = this._currentScene.getWaitingItemsCount();
  7319. if (remaining > 0) {
  7320. this._textureLoadingCallback(remaining);
  7321. }
  7322. }
  7323. this._currentScene.render();
  7324. }
  7325. };
  7326. FilesInput.prototype.drag = function (e) {
  7327. e.stopPropagation();
  7328. e.preventDefault();
  7329. };
  7330. FilesInput.prototype.drop = function (eventDrop) {
  7331. eventDrop.stopPropagation();
  7332. eventDrop.preventDefault();
  7333. this.loadFiles(eventDrop);
  7334. };
  7335. FilesInput.prototype.loadFiles = function (event) {
  7336. if (this._startingProcessingFilesCallback)
  7337. this._startingProcessingFilesCallback();
  7338. // Handling data transfer via drag'n'drop
  7339. if (event && event.dataTransfer && event.dataTransfer.files) {
  7340. this._filesToLoad = event.dataTransfer.files;
  7341. }
  7342. // Handling files from input files
  7343. if (event && event.target && event.target.files) {
  7344. this._filesToLoad = event.target.files;
  7345. }
  7346. if (this._filesToLoad && this._filesToLoad.length > 0) {
  7347. for (var i = 0; i < this._filesToLoad.length; i++) {
  7348. switch (this._filesToLoad[i].type) {
  7349. case "image/jpeg":
  7350. case "image/png":
  7351. case "image/bmp":
  7352. FilesInput.FilesTextures[this._filesToLoad[i].name] = this._filesToLoad[i];
  7353. break;
  7354. case "image/targa":
  7355. case "image/vnd.ms-dds":
  7356. case "audio/wav":
  7357. case "audio/x-wav":
  7358. case "audio/mp3":
  7359. case "audio/mpeg":
  7360. case "audio/mpeg3":
  7361. case "audio/x-mpeg-3":
  7362. case "audio/ogg":
  7363. FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
  7364. break;
  7365. default:
  7366. if ((this._filesToLoad[i].name.indexOf(".babylon") !== -1 || this._filesToLoad[i].name.indexOf(".stl") !== -1 ||
  7367. this._filesToLoad[i].name.indexOf(".obj") !== -1 || this._filesToLoad[i].name.indexOf(".mtl") !== -1)
  7368. && this._filesToLoad[i].name.indexOf(".manifest") === -1
  7369. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  7370. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  7371. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  7372. this._sceneFileToLoad = this._filesToLoad[i];
  7373. }
  7374. break;
  7375. }
  7376. }
  7377. this.reload();
  7378. }
  7379. };
  7380. FilesInput.prototype.reload = function () {
  7381. var _this = this;
  7382. var that = this;
  7383. // If a ".babylon" file has been provided
  7384. if (this._sceneFileToLoad) {
  7385. if (this._currentScene) {
  7386. if (BABYLON.Tools.errorsCount > 0) {
  7387. BABYLON.Tools.ClearLogCache();
  7388. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  7389. }
  7390. this._engine.stopRenderLoop();
  7391. this._currentScene.dispose();
  7392. }
  7393. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  7394. that._currentScene = newScene;
  7395. // Wait for textures and shaders to be ready
  7396. that._currentScene.executeWhenReady(function () {
  7397. // Attach camera to canvas inputs
  7398. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  7399. that._currentScene.createDefaultCameraOrLight();
  7400. }
  7401. that._currentScene.activeCamera.attachControl(that._canvas);
  7402. if (that._sceneLoadedCallback) {
  7403. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  7404. }
  7405. that._engine.runRenderLoop(function () { that.renderFunction(); });
  7406. });
  7407. }, function (progress) {
  7408. if (_this._progressCallback) {
  7409. _this._progressCallback(progress);
  7410. }
  7411. });
  7412. }
  7413. else {
  7414. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  7415. }
  7416. };
  7417. FilesInput.FilesTextures = new Array();
  7418. FilesInput.FilesToLoad = new Array();
  7419. return FilesInput;
  7420. })();
  7421. BABYLON.FilesInput = FilesInput;
  7422. })(BABYLON || (BABYLON = {}));
  7423. var BABYLON;
  7424. (function (BABYLON) {
  7425. var IntersectionInfo = (function () {
  7426. function IntersectionInfo(bu, bv, distance) {
  7427. this.bu = bu;
  7428. this.bv = bv;
  7429. this.distance = distance;
  7430. this.faceId = 0;
  7431. this.subMeshId = 0;
  7432. }
  7433. return IntersectionInfo;
  7434. })();
  7435. BABYLON.IntersectionInfo = IntersectionInfo;
  7436. var PickingInfo = (function () {
  7437. function PickingInfo() {
  7438. this.hit = false;
  7439. this.distance = 0;
  7440. this.pickedPoint = null;
  7441. this.pickedMesh = null;
  7442. this.bu = 0;
  7443. this.bv = 0;
  7444. this.faceId = -1;
  7445. this.subMeshId = 0;
  7446. this.pickedSprite = null;
  7447. }
  7448. // Methods
  7449. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  7450. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  7451. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  7452. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  7453. return null;
  7454. }
  7455. var indices = this.pickedMesh.getIndices();
  7456. var result;
  7457. if (useVerticesNormals) {
  7458. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  7459. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  7460. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  7461. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  7462. normal0 = normal0.scale(this.bu);
  7463. normal1 = normal1.scale(this.bv);
  7464. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  7465. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  7466. }
  7467. else {
  7468. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  7469. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  7470. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  7471. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  7472. var p1p2 = vertex1.subtract(vertex2);
  7473. var p3p2 = vertex3.subtract(vertex2);
  7474. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  7475. }
  7476. if (useWorldCoordinates) {
  7477. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  7478. }
  7479. return BABYLON.Vector3.Normalize(result);
  7480. };
  7481. PickingInfo.prototype.getTextureCoordinates = function () {
  7482. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  7483. return null;
  7484. }
  7485. var indices = this.pickedMesh.getIndices();
  7486. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  7487. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  7488. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  7489. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  7490. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  7491. uv1 = uv1.scale(this.bu);
  7492. uv2 = uv2.scale(this.bv);
  7493. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  7494. };
  7495. return PickingInfo;
  7496. })();
  7497. BABYLON.PickingInfo = PickingInfo;
  7498. })(BABYLON || (BABYLON = {}));
  7499. var BABYLON;
  7500. (function (BABYLON) {
  7501. var BoundingSphere = (function () {
  7502. function BoundingSphere(minimum, maximum) {
  7503. this.minimum = minimum;
  7504. this.maximum = maximum;
  7505. this._tempRadiusVector = BABYLON.Vector3.Zero();
  7506. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  7507. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  7508. this.radius = distance * 0.5;
  7509. this.centerWorld = BABYLON.Vector3.Zero();
  7510. this._update(BABYLON.Matrix.Identity());
  7511. }
  7512. // Methods
  7513. BoundingSphere.prototype._update = function (world) {
  7514. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  7515. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  7516. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  7517. };
  7518. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  7519. for (var i = 0; i < 6; i++) {
  7520. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  7521. return false;
  7522. }
  7523. return true;
  7524. };
  7525. BoundingSphere.prototype.intersectsPoint = function (point) {
  7526. var x = this.centerWorld.x - point.x;
  7527. var y = this.centerWorld.y - point.y;
  7528. var z = this.centerWorld.z - point.z;
  7529. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7530. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  7531. return false;
  7532. return true;
  7533. };
  7534. // Statics
  7535. BoundingSphere.Intersects = function (sphere0, sphere1) {
  7536. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  7537. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  7538. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  7539. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7540. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  7541. return false;
  7542. return true;
  7543. };
  7544. return BoundingSphere;
  7545. })();
  7546. BABYLON.BoundingSphere = BoundingSphere;
  7547. })(BABYLON || (BABYLON = {}));
  7548. var BABYLON;
  7549. (function (BABYLON) {
  7550. var BoundingBox = (function () {
  7551. function BoundingBox(minimum, maximum) {
  7552. this.minimum = minimum;
  7553. this.maximum = maximum;
  7554. this.vectors = new Array();
  7555. this.vectorsWorld = new Array();
  7556. // Bounding vectors
  7557. this.vectors.push(this.minimum.clone());
  7558. this.vectors.push(this.maximum.clone());
  7559. this.vectors.push(this.minimum.clone());
  7560. this.vectors[2].x = this.maximum.x;
  7561. this.vectors.push(this.minimum.clone());
  7562. this.vectors[3].y = this.maximum.y;
  7563. this.vectors.push(this.minimum.clone());
  7564. this.vectors[4].z = this.maximum.z;
  7565. this.vectors.push(this.maximum.clone());
  7566. this.vectors[5].z = this.minimum.z;
  7567. this.vectors.push(this.maximum.clone());
  7568. this.vectors[6].x = this.minimum.x;
  7569. this.vectors.push(this.maximum.clone());
  7570. this.vectors[7].y = this.minimum.y;
  7571. // OBB
  7572. this.center = this.maximum.add(this.minimum).scale(0.5);
  7573. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  7574. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  7575. // World
  7576. for (var index = 0; index < this.vectors.length; index++) {
  7577. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  7578. }
  7579. this.minimumWorld = BABYLON.Vector3.Zero();
  7580. this.maximumWorld = BABYLON.Vector3.Zero();
  7581. this._update(BABYLON.Matrix.Identity());
  7582. }
  7583. // Methods
  7584. BoundingBox.prototype.getWorldMatrix = function () {
  7585. return this._worldMatrix;
  7586. };
  7587. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  7588. this._worldMatrix.copyFrom(matrix);
  7589. return this;
  7590. };
  7591. BoundingBox.prototype._update = function (world) {
  7592. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  7593. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  7594. for (var index = 0; index < this.vectors.length; index++) {
  7595. var v = this.vectorsWorld[index];
  7596. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  7597. if (v.x < this.minimumWorld.x)
  7598. this.minimumWorld.x = v.x;
  7599. if (v.y < this.minimumWorld.y)
  7600. this.minimumWorld.y = v.y;
  7601. if (v.z < this.minimumWorld.z)
  7602. this.minimumWorld.z = v.z;
  7603. if (v.x > this.maximumWorld.x)
  7604. this.maximumWorld.x = v.x;
  7605. if (v.y > this.maximumWorld.y)
  7606. this.maximumWorld.y = v.y;
  7607. if (v.z > this.maximumWorld.z)
  7608. this.maximumWorld.z = v.z;
  7609. }
  7610. // OBB
  7611. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  7612. this.center.scaleInPlace(0.5);
  7613. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  7614. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  7615. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  7616. this._worldMatrix = world;
  7617. };
  7618. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  7619. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  7620. };
  7621. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7622. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  7623. };
  7624. BoundingBox.prototype.intersectsPoint = function (point) {
  7625. var delta = -BABYLON.Epsilon;
  7626. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  7627. return false;
  7628. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  7629. return false;
  7630. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  7631. return false;
  7632. return true;
  7633. };
  7634. BoundingBox.prototype.intersectsSphere = function (sphere) {
  7635. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  7636. };
  7637. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  7638. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  7639. return false;
  7640. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  7641. return false;
  7642. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  7643. return false;
  7644. return true;
  7645. };
  7646. // Statics
  7647. BoundingBox.Intersects = function (box0, box1) {
  7648. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  7649. return false;
  7650. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  7651. return false;
  7652. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  7653. return false;
  7654. return true;
  7655. };
  7656. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  7657. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  7658. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  7659. return (num <= (sphereRadius * sphereRadius));
  7660. };
  7661. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  7662. for (var p = 0; p < 6; p++) {
  7663. for (var i = 0; i < 8; i++) {
  7664. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7665. return false;
  7666. }
  7667. }
  7668. }
  7669. return true;
  7670. };
  7671. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  7672. for (var p = 0; p < 6; p++) {
  7673. var inCount = 8;
  7674. for (var i = 0; i < 8; i++) {
  7675. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7676. --inCount;
  7677. }
  7678. else {
  7679. break;
  7680. }
  7681. }
  7682. if (inCount === 0)
  7683. return false;
  7684. }
  7685. return true;
  7686. };
  7687. return BoundingBox;
  7688. })();
  7689. BABYLON.BoundingBox = BoundingBox;
  7690. })(BABYLON || (BABYLON = {}));
  7691. var BABYLON;
  7692. (function (BABYLON) {
  7693. var computeBoxExtents = function (axis, box) {
  7694. var p = BABYLON.Vector3.Dot(box.center, axis);
  7695. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  7696. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  7697. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  7698. var r = r0 + r1 + r2;
  7699. return {
  7700. min: p - r,
  7701. max: p + r
  7702. };
  7703. };
  7704. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  7705. var axisOverlap = function (axis, box0, box1) {
  7706. var result0 = computeBoxExtents(axis, box0);
  7707. var result1 = computeBoxExtents(axis, box1);
  7708. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  7709. };
  7710. var BoundingInfo = (function () {
  7711. function BoundingInfo(minimum, maximum) {
  7712. this.minimum = minimum;
  7713. this.maximum = maximum;
  7714. this._isLocked = false;
  7715. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  7716. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  7717. }
  7718. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  7719. get: function () {
  7720. return this._isLocked;
  7721. },
  7722. set: function (value) {
  7723. this._isLocked = value;
  7724. },
  7725. enumerable: true,
  7726. configurable: true
  7727. });
  7728. // Methods
  7729. BoundingInfo.prototype.update = function (world) {
  7730. if (this._isLocked) {
  7731. return;
  7732. }
  7733. this.boundingBox._update(world);
  7734. this.boundingSphere._update(world);
  7735. };
  7736. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  7737. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  7738. return false;
  7739. return this.boundingBox.isInFrustum(frustumPlanes);
  7740. };
  7741. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7742. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  7743. };
  7744. BoundingInfo.prototype._checkCollision = function (collider) {
  7745. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  7746. };
  7747. BoundingInfo.prototype.intersectsPoint = function (point) {
  7748. if (!this.boundingSphere.centerWorld) {
  7749. return false;
  7750. }
  7751. if (!this.boundingSphere.intersectsPoint(point)) {
  7752. return false;
  7753. }
  7754. if (!this.boundingBox.intersectsPoint(point)) {
  7755. return false;
  7756. }
  7757. return true;
  7758. };
  7759. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  7760. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  7761. return false;
  7762. }
  7763. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  7764. return false;
  7765. }
  7766. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  7767. return false;
  7768. }
  7769. if (!precise) {
  7770. return true;
  7771. }
  7772. var box0 = this.boundingBox;
  7773. var box1 = boundingInfo.boundingBox;
  7774. if (!axisOverlap(box0.directions[0], box0, box1))
  7775. return false;
  7776. if (!axisOverlap(box0.directions[1], box0, box1))
  7777. return false;
  7778. if (!axisOverlap(box0.directions[2], box0, box1))
  7779. return false;
  7780. if (!axisOverlap(box1.directions[0], box0, box1))
  7781. return false;
  7782. if (!axisOverlap(box1.directions[1], box0, box1))
  7783. return false;
  7784. if (!axisOverlap(box1.directions[2], box0, box1))
  7785. return false;
  7786. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  7787. return false;
  7788. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  7789. return false;
  7790. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  7791. return false;
  7792. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  7793. return false;
  7794. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  7795. return false;
  7796. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  7797. return false;
  7798. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  7799. return false;
  7800. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  7801. return false;
  7802. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  7803. return false;
  7804. return true;
  7805. };
  7806. return BoundingInfo;
  7807. })();
  7808. BABYLON.BoundingInfo = BoundingInfo;
  7809. })(BABYLON || (BABYLON = {}));
  7810. var BABYLON;
  7811. (function (BABYLON) {
  7812. var Ray = (function () {
  7813. function Ray(origin, direction, length) {
  7814. if (length === void 0) { length = Number.MAX_VALUE; }
  7815. this.origin = origin;
  7816. this.direction = direction;
  7817. this.length = length;
  7818. }
  7819. // Methods
  7820. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  7821. var d = 0.0;
  7822. var maxValue = Number.MAX_VALUE;
  7823. var inv;
  7824. var min;
  7825. var max;
  7826. var temp;
  7827. if (Math.abs(this.direction.x) < 0.0000001) {
  7828. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  7829. return false;
  7830. }
  7831. }
  7832. else {
  7833. inv = 1.0 / this.direction.x;
  7834. min = (minimum.x - this.origin.x) * inv;
  7835. max = (maximum.x - this.origin.x) * inv;
  7836. if (max === -Infinity) {
  7837. max = Infinity;
  7838. }
  7839. if (min > max) {
  7840. temp = min;
  7841. min = max;
  7842. max = temp;
  7843. }
  7844. d = Math.max(min, d);
  7845. maxValue = Math.min(max, maxValue);
  7846. if (d > maxValue) {
  7847. return false;
  7848. }
  7849. }
  7850. if (Math.abs(this.direction.y) < 0.0000001) {
  7851. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  7852. return false;
  7853. }
  7854. }
  7855. else {
  7856. inv = 1.0 / this.direction.y;
  7857. min = (minimum.y - this.origin.y) * inv;
  7858. max = (maximum.y - this.origin.y) * inv;
  7859. if (max === -Infinity) {
  7860. max = Infinity;
  7861. }
  7862. if (min > max) {
  7863. temp = min;
  7864. min = max;
  7865. max = temp;
  7866. }
  7867. d = Math.max(min, d);
  7868. maxValue = Math.min(max, maxValue);
  7869. if (d > maxValue) {
  7870. return false;
  7871. }
  7872. }
  7873. if (Math.abs(this.direction.z) < 0.0000001) {
  7874. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  7875. return false;
  7876. }
  7877. }
  7878. else {
  7879. inv = 1.0 / this.direction.z;
  7880. min = (minimum.z - this.origin.z) * inv;
  7881. max = (maximum.z - this.origin.z) * inv;
  7882. if (max === -Infinity) {
  7883. max = Infinity;
  7884. }
  7885. if (min > max) {
  7886. temp = min;
  7887. min = max;
  7888. max = temp;
  7889. }
  7890. d = Math.max(min, d);
  7891. maxValue = Math.min(max, maxValue);
  7892. if (d > maxValue) {
  7893. return false;
  7894. }
  7895. }
  7896. return true;
  7897. };
  7898. Ray.prototype.intersectsBox = function (box) {
  7899. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  7900. };
  7901. Ray.prototype.intersectsSphere = function (sphere) {
  7902. var x = sphere.center.x - this.origin.x;
  7903. var y = sphere.center.y - this.origin.y;
  7904. var z = sphere.center.z - this.origin.z;
  7905. var pyth = (x * x) + (y * y) + (z * z);
  7906. var rr = sphere.radius * sphere.radius;
  7907. if (pyth <= rr) {
  7908. return true;
  7909. }
  7910. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  7911. if (dot < 0.0) {
  7912. return false;
  7913. }
  7914. var temp = pyth - (dot * dot);
  7915. return temp <= rr;
  7916. };
  7917. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  7918. if (!this._edge1) {
  7919. this._edge1 = BABYLON.Vector3.Zero();
  7920. this._edge2 = BABYLON.Vector3.Zero();
  7921. this._pvec = BABYLON.Vector3.Zero();
  7922. this._tvec = BABYLON.Vector3.Zero();
  7923. this._qvec = BABYLON.Vector3.Zero();
  7924. }
  7925. vertex1.subtractToRef(vertex0, this._edge1);
  7926. vertex2.subtractToRef(vertex0, this._edge2);
  7927. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  7928. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  7929. if (det === 0) {
  7930. return null;
  7931. }
  7932. var invdet = 1 / det;
  7933. this.origin.subtractToRef(vertex0, this._tvec);
  7934. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  7935. if (bu < 0 || bu > 1.0) {
  7936. return null;
  7937. }
  7938. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  7939. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  7940. if (bv < 0 || bu + bv > 1.0) {
  7941. return null;
  7942. }
  7943. //check if the distance is longer than the predefined length.
  7944. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  7945. if (distance > this.length) {
  7946. return null;
  7947. }
  7948. return new BABYLON.IntersectionInfo(bu, bv, distance);
  7949. };
  7950. // Statics
  7951. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  7952. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  7953. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  7954. var direction = end.subtract(start);
  7955. direction.normalize();
  7956. return new Ray(start, direction);
  7957. };
  7958. /**
  7959. * 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
  7960. * transformed to the given world matrix.
  7961. * @param origin The origin point
  7962. * @param end The end point
  7963. * @param world a matrix to transform the ray to. Default is the identity matrix.
  7964. */
  7965. Ray.CreateNewFromTo = function (origin, end, world) {
  7966. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  7967. var direction = end.subtract(origin);
  7968. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  7969. direction.normalize();
  7970. return Ray.Transform(new Ray(origin, direction, length), world);
  7971. };
  7972. Ray.Transform = function (ray, matrix) {
  7973. var newOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, matrix);
  7974. var newDirection = BABYLON.Vector3.TransformNormal(ray.direction, matrix);
  7975. return new Ray(newOrigin, newDirection, ray.length);
  7976. };
  7977. return Ray;
  7978. })();
  7979. BABYLON.Ray = Ray;
  7980. })(BABYLON || (BABYLON = {}));
  7981. var BABYLON;
  7982. (function (BABYLON) {
  7983. var AbstractMesh = (function (_super) {
  7984. __extends(AbstractMesh, _super);
  7985. // Constructor
  7986. function AbstractMesh(name, scene) {
  7987. var _this = this;
  7988. _super.call(this, name, scene);
  7989. // Properties
  7990. this.definedFacingForward = true; // orientation for POV movement & rotation
  7991. this.position = new BABYLON.Vector3(0, 0, 0);
  7992. this._rotation = new BABYLON.Vector3(0, 0, 0);
  7993. this._scaling = new BABYLON.Vector3(1, 1, 1);
  7994. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  7995. this.visibility = 1.0;
  7996. this.alphaIndex = Number.MAX_VALUE;
  7997. this.infiniteDistance = false;
  7998. this.isVisible = true;
  7999. this.isPickable = true;
  8000. this.showBoundingBox = false;
  8001. this.showSubMeshesBoundingBox = false;
  8002. this.onDispose = null;
  8003. this.isBlocker = false;
  8004. this.renderingGroupId = 0;
  8005. this.receiveShadows = false;
  8006. this.renderOutline = false;
  8007. this.outlineColor = BABYLON.Color3.Red();
  8008. this.outlineWidth = 0.02;
  8009. this.renderOverlay = false;
  8010. this.overlayColor = BABYLON.Color3.Red();
  8011. this.overlayAlpha = 0.5;
  8012. this.hasVertexAlpha = false;
  8013. this.useVertexColors = true;
  8014. this.applyFog = true;
  8015. this.computeBonesUsingShaders = true;
  8016. this.scalingDeterminant = 1;
  8017. this.numBoneInfluencers = 4;
  8018. this.useOctreeForRenderingSelection = true;
  8019. this.useOctreeForPicking = true;
  8020. this.useOctreeForCollisions = true;
  8021. this.layerMask = 0x0FFFFFFF;
  8022. this.alwaysSelectAsActiveMesh = false;
  8023. // Collisions
  8024. this._checkCollisions = false;
  8025. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  8026. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  8027. this._collider = new BABYLON.Collider();
  8028. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8029. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8030. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8031. // Edges
  8032. this.edgesWidth = 1;
  8033. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  8034. // Cache
  8035. this._localWorld = BABYLON.Matrix.Zero();
  8036. this._worldMatrix = BABYLON.Matrix.Zero();
  8037. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  8038. this._absolutePosition = BABYLON.Vector3.Zero();
  8039. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  8040. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  8041. this._isDirty = false;
  8042. this._pivotMatrix = BABYLON.Matrix.Identity();
  8043. this._isDisposed = false;
  8044. this._renderId = 0;
  8045. this._intersectionsInProgress = new Array();
  8046. this._onAfterWorldMatrixUpdate = new Array();
  8047. this._isWorldMatrixFrozen = false;
  8048. this._unIndexed = false;
  8049. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  8050. if (collidedMesh === void 0) { collidedMesh = null; }
  8051. //TODO move this to the collision coordinator!
  8052. if (_this.getScene().workerCollisions)
  8053. newPosition.multiplyInPlace(_this._collider.radius);
  8054. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  8055. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  8056. _this.position.addInPlace(_this._diffPositionForCollisions);
  8057. }
  8058. if (_this.onCollide && collidedMesh) {
  8059. _this.onCollide(collidedMesh);
  8060. }
  8061. if (_this.onCollisionPositionChange) {
  8062. _this.onCollisionPositionChange(_this.position);
  8063. }
  8064. };
  8065. scene.addMesh(this);
  8066. }
  8067. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  8068. get: function () {
  8069. return AbstractMesh._BILLBOARDMODE_NONE;
  8070. },
  8071. enumerable: true,
  8072. configurable: true
  8073. });
  8074. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  8075. get: function () {
  8076. return AbstractMesh._BILLBOARDMODE_X;
  8077. },
  8078. enumerable: true,
  8079. configurable: true
  8080. });
  8081. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  8082. get: function () {
  8083. return AbstractMesh._BILLBOARDMODE_Y;
  8084. },
  8085. enumerable: true,
  8086. configurable: true
  8087. });
  8088. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  8089. get: function () {
  8090. return AbstractMesh._BILLBOARDMODE_Z;
  8091. },
  8092. enumerable: true,
  8093. configurable: true
  8094. });
  8095. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  8096. get: function () {
  8097. return AbstractMesh._BILLBOARDMODE_ALL;
  8098. },
  8099. enumerable: true,
  8100. configurable: true
  8101. });
  8102. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  8103. get: function () {
  8104. return this._skeleton;
  8105. },
  8106. set: function (value) {
  8107. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  8108. this._skeleton._unregisterMeshWithPoseMatrix(this);
  8109. }
  8110. if (value && value.needInitialSkinMatrix) {
  8111. value._registerMeshWithPoseMatrix(this);
  8112. }
  8113. this._skeleton = value;
  8114. if (!this._skeleton) {
  8115. this._bonesTransformMatrices = null;
  8116. }
  8117. },
  8118. enumerable: true,
  8119. configurable: true
  8120. });
  8121. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  8122. /**
  8123. * Getting the rotation object.
  8124. * If rotation quaternion is set, this vector will (almost always) be the Zero vector!
  8125. */
  8126. get: function () {
  8127. return this._rotation;
  8128. },
  8129. set: function (newRotation) {
  8130. this._rotation = newRotation;
  8131. },
  8132. enumerable: true,
  8133. configurable: true
  8134. });
  8135. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  8136. get: function () {
  8137. return this._scaling;
  8138. },
  8139. set: function (newScaling) {
  8140. this._scaling = newScaling;
  8141. if (this.physicsImpostor) {
  8142. this.physicsImpostor.forceUpdate();
  8143. }
  8144. },
  8145. enumerable: true,
  8146. configurable: true
  8147. });
  8148. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  8149. get: function () {
  8150. return this._rotationQuaternion;
  8151. },
  8152. set: function (quaternion) {
  8153. this._rotationQuaternion = quaternion;
  8154. //reset the rotation vector.
  8155. if (quaternion && this.rotation.length()) {
  8156. this.rotation.copyFromFloats(0, 0, 0);
  8157. }
  8158. },
  8159. enumerable: true,
  8160. configurable: true
  8161. });
  8162. // Methods
  8163. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  8164. this._poseMatrix.copyFrom(matrix);
  8165. };
  8166. AbstractMesh.prototype.getPoseMatrix = function () {
  8167. return this._poseMatrix;
  8168. };
  8169. AbstractMesh.prototype.disableEdgesRendering = function () {
  8170. if (this._edgesRenderer !== undefined) {
  8171. this._edgesRenderer.dispose();
  8172. this._edgesRenderer = undefined;
  8173. }
  8174. };
  8175. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  8176. if (epsilon === void 0) { epsilon = 0.95; }
  8177. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  8178. this.disableEdgesRendering();
  8179. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  8180. };
  8181. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  8182. get: function () {
  8183. return false;
  8184. },
  8185. enumerable: true,
  8186. configurable: true
  8187. });
  8188. AbstractMesh.prototype.getLOD = function (camera) {
  8189. return this;
  8190. };
  8191. AbstractMesh.prototype.getTotalVertices = function () {
  8192. return 0;
  8193. };
  8194. AbstractMesh.prototype.getIndices = function () {
  8195. return null;
  8196. };
  8197. AbstractMesh.prototype.getVerticesData = function (kind) {
  8198. return null;
  8199. };
  8200. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  8201. return false;
  8202. };
  8203. AbstractMesh.prototype.getBoundingInfo = function () {
  8204. if (this._masterMesh) {
  8205. return this._masterMesh.getBoundingInfo();
  8206. }
  8207. if (!this._boundingInfo) {
  8208. this._updateBoundingInfo();
  8209. }
  8210. return this._boundingInfo;
  8211. };
  8212. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  8213. get: function () {
  8214. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  8215. },
  8216. enumerable: true,
  8217. configurable: true
  8218. });
  8219. AbstractMesh.prototype._preActivate = function () {
  8220. };
  8221. AbstractMesh.prototype._activate = function (renderId) {
  8222. this._renderId = renderId;
  8223. };
  8224. AbstractMesh.prototype.getWorldMatrix = function () {
  8225. if (this._masterMesh) {
  8226. return this._masterMesh.getWorldMatrix();
  8227. }
  8228. if (this._currentRenderId !== this.getScene().getRenderId()) {
  8229. this.computeWorldMatrix();
  8230. }
  8231. return this._worldMatrix;
  8232. };
  8233. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  8234. get: function () {
  8235. return this._worldMatrix;
  8236. },
  8237. enumerable: true,
  8238. configurable: true
  8239. });
  8240. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  8241. get: function () {
  8242. return this._absolutePosition;
  8243. },
  8244. enumerable: true,
  8245. configurable: true
  8246. });
  8247. AbstractMesh.prototype.freezeWorldMatrix = function () {
  8248. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  8249. this.computeWorldMatrix(true);
  8250. this._isWorldMatrixFrozen = true;
  8251. };
  8252. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  8253. this._isWorldMatrixFrozen = false;
  8254. this.computeWorldMatrix(true);
  8255. };
  8256. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  8257. get: function () {
  8258. return this._isWorldMatrixFrozen;
  8259. },
  8260. enumerable: true,
  8261. configurable: true
  8262. });
  8263. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  8264. axis.normalize();
  8265. if (!this.rotationQuaternion) {
  8266. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  8267. this.rotation = BABYLON.Vector3.Zero();
  8268. }
  8269. var rotationQuaternion;
  8270. if (!space || space === BABYLON.Space.LOCAL) {
  8271. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8272. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  8273. }
  8274. else {
  8275. if (this.parent) {
  8276. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8277. invertParentWorldMatrix.invert();
  8278. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  8279. }
  8280. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8281. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  8282. }
  8283. };
  8284. AbstractMesh.prototype.translate = function (axis, distance, space) {
  8285. var displacementVector = axis.scale(distance);
  8286. if (!space || space === BABYLON.Space.LOCAL) {
  8287. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  8288. this.setPositionWithLocalVector(tempV3);
  8289. }
  8290. else {
  8291. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  8292. }
  8293. };
  8294. AbstractMesh.prototype.getAbsolutePosition = function () {
  8295. this.computeWorldMatrix();
  8296. return this._absolutePosition;
  8297. };
  8298. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  8299. if (!absolutePosition) {
  8300. return;
  8301. }
  8302. var absolutePositionX;
  8303. var absolutePositionY;
  8304. var absolutePositionZ;
  8305. if (absolutePosition.x === undefined) {
  8306. if (arguments.length < 3) {
  8307. return;
  8308. }
  8309. absolutePositionX = arguments[0];
  8310. absolutePositionY = arguments[1];
  8311. absolutePositionZ = arguments[2];
  8312. }
  8313. else {
  8314. absolutePositionX = absolutePosition.x;
  8315. absolutePositionY = absolutePosition.y;
  8316. absolutePositionZ = absolutePosition.z;
  8317. }
  8318. if (this.parent) {
  8319. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8320. invertParentWorldMatrix.invert();
  8321. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  8322. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  8323. }
  8324. else {
  8325. this.position.x = absolutePositionX;
  8326. this.position.y = absolutePositionY;
  8327. this.position.z = absolutePositionZ;
  8328. }
  8329. };
  8330. // ================================== Point of View Movement =================================
  8331. /**
  8332. * Perform relative position change from the point of view of behind the front of the mesh.
  8333. * This is performed taking into account the meshes current rotation, so you do not have to care.
  8334. * Supports definition of mesh facing forward or backward.
  8335. * @param {number} amountRight
  8336. * @param {number} amountUp
  8337. * @param {number} amountForward
  8338. */
  8339. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  8340. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  8341. };
  8342. /**
  8343. * Calculate relative position change from the point of view of behind the front of the mesh.
  8344. * This is performed taking into account the meshes current rotation, so you do not have to care.
  8345. * Supports definition of mesh facing forward or backward.
  8346. * @param {number} amountRight
  8347. * @param {number} amountUp
  8348. * @param {number} amountForward
  8349. */
  8350. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  8351. var rotMatrix = new BABYLON.Matrix();
  8352. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  8353. rotQuaternion.toRotationMatrix(rotMatrix);
  8354. var translationDelta = BABYLON.Vector3.Zero();
  8355. var defForwardMult = this.definedFacingForward ? -1 : 1;
  8356. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  8357. return translationDelta;
  8358. };
  8359. // ================================== Point of View Rotation =================================
  8360. /**
  8361. * Perform relative rotation change from the point of view of behind the front of the mesh.
  8362. * Supports definition of mesh facing forward or backward.
  8363. * @param {number} flipBack
  8364. * @param {number} twirlClockwise
  8365. * @param {number} tiltRight
  8366. */
  8367. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  8368. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  8369. };
  8370. /**
  8371. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  8372. * Supports definition of mesh facing forward or backward.
  8373. * @param {number} flipBack
  8374. * @param {number} twirlClockwise
  8375. * @param {number} tiltRight
  8376. */
  8377. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  8378. var defForwardMult = this.definedFacingForward ? 1 : -1;
  8379. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  8380. };
  8381. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  8382. this._pivotMatrix = matrix;
  8383. this._cache.pivotMatrixUpdated = true;
  8384. };
  8385. AbstractMesh.prototype.getPivotMatrix = function () {
  8386. return this._pivotMatrix;
  8387. };
  8388. AbstractMesh.prototype._isSynchronized = function () {
  8389. if (this._isDirty) {
  8390. return false;
  8391. }
  8392. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  8393. return false;
  8394. if (this._cache.pivotMatrixUpdated) {
  8395. return false;
  8396. }
  8397. if (this.infiniteDistance) {
  8398. return false;
  8399. }
  8400. if (!this._cache.position.equals(this.position))
  8401. return false;
  8402. if (this.rotationQuaternion) {
  8403. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  8404. return false;
  8405. }
  8406. else {
  8407. if (!this._cache.rotation.equals(this.rotation))
  8408. return false;
  8409. }
  8410. if (!this._cache.scaling.equals(this.scaling))
  8411. return false;
  8412. return true;
  8413. };
  8414. AbstractMesh.prototype._initCache = function () {
  8415. _super.prototype._initCache.call(this);
  8416. this._cache.localMatrixUpdated = false;
  8417. this._cache.position = BABYLON.Vector3.Zero();
  8418. this._cache.scaling = BABYLON.Vector3.Zero();
  8419. this._cache.rotation = BABYLON.Vector3.Zero();
  8420. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  8421. this._cache.billboardMode = -1;
  8422. };
  8423. AbstractMesh.prototype.markAsDirty = function (property) {
  8424. if (property === "rotation") {
  8425. this.rotationQuaternion = null;
  8426. }
  8427. this._currentRenderId = Number.MAX_VALUE;
  8428. this._isDirty = true;
  8429. };
  8430. AbstractMesh.prototype._updateBoundingInfo = function () {
  8431. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  8432. this._boundingInfo.update(this.worldMatrixFromCache);
  8433. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  8434. };
  8435. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  8436. if (!this.subMeshes) {
  8437. return;
  8438. }
  8439. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  8440. var subMesh = this.subMeshes[subIndex];
  8441. if (!subMesh.IsGlobal) {
  8442. subMesh.updateBoundingInfo(matrix);
  8443. }
  8444. }
  8445. };
  8446. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  8447. if (this._isWorldMatrixFrozen) {
  8448. return this._worldMatrix;
  8449. }
  8450. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  8451. this._currentRenderId = this.getScene().getRenderId();
  8452. return this._worldMatrix;
  8453. }
  8454. this._cache.position.copyFrom(this.position);
  8455. this._cache.scaling.copyFrom(this.scaling);
  8456. this._cache.pivotMatrixUpdated = false;
  8457. this._cache.billboardMode = this.billboardMode;
  8458. this._currentRenderId = this.getScene().getRenderId();
  8459. this._isDirty = false;
  8460. // Scaling
  8461. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  8462. // Rotation
  8463. //rotate, if quaternion is set and rotation was used
  8464. if (this.rotationQuaternion) {
  8465. var len = this.rotation.length();
  8466. if (len) {
  8467. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  8468. this.rotation.copyFromFloats(0, 0, 0);
  8469. }
  8470. }
  8471. if (this.rotationQuaternion) {
  8472. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  8473. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  8474. }
  8475. else {
  8476. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  8477. this._cache.rotation.copyFrom(this.rotation);
  8478. }
  8479. // Translation
  8480. if (this.infiniteDistance && !this.parent) {
  8481. var camera = this.getScene().activeCamera;
  8482. if (camera) {
  8483. var cameraWorldMatrix = camera.getWorldMatrix();
  8484. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  8485. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  8486. }
  8487. }
  8488. else {
  8489. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  8490. }
  8491. // Composing transformations
  8492. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  8493. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  8494. // Billboarding
  8495. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  8496. var localPosition = this.position.clone();
  8497. var zero = this.getScene().activeCamera.globalPosition.clone();
  8498. if (this.parent && this.parent.position) {
  8499. localPosition.addInPlace(this.parent.position);
  8500. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, BABYLON.Tmp.Matrix[2]);
  8501. }
  8502. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  8503. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  8504. zero.x = localPosition.x + BABYLON.Epsilon;
  8505. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  8506. zero.y = localPosition.y + BABYLON.Epsilon;
  8507. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  8508. zero.z = localPosition.z + BABYLON.Epsilon;
  8509. }
  8510. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), BABYLON.Tmp.Matrix[3]);
  8511. BABYLON.Tmp.Matrix[3].m[12] = BABYLON.Tmp.Matrix[3].m[13] = BABYLON.Tmp.Matrix[3].m[14] = 0;
  8512. BABYLON.Tmp.Matrix[3].invert();
  8513. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[3], this._localWorld);
  8514. this._rotateYByPI.multiplyToRef(this._localWorld, BABYLON.Tmp.Matrix[5]);
  8515. }
  8516. // Local world
  8517. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  8518. // Parent
  8519. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  8520. this._markSyncedWithParent();
  8521. if (this._meshToBoneReferal) {
  8522. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  8523. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  8524. }
  8525. else {
  8526. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  8527. }
  8528. }
  8529. else {
  8530. this._worldMatrix.copyFrom(this._localWorld);
  8531. }
  8532. // Bounding info
  8533. this._updateBoundingInfo();
  8534. // Absolute position
  8535. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  8536. // Callbacks
  8537. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  8538. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  8539. }
  8540. if (!this._poseMatrix) {
  8541. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  8542. }
  8543. return this._worldMatrix;
  8544. };
  8545. /**
  8546. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  8547. * @param func: callback function to add
  8548. */
  8549. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  8550. this._onAfterWorldMatrixUpdate.push(func);
  8551. };
  8552. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  8553. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  8554. if (index > -1) {
  8555. this._onAfterWorldMatrixUpdate.splice(index, 1);
  8556. }
  8557. };
  8558. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  8559. this.computeWorldMatrix();
  8560. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  8561. };
  8562. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  8563. this.computeWorldMatrix();
  8564. var invLocalWorldMatrix = this._localWorld.clone();
  8565. invLocalWorldMatrix.invert();
  8566. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  8567. };
  8568. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  8569. this.computeWorldMatrix(true);
  8570. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  8571. };
  8572. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  8573. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  8574. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  8575. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  8576. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  8577. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  8578. /// <returns>Mesh oriented towards targetMesh</returns>
  8579. yawCor = yawCor || 0; // default to zero if undefined
  8580. pitchCor = pitchCor || 0;
  8581. rollCor = rollCor || 0;
  8582. var dv = targetPoint.subtract(this.position);
  8583. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  8584. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  8585. var pitch = Math.atan2(dv.y, len);
  8586. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  8587. };
  8588. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  8589. this._meshToBoneReferal = affectedMesh;
  8590. this.parent = bone;
  8591. if (bone.getWorldMatrix().determinant() < 0) {
  8592. this.scalingDeterminant *= -1;
  8593. }
  8594. };
  8595. AbstractMesh.prototype.detachFromBone = function () {
  8596. if (this.parent.getWorldMatrix().determinant() < 0) {
  8597. this.scalingDeterminant *= -1;
  8598. }
  8599. this._meshToBoneReferal = null;
  8600. this.parent = null;
  8601. };
  8602. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  8603. return this._boundingInfo.isInFrustum(frustumPlanes);
  8604. };
  8605. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  8606. if (!camera) {
  8607. camera = this.getScene().activeCamera;
  8608. }
  8609. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  8610. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  8611. return false;
  8612. }
  8613. return true;
  8614. };
  8615. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  8616. if (!this._boundingInfo || !mesh._boundingInfo) {
  8617. return false;
  8618. }
  8619. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  8620. };
  8621. AbstractMesh.prototype.intersectsPoint = function (point) {
  8622. if (!this._boundingInfo) {
  8623. return false;
  8624. }
  8625. return this._boundingInfo.intersectsPoint(point);
  8626. };
  8627. // Physics
  8628. /**
  8629. * @Deprecated. Use new PhysicsImpostor instead.
  8630. * */
  8631. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  8632. //legacy support
  8633. if (impostor.impostor) {
  8634. options = impostor;
  8635. impostor = impostor.impostor;
  8636. }
  8637. this.physicsImpostor = new BABYLON.PhysicsImpostor(this, impostor, options);
  8638. return this.physicsImpostor.physicsBody;
  8639. };
  8640. AbstractMesh.prototype.getPhysicsImpostor = function () {
  8641. return this.physicsImpostor;
  8642. };
  8643. /**
  8644. * @Deprecated. Use getPhysicsImpostor().getParam("mass");
  8645. */
  8646. AbstractMesh.prototype.getPhysicsMass = function () {
  8647. return this.physicsImpostor.getParam("mass");
  8648. };
  8649. /**
  8650. * @Deprecated. Use getPhysicsImpostor().getParam("friction");
  8651. */
  8652. AbstractMesh.prototype.getPhysicsFriction = function () {
  8653. return this.physicsImpostor.getParam("friction");
  8654. };
  8655. /**
  8656. * @Deprecated. Use getPhysicsImpostor().getParam("restitution");
  8657. */
  8658. AbstractMesh.prototype.getPhysicsRestitution = function () {
  8659. return this.physicsImpostor.getParam("resitution");
  8660. };
  8661. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  8662. if (!camera) {
  8663. camera = this.getScene().activeCamera;
  8664. }
  8665. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  8666. };
  8667. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  8668. if (!camera) {
  8669. camera = this.getScene().activeCamera;
  8670. }
  8671. return this.absolutePosition.subtract(camera.position).length();
  8672. };
  8673. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  8674. if (!this.physicsImpostor) {
  8675. return;
  8676. }
  8677. this.physicsImpostor.applyImpulse(force, contactPoint);
  8678. };
  8679. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  8680. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  8681. return;
  8682. }
  8683. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  8684. mainPivot: pivot1,
  8685. connectedPivot: pivot2,
  8686. nativeParams: options
  8687. });
  8688. };
  8689. /**
  8690. * @Deprecated
  8691. */
  8692. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  8693. BABYLON.Tools.Warn("updatePhysicsBodyPosition() is deprecated, please use updatePhysicsBody()");
  8694. this.updatePhysicsBody();
  8695. };
  8696. /**
  8697. * @Deprecated
  8698. * Calling this function is not needed anymore.
  8699. * The physics engine takes care of transofmration automatically.
  8700. */
  8701. AbstractMesh.prototype.updatePhysicsBody = function () {
  8702. //Unneeded
  8703. };
  8704. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  8705. // Collisions
  8706. get: function () {
  8707. return this._checkCollisions;
  8708. },
  8709. set: function (collisionEnabled) {
  8710. this._checkCollisions = collisionEnabled;
  8711. if (this.getScene().workerCollisions) {
  8712. this.getScene().collisionCoordinator.onMeshUpdated(this);
  8713. }
  8714. },
  8715. enumerable: true,
  8716. configurable: true
  8717. });
  8718. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  8719. var globalPosition = this.getAbsolutePosition();
  8720. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  8721. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  8722. this._collider.radius = this.ellipsoid;
  8723. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  8724. };
  8725. // Submeshes octree
  8726. /**
  8727. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  8728. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  8729. */
  8730. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  8731. if (maxCapacity === void 0) { maxCapacity = 64; }
  8732. if (maxDepth === void 0) { maxDepth = 2; }
  8733. if (!this._submeshesOctree) {
  8734. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  8735. }
  8736. this.computeWorldMatrix(true);
  8737. // Update octree
  8738. var bbox = this.getBoundingInfo().boundingBox;
  8739. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  8740. return this._submeshesOctree;
  8741. };
  8742. // Collisions
  8743. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  8744. this._generatePointsArray();
  8745. // Transformation
  8746. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  8747. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  8748. subMesh._lastColliderWorldVertices = [];
  8749. subMesh._trianglePlanes = [];
  8750. var start = subMesh.verticesStart;
  8751. var end = (subMesh.verticesStart + subMesh.verticesCount);
  8752. for (var i = start; i < end; i++) {
  8753. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  8754. }
  8755. }
  8756. // Collide
  8757. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  8758. if (collider.collisionFound) {
  8759. collider.collidedMesh = this;
  8760. }
  8761. };
  8762. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  8763. var subMeshes;
  8764. var len;
  8765. // Octrees
  8766. if (this._submeshesOctree && this.useOctreeForCollisions) {
  8767. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  8768. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  8769. len = intersections.length;
  8770. subMeshes = intersections.data;
  8771. }
  8772. else {
  8773. subMeshes = this.subMeshes;
  8774. len = subMeshes.length;
  8775. }
  8776. for (var index = 0; index < len; index++) {
  8777. var subMesh = subMeshes[index];
  8778. // Bounding test
  8779. if (len > 1 && !subMesh._checkCollision(collider))
  8780. continue;
  8781. this._collideForSubMesh(subMesh, transformMatrix, collider);
  8782. }
  8783. };
  8784. AbstractMesh.prototype._checkCollision = function (collider) {
  8785. // Bounding box test
  8786. if (!this._boundingInfo._checkCollision(collider))
  8787. return;
  8788. // Transformation matrix
  8789. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  8790. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  8791. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  8792. };
  8793. // Picking
  8794. AbstractMesh.prototype._generatePointsArray = function () {
  8795. return false;
  8796. };
  8797. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  8798. var pickingInfo = new BABYLON.PickingInfo();
  8799. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  8800. return pickingInfo;
  8801. }
  8802. if (!this._generatePointsArray()) {
  8803. return pickingInfo;
  8804. }
  8805. var intersectInfo = null;
  8806. // Octrees
  8807. var subMeshes;
  8808. var len;
  8809. if (this._submeshesOctree && this.useOctreeForPicking) {
  8810. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  8811. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  8812. len = intersections.length;
  8813. subMeshes = intersections.data;
  8814. }
  8815. else {
  8816. subMeshes = this.subMeshes;
  8817. len = subMeshes.length;
  8818. }
  8819. for (var index = 0; index < len; index++) {
  8820. var subMesh = subMeshes[index];
  8821. // Bounding test
  8822. if (len > 1 && !subMesh.canIntersects(ray))
  8823. continue;
  8824. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  8825. if (currentIntersectInfo) {
  8826. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  8827. intersectInfo = currentIntersectInfo;
  8828. intersectInfo.subMeshId = index;
  8829. if (fastCheck) {
  8830. break;
  8831. }
  8832. }
  8833. }
  8834. }
  8835. if (intersectInfo) {
  8836. // Get picked point
  8837. var world = this.getWorldMatrix();
  8838. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  8839. var direction = ray.direction.clone();
  8840. direction = direction.scale(intersectInfo.distance);
  8841. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  8842. var pickedPoint = worldOrigin.add(worldDirection);
  8843. // Return result
  8844. pickingInfo.hit = true;
  8845. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  8846. pickingInfo.pickedPoint = pickedPoint;
  8847. pickingInfo.pickedMesh = this;
  8848. pickingInfo.bu = intersectInfo.bu;
  8849. pickingInfo.bv = intersectInfo.bv;
  8850. pickingInfo.faceId = intersectInfo.faceId;
  8851. pickingInfo.subMeshId = intersectInfo.subMeshId;
  8852. return pickingInfo;
  8853. }
  8854. return pickingInfo;
  8855. };
  8856. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8857. return null;
  8858. };
  8859. AbstractMesh.prototype.releaseSubMeshes = function () {
  8860. if (this.subMeshes) {
  8861. while (this.subMeshes.length) {
  8862. this.subMeshes[0].dispose();
  8863. }
  8864. }
  8865. else {
  8866. this.subMeshes = new Array();
  8867. }
  8868. };
  8869. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  8870. var index;
  8871. // Action manager
  8872. if (this.actionManager) {
  8873. this.actionManager.dispose();
  8874. this.actionManager = null;
  8875. }
  8876. // Skeleton
  8877. this.skeleton = null;
  8878. // Animations
  8879. this.getScene().stopAnimation(this);
  8880. // Physics
  8881. if (this.physicsImpostor) {
  8882. this.physicsImpostor.dispose(!doNotRecurse);
  8883. }
  8884. // Intersections in progress
  8885. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  8886. var other = this._intersectionsInProgress[index];
  8887. var pos = other._intersectionsInProgress.indexOf(this);
  8888. other._intersectionsInProgress.splice(pos, 1);
  8889. }
  8890. this._intersectionsInProgress = [];
  8891. // Edges
  8892. if (this._edgesRenderer) {
  8893. this._edgesRenderer.dispose();
  8894. this._edgesRenderer = null;
  8895. }
  8896. // SubMeshes
  8897. this.releaseSubMeshes();
  8898. // Remove from scene
  8899. this.getScene().removeMesh(this);
  8900. if (!doNotRecurse) {
  8901. // Particles
  8902. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8903. if (this.getScene().particleSystems[index].emitter === this) {
  8904. this.getScene().particleSystems[index].dispose();
  8905. index--;
  8906. }
  8907. }
  8908. // Children
  8909. var objects = this.getScene().meshes.slice(0);
  8910. for (index = 0; index < objects.length; index++) {
  8911. if (objects[index].parent === this) {
  8912. objects[index].dispose();
  8913. }
  8914. }
  8915. }
  8916. else {
  8917. for (index = 0; index < this.getScene().meshes.length; index++) {
  8918. var obj = this.getScene().meshes[index];
  8919. if (obj.parent === this) {
  8920. obj.parent = null;
  8921. obj.computeWorldMatrix(true);
  8922. }
  8923. }
  8924. }
  8925. this._onAfterWorldMatrixUpdate = [];
  8926. this._isDisposed = true;
  8927. // Callback
  8928. if (this.onDispose) {
  8929. this.onDispose();
  8930. }
  8931. };
  8932. // Statics
  8933. AbstractMesh._BILLBOARDMODE_NONE = 0;
  8934. AbstractMesh._BILLBOARDMODE_X = 1;
  8935. AbstractMesh._BILLBOARDMODE_Y = 2;
  8936. AbstractMesh._BILLBOARDMODE_Z = 4;
  8937. AbstractMesh._BILLBOARDMODE_ALL = 7;
  8938. return AbstractMesh;
  8939. })(BABYLON.Node);
  8940. BABYLON.AbstractMesh = AbstractMesh;
  8941. })(BABYLON || (BABYLON = {}));
  8942. var BABYLON;
  8943. (function (BABYLON) {
  8944. var Light = (function (_super) {
  8945. __extends(Light, _super);
  8946. function Light(name, scene) {
  8947. _super.call(this, name, scene);
  8948. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  8949. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  8950. this.intensity = 1.0;
  8951. this.range = Number.MAX_VALUE;
  8952. this.includeOnlyWithLayerMask = 0;
  8953. this.includedOnlyMeshes = new Array();
  8954. this.excludedMeshes = new Array();
  8955. this.excludeWithLayerMask = 0;
  8956. // PBR Properties.
  8957. this.radius = 0.00001;
  8958. this._excludedMeshesIds = new Array();
  8959. this._includedOnlyMeshesIds = new Array();
  8960. scene.addLight(this);
  8961. }
  8962. Light.prototype.getShadowGenerator = function () {
  8963. return this._shadowGenerator;
  8964. };
  8965. Light.prototype.getAbsolutePosition = function () {
  8966. return BABYLON.Vector3.Zero();
  8967. };
  8968. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  8969. };
  8970. Light.prototype._getWorldMatrix = function () {
  8971. return BABYLON.Matrix.Identity();
  8972. };
  8973. Light.prototype.canAffectMesh = function (mesh) {
  8974. if (!mesh) {
  8975. return true;
  8976. }
  8977. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  8978. return false;
  8979. }
  8980. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  8981. return false;
  8982. }
  8983. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  8984. return false;
  8985. }
  8986. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  8987. return false;
  8988. }
  8989. return true;
  8990. };
  8991. Light.prototype.getWorldMatrix = function () {
  8992. this._currentRenderId = this.getScene().getRenderId();
  8993. var worldMatrix = this._getWorldMatrix();
  8994. if (this.parent && this.parent.getWorldMatrix) {
  8995. if (!this._parentedWorldMatrix) {
  8996. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  8997. }
  8998. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  8999. this._markSyncedWithParent();
  9000. return this._parentedWorldMatrix;
  9001. }
  9002. return worldMatrix;
  9003. };
  9004. Light.prototype.dispose = function () {
  9005. if (this._shadowGenerator) {
  9006. this._shadowGenerator.dispose();
  9007. this._shadowGenerator = null;
  9008. }
  9009. // Animations
  9010. this.getScene().stopAnimation(this);
  9011. // Remove from scene
  9012. this.getScene().removeLight(this);
  9013. };
  9014. Light.prototype.getTypeID = function () {
  9015. return 0;
  9016. };
  9017. Light.prototype.clone = function (name) {
  9018. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  9019. };
  9020. Light.prototype.serialize = function () {
  9021. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  9022. // Type
  9023. serializationObject.type = this.getTypeID();
  9024. // Parent
  9025. if (this.parent) {
  9026. serializationObject.parentId = this.parent.id;
  9027. }
  9028. // Animations
  9029. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  9030. serializationObject.ranges = this.serializeAnimationRanges();
  9031. return serializationObject;
  9032. };
  9033. Light.GetConstructorFromName = function (type, name, scene) {
  9034. switch (type) {
  9035. case 0:
  9036. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  9037. case 1:
  9038. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  9039. case 2:
  9040. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  9041. case 3:
  9042. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  9043. }
  9044. };
  9045. Light.Parse = function (parsedLight, scene) {
  9046. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  9047. // Inclusion / exclusions
  9048. if (parsedLight.excludedMeshesIds) {
  9049. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  9050. }
  9051. if (parsedLight.includedOnlyMeshesIds) {
  9052. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  9053. }
  9054. // Parent
  9055. if (parsedLight.parentId) {
  9056. light._waitingParentId = parsedLight.parentId;
  9057. }
  9058. // Animations
  9059. if (parsedLight.animations) {
  9060. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  9061. var parsedAnimation = parsedLight.animations[animationIndex];
  9062. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  9063. }
  9064. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  9065. }
  9066. if (parsedLight.autoAnimate) {
  9067. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  9068. }
  9069. return light;
  9070. };
  9071. __decorate([
  9072. BABYLON.serializeAsColor3()
  9073. ], Light.prototype, "diffuse", void 0);
  9074. __decorate([
  9075. BABYLON.serializeAsColor3()
  9076. ], Light.prototype, "specular", void 0);
  9077. __decorate([
  9078. BABYLON.serialize()
  9079. ], Light.prototype, "intensity", void 0);
  9080. __decorate([
  9081. BABYLON.serialize()
  9082. ], Light.prototype, "range", void 0);
  9083. __decorate([
  9084. BABYLON.serialize()
  9085. ], Light.prototype, "includeOnlyWithLayerMask", void 0);
  9086. __decorate([
  9087. BABYLON.serialize()
  9088. ], Light.prototype, "radius", void 0);
  9089. return Light;
  9090. })(BABYLON.Node);
  9091. BABYLON.Light = Light;
  9092. })(BABYLON || (BABYLON = {}));
  9093. var BABYLON;
  9094. (function (BABYLON) {
  9095. var PointLight = (function (_super) {
  9096. __extends(PointLight, _super);
  9097. function PointLight(name, position, scene) {
  9098. _super.call(this, name, scene);
  9099. this.position = position;
  9100. }
  9101. PointLight.prototype.getAbsolutePosition = function () {
  9102. return this.transformedPosition ? this.transformedPosition : this.position;
  9103. };
  9104. PointLight.prototype.computeTransformedPosition = function () {
  9105. if (this.parent && this.parent.getWorldMatrix) {
  9106. if (!this.transformedPosition) {
  9107. this.transformedPosition = BABYLON.Vector3.Zero();
  9108. }
  9109. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  9110. return true;
  9111. }
  9112. return false;
  9113. };
  9114. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  9115. if (this.parent && this.parent.getWorldMatrix) {
  9116. this.computeTransformedPosition();
  9117. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
  9118. return;
  9119. }
  9120. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  9121. };
  9122. PointLight.prototype.needCube = function () {
  9123. return true;
  9124. };
  9125. PointLight.prototype.supportsVSM = function () {
  9126. return false;
  9127. };
  9128. PointLight.prototype.needRefreshPerFrame = function () {
  9129. return false;
  9130. };
  9131. PointLight.prototype.getShadowDirection = function (faceIndex) {
  9132. switch (faceIndex) {
  9133. case 0:
  9134. return new BABYLON.Vector3(1, 0, 0);
  9135. case 1:
  9136. return new BABYLON.Vector3(-1, 0, 0);
  9137. case 2:
  9138. return new BABYLON.Vector3(0, -1, 0);
  9139. case 3:
  9140. return new BABYLON.Vector3(0, 1, 0);
  9141. case 4:
  9142. return new BABYLON.Vector3(0, 0, 1);
  9143. case 5:
  9144. return new BABYLON.Vector3(0, 0, -1);
  9145. }
  9146. return BABYLON.Vector3.Zero();
  9147. };
  9148. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  9149. var activeCamera = this.getScene().activeCamera;
  9150. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  9151. };
  9152. PointLight.prototype._getWorldMatrix = function () {
  9153. if (!this._worldMatrix) {
  9154. this._worldMatrix = BABYLON.Matrix.Identity();
  9155. }
  9156. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  9157. return this._worldMatrix;
  9158. };
  9159. PointLight.prototype.getTypeID = function () {
  9160. return 0;
  9161. };
  9162. __decorate([
  9163. BABYLON.serializeAsVector3()
  9164. ], PointLight.prototype, "position", void 0);
  9165. return PointLight;
  9166. })(BABYLON.Light);
  9167. BABYLON.PointLight = PointLight;
  9168. })(BABYLON || (BABYLON = {}));
  9169. var BABYLON;
  9170. (function (BABYLON) {
  9171. var SpotLight = (function (_super) {
  9172. __extends(SpotLight, _super);
  9173. function SpotLight(name, position, direction, angle, exponent, scene) {
  9174. _super.call(this, name, scene);
  9175. this.position = position;
  9176. this.direction = direction;
  9177. this.angle = angle;
  9178. this.exponent = exponent;
  9179. }
  9180. SpotLight.prototype.getAbsolutePosition = function () {
  9181. return this.transformedPosition ? this.transformedPosition : this.position;
  9182. };
  9183. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  9184. var activeCamera = this.getScene().activeCamera;
  9185. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  9186. };
  9187. SpotLight.prototype.needCube = function () {
  9188. return false;
  9189. };
  9190. SpotLight.prototype.supportsVSM = function () {
  9191. return true;
  9192. };
  9193. SpotLight.prototype.needRefreshPerFrame = function () {
  9194. return false;
  9195. };
  9196. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  9197. return this.direction;
  9198. };
  9199. SpotLight.prototype.setDirectionToTarget = function (target) {
  9200. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  9201. return this.direction;
  9202. };
  9203. SpotLight.prototype.computeTransformedPosition = function () {
  9204. if (this.parent && this.parent.getWorldMatrix) {
  9205. if (!this.transformedPosition) {
  9206. this.transformedPosition = BABYLON.Vector3.Zero();
  9207. }
  9208. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  9209. return true;
  9210. }
  9211. return false;
  9212. };
  9213. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  9214. var normalizeDirection;
  9215. if (this.parent && this.parent.getWorldMatrix) {
  9216. if (!this._transformedDirection) {
  9217. this._transformedDirection = BABYLON.Vector3.Zero();
  9218. }
  9219. this.computeTransformedPosition();
  9220. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  9221. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  9222. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  9223. }
  9224. else {
  9225. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  9226. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  9227. }
  9228. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  9229. };
  9230. SpotLight.prototype._getWorldMatrix = function () {
  9231. if (!this._worldMatrix) {
  9232. this._worldMatrix = BABYLON.Matrix.Identity();
  9233. }
  9234. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  9235. return this._worldMatrix;
  9236. };
  9237. SpotLight.prototype.getTypeID = function () {
  9238. return 2;
  9239. };
  9240. __decorate([
  9241. BABYLON.serializeAsVector3()
  9242. ], SpotLight.prototype, "position", void 0);
  9243. __decorate([
  9244. BABYLON.serializeAsVector3()
  9245. ], SpotLight.prototype, "direction", void 0);
  9246. __decorate([
  9247. BABYLON.serialize()
  9248. ], SpotLight.prototype, "angle", void 0);
  9249. __decorate([
  9250. BABYLON.serialize()
  9251. ], SpotLight.prototype, "exponent", void 0);
  9252. return SpotLight;
  9253. })(BABYLON.Light);
  9254. BABYLON.SpotLight = SpotLight;
  9255. })(BABYLON || (BABYLON = {}));
  9256. var BABYLON;
  9257. (function (BABYLON) {
  9258. var HemisphericLight = (function (_super) {
  9259. __extends(HemisphericLight, _super);
  9260. function HemisphericLight(name, direction, scene) {
  9261. _super.call(this, name, scene);
  9262. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  9263. this.direction = direction;
  9264. }
  9265. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  9266. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  9267. return this.direction;
  9268. };
  9269. HemisphericLight.prototype.getShadowGenerator = function () {
  9270. return null;
  9271. };
  9272. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  9273. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  9274. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  9275. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  9276. };
  9277. HemisphericLight.prototype._getWorldMatrix = function () {
  9278. if (!this._worldMatrix) {
  9279. this._worldMatrix = BABYLON.Matrix.Identity();
  9280. }
  9281. return this._worldMatrix;
  9282. };
  9283. HemisphericLight.prototype.getTypeID = function () {
  9284. return 3;
  9285. };
  9286. __decorate([
  9287. BABYLON.serializeAsColor3()
  9288. ], HemisphericLight.prototype, "groundColor", void 0);
  9289. __decorate([
  9290. BABYLON.serializeAsVector3()
  9291. ], HemisphericLight.prototype, "direction", void 0);
  9292. return HemisphericLight;
  9293. })(BABYLON.Light);
  9294. BABYLON.HemisphericLight = HemisphericLight;
  9295. })(BABYLON || (BABYLON = {}));
  9296. var BABYLON;
  9297. (function (BABYLON) {
  9298. var DirectionalLight = (function (_super) {
  9299. __extends(DirectionalLight, _super);
  9300. function DirectionalLight(name, direction, scene) {
  9301. _super.call(this, name, scene);
  9302. this.shadowOrthoScale = 0.5;
  9303. this.autoUpdateExtends = true;
  9304. // Cache
  9305. this._orthoLeft = Number.MAX_VALUE;
  9306. this._orthoRight = Number.MIN_VALUE;
  9307. this._orthoTop = Number.MIN_VALUE;
  9308. this._orthoBottom = Number.MAX_VALUE;
  9309. this.position = direction.scale(-1);
  9310. this.direction = direction;
  9311. }
  9312. DirectionalLight.prototype.getAbsolutePosition = function () {
  9313. return this.transformedPosition ? this.transformedPosition : this.position;
  9314. };
  9315. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  9316. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  9317. return this.direction;
  9318. };
  9319. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  9320. var activeCamera = this.getScene().activeCamera;
  9321. // Check extends
  9322. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  9323. var tempVector3 = BABYLON.Vector3.Zero();
  9324. this._orthoLeft = Number.MAX_VALUE;
  9325. this._orthoRight = Number.MIN_VALUE;
  9326. this._orthoTop = Number.MIN_VALUE;
  9327. this._orthoBottom = Number.MAX_VALUE;
  9328. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  9329. var mesh = renderList[meshIndex];
  9330. if (!mesh) {
  9331. continue;
  9332. }
  9333. var boundingInfo = mesh.getBoundingInfo();
  9334. if (!boundingInfo) {
  9335. continue;
  9336. }
  9337. var boundingBox = boundingInfo.boundingBox;
  9338. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  9339. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  9340. if (tempVector3.x < this._orthoLeft)
  9341. this._orthoLeft = tempVector3.x;
  9342. if (tempVector3.y < this._orthoBottom)
  9343. this._orthoBottom = tempVector3.y;
  9344. if (tempVector3.x > this._orthoRight)
  9345. this._orthoRight = tempVector3.x;
  9346. if (tempVector3.y > this._orthoTop)
  9347. this._orthoTop = tempVector3.y;
  9348. }
  9349. }
  9350. }
  9351. var xOffset = this._orthoRight - this._orthoLeft;
  9352. var yOffset = this._orthoTop - this._orthoBottom;
  9353. 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);
  9354. };
  9355. DirectionalLight.prototype.supportsVSM = function () {
  9356. return true;
  9357. };
  9358. DirectionalLight.prototype.needRefreshPerFrame = function () {
  9359. return true;
  9360. };
  9361. DirectionalLight.prototype.needCube = function () {
  9362. return false;
  9363. };
  9364. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  9365. return this.direction;
  9366. };
  9367. DirectionalLight.prototype.computeTransformedPosition = function () {
  9368. if (this.parent && this.parent.getWorldMatrix) {
  9369. if (!this.transformedPosition) {
  9370. this.transformedPosition = BABYLON.Vector3.Zero();
  9371. }
  9372. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  9373. return true;
  9374. }
  9375. return false;
  9376. };
  9377. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  9378. if (this.parent && this.parent.getWorldMatrix) {
  9379. if (!this._transformedDirection) {
  9380. this._transformedDirection = BABYLON.Vector3.Zero();
  9381. }
  9382. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  9383. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  9384. return;
  9385. }
  9386. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  9387. };
  9388. DirectionalLight.prototype._getWorldMatrix = function () {
  9389. if (!this._worldMatrix) {
  9390. this._worldMatrix = BABYLON.Matrix.Identity();
  9391. }
  9392. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  9393. return this._worldMatrix;
  9394. };
  9395. DirectionalLight.prototype.getTypeID = function () {
  9396. return 1;
  9397. };
  9398. __decorate([
  9399. BABYLON.serializeAsVector3()
  9400. ], DirectionalLight.prototype, "position", void 0);
  9401. __decorate([
  9402. BABYLON.serializeAsVector3()
  9403. ], DirectionalLight.prototype, "direction", void 0);
  9404. __decorate([
  9405. BABYLON.serialize()
  9406. ], DirectionalLight.prototype, "shadowOrthoScale", void 0);
  9407. __decorate([
  9408. BABYLON.serialize()
  9409. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  9410. return DirectionalLight;
  9411. })(BABYLON.Light);
  9412. BABYLON.DirectionalLight = DirectionalLight;
  9413. })(BABYLON || (BABYLON = {}));
  9414. var BABYLON;
  9415. (function (BABYLON) {
  9416. var ShadowGenerator = (function () {
  9417. function ShadowGenerator(mapSize, light) {
  9418. var _this = this;
  9419. // Members
  9420. this._filter = ShadowGenerator.FILTER_NONE;
  9421. this.blurScale = 2;
  9422. this._blurBoxOffset = 0;
  9423. this._bias = 0.00005;
  9424. this._lightDirection = BABYLON.Vector3.Zero();
  9425. this.forceBackFacesOnly = false;
  9426. this._darkness = 0;
  9427. this._transparencyShadow = false;
  9428. this._viewMatrix = BABYLON.Matrix.Zero();
  9429. this._projectionMatrix = BABYLON.Matrix.Zero();
  9430. this._transformMatrix = BABYLON.Matrix.Zero();
  9431. this._worldViewProjection = BABYLON.Matrix.Zero();
  9432. this._currentFaceIndex = 0;
  9433. this._currentFaceIndexCache = 0;
  9434. this._light = light;
  9435. this._scene = light.getScene();
  9436. this._mapSize = mapSize;
  9437. light._shadowGenerator = this;
  9438. // Render target
  9439. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, light.needCube());
  9440. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9441. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9442. this._shadowMap.anisotropicFilteringLevel = 1;
  9443. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9444. this._shadowMap.renderParticles = false;
  9445. this._shadowMap.onBeforeRender = function (faceIndex) {
  9446. _this._currentFaceIndex = faceIndex;
  9447. };
  9448. this._shadowMap.onAfterUnbind = function () {
  9449. if (!_this.useBlurVarianceShadowMap) {
  9450. return;
  9451. }
  9452. if (!_this._shadowMap2) {
  9453. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  9454. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9455. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9456. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  9457. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  9458. _this._downSamplePostprocess.onApply = function (effect) {
  9459. effect.setTexture("textureSampler", _this._shadowMap);
  9460. };
  9461. _this.blurBoxOffset = 1;
  9462. }
  9463. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  9464. };
  9465. // Custom render function
  9466. var renderSubMesh = function (subMesh) {
  9467. var mesh = subMesh.getRenderingMesh();
  9468. var scene = _this._scene;
  9469. var engine = scene.getEngine();
  9470. // Culling
  9471. engine.setState(subMesh.getMaterial().backFaceCulling);
  9472. // Managing instances
  9473. var batch = mesh._getInstancesRenderList(subMesh._id);
  9474. if (batch.mustReturn) {
  9475. return;
  9476. }
  9477. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  9478. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  9479. engine.enableEffect(_this._effect);
  9480. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  9481. var material = subMesh.getMaterial();
  9482. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  9483. _this._effect.setVector3("lightPosition", _this.getLight().position);
  9484. if (_this.getLight().needCube()) {
  9485. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  9486. }
  9487. // Alpha test
  9488. if (material && material.needAlphaTesting()) {
  9489. var alphaTexture = material.getAlphaTestTexture();
  9490. _this._effect.setTexture("diffuseSampler", alphaTexture);
  9491. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  9492. }
  9493. // Bones
  9494. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  9495. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  9496. }
  9497. if (_this.forceBackFacesOnly) {
  9498. engine.setState(true, 0, false, true);
  9499. }
  9500. // Draw
  9501. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  9502. if (_this.forceBackFacesOnly) {
  9503. engine.setState(true, 0, false, false);
  9504. }
  9505. }
  9506. else {
  9507. // Need to reset refresh rate of the shadowMap
  9508. _this._shadowMap.resetRefreshCounter();
  9509. }
  9510. };
  9511. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  9512. var index;
  9513. for (index = 0; index < opaqueSubMeshes.length; index++) {
  9514. renderSubMesh(opaqueSubMeshes.data[index]);
  9515. }
  9516. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  9517. renderSubMesh(alphaTestSubMeshes.data[index]);
  9518. }
  9519. if (_this._transparencyShadow) {
  9520. for (index = 0; index < transparentSubMeshes.length; index++) {
  9521. renderSubMesh(transparentSubMeshes.data[index]);
  9522. }
  9523. }
  9524. };
  9525. this._shadowMap.onClear = function (engine) {
  9526. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  9527. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  9528. }
  9529. else {
  9530. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  9531. }
  9532. };
  9533. }
  9534. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  9535. // Static
  9536. get: function () {
  9537. return ShadowGenerator._FILTER_NONE;
  9538. },
  9539. enumerable: true,
  9540. configurable: true
  9541. });
  9542. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  9543. get: function () {
  9544. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  9545. },
  9546. enumerable: true,
  9547. configurable: true
  9548. });
  9549. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  9550. get: function () {
  9551. return ShadowGenerator._FILTER_POISSONSAMPLING;
  9552. },
  9553. enumerable: true,
  9554. configurable: true
  9555. });
  9556. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  9557. get: function () {
  9558. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  9559. },
  9560. enumerable: true,
  9561. configurable: true
  9562. });
  9563. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  9564. get: function () {
  9565. return this._bias;
  9566. },
  9567. set: function (bias) {
  9568. this._bias = bias;
  9569. },
  9570. enumerable: true,
  9571. configurable: true
  9572. });
  9573. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  9574. get: function () {
  9575. return this._blurBoxOffset;
  9576. },
  9577. set: function (value) {
  9578. var _this = this;
  9579. if (this._blurBoxOffset === value) {
  9580. return;
  9581. }
  9582. this._blurBoxOffset = value;
  9583. if (this._boxBlurPostprocess) {
  9584. this._boxBlurPostprocess.dispose();
  9585. }
  9586. 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);
  9587. this._boxBlurPostprocess.onApply = function (effect) {
  9588. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  9589. };
  9590. },
  9591. enumerable: true,
  9592. configurable: true
  9593. });
  9594. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  9595. get: function () {
  9596. return this._filter;
  9597. },
  9598. set: function (value) {
  9599. if (this._filter === value) {
  9600. return;
  9601. }
  9602. this._filter = value;
  9603. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  9604. this._shadowMap.anisotropicFilteringLevel = 16;
  9605. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  9606. }
  9607. else {
  9608. this._shadowMap.anisotropicFilteringLevel = 1;
  9609. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9610. }
  9611. },
  9612. enumerable: true,
  9613. configurable: true
  9614. });
  9615. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  9616. get: function () {
  9617. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  9618. },
  9619. set: function (value) {
  9620. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  9621. },
  9622. enumerable: true,
  9623. configurable: true
  9624. });
  9625. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  9626. get: function () {
  9627. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  9628. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  9629. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  9630. },
  9631. set: function (value) {
  9632. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  9633. },
  9634. enumerable: true,
  9635. configurable: true
  9636. });
  9637. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  9638. get: function () {
  9639. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  9640. },
  9641. set: function (value) {
  9642. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  9643. },
  9644. enumerable: true,
  9645. configurable: true
  9646. });
  9647. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  9648. var defines = [];
  9649. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  9650. defines.push("#define VSM");
  9651. }
  9652. if (this.getLight().needCube()) {
  9653. defines.push("#define CUBEMAP");
  9654. }
  9655. var attribs = [BABYLON.VertexBuffer.PositionKind];
  9656. var mesh = subMesh.getMesh();
  9657. var material = subMesh.getMaterial();
  9658. // Alpha test
  9659. if (material && material.needAlphaTesting()) {
  9660. defines.push("#define ALPHATEST");
  9661. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  9662. attribs.push(BABYLON.VertexBuffer.UVKind);
  9663. defines.push("#define UV1");
  9664. }
  9665. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  9666. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  9667. defines.push("#define UV2");
  9668. }
  9669. }
  9670. // Bones
  9671. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  9672. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  9673. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  9674. if (mesh.numBoneInfluencers > 4) {
  9675. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  9676. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  9677. }
  9678. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  9679. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  9680. }
  9681. else {
  9682. defines.push("#define NUM_BONE_INFLUENCERS 0");
  9683. }
  9684. // Instances
  9685. if (useInstances) {
  9686. defines.push("#define INSTANCES");
  9687. attribs.push("world0");
  9688. attribs.push("world1");
  9689. attribs.push("world2");
  9690. attribs.push("world3");
  9691. }
  9692. // Get correct effect
  9693. var join = defines.join("\n");
  9694. if (this._cachedDefines !== join) {
  9695. this._cachedDefines = join;
  9696. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues"], ["diffuseSampler"], join);
  9697. }
  9698. return this._effect.isReady();
  9699. };
  9700. ShadowGenerator.prototype.getShadowMap = function () {
  9701. return this._shadowMap;
  9702. };
  9703. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  9704. if (this._shadowMap2) {
  9705. return this._shadowMap2;
  9706. }
  9707. return this._shadowMap;
  9708. };
  9709. ShadowGenerator.prototype.getLight = function () {
  9710. return this._light;
  9711. };
  9712. // Methods
  9713. ShadowGenerator.prototype.getTransformMatrix = function () {
  9714. var scene = this._scene;
  9715. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  9716. return this._transformMatrix;
  9717. }
  9718. this._currentRenderID = scene.getRenderId();
  9719. this._currentFaceIndexCache = this._currentFaceIndex;
  9720. var lightPosition = this._light.position;
  9721. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  9722. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  9723. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  9724. }
  9725. if (this._light.computeTransformedPosition()) {
  9726. lightPosition = this._light.transformedPosition;
  9727. }
  9728. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  9729. this._cachedPosition = lightPosition.clone();
  9730. this._cachedDirection = this._lightDirection.clone();
  9731. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  9732. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  9733. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  9734. }
  9735. return this._transformMatrix;
  9736. };
  9737. ShadowGenerator.prototype.getDarkness = function () {
  9738. return this._darkness;
  9739. };
  9740. ShadowGenerator.prototype.setDarkness = function (darkness) {
  9741. if (darkness >= 1.0)
  9742. this._darkness = 1.0;
  9743. else if (darkness <= 0.0)
  9744. this._darkness = 0.0;
  9745. else
  9746. this._darkness = darkness;
  9747. };
  9748. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  9749. this._transparencyShadow = hasShadow;
  9750. };
  9751. ShadowGenerator.prototype._packHalf = function (depth) {
  9752. var scale = depth * 255.0;
  9753. var fract = scale - Math.floor(scale);
  9754. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  9755. };
  9756. ShadowGenerator.prototype.dispose = function () {
  9757. this._shadowMap.dispose();
  9758. if (this._shadowMap2) {
  9759. this._shadowMap2.dispose();
  9760. }
  9761. if (this._downSamplePostprocess) {
  9762. this._downSamplePostprocess.dispose();
  9763. }
  9764. if (this._boxBlurPostprocess) {
  9765. this._boxBlurPostprocess.dispose();
  9766. }
  9767. };
  9768. ShadowGenerator.prototype.serialize = function () {
  9769. var serializationObject = {};
  9770. serializationObject.lightId = this._light.id;
  9771. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  9772. serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
  9773. serializationObject.usePoissonSampling = this.usePoissonSampling;
  9774. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  9775. serializationObject.renderList = [];
  9776. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  9777. var mesh = this.getShadowMap().renderList[meshIndex];
  9778. serializationObject.renderList.push(mesh.id);
  9779. }
  9780. return serializationObject;
  9781. };
  9782. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  9783. //casting to point light, as light is missing the position attr and typescript complains.
  9784. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  9785. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  9786. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  9787. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  9788. shadowGenerator.getShadowMap().renderList.push(mesh);
  9789. }
  9790. if (parsedShadowGenerator.usePoissonSampling) {
  9791. shadowGenerator.usePoissonSampling = true;
  9792. }
  9793. else if (parsedShadowGenerator.useVarianceShadowMap) {
  9794. shadowGenerator.useVarianceShadowMap = true;
  9795. }
  9796. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  9797. shadowGenerator.useBlurVarianceShadowMap = true;
  9798. if (parsedShadowGenerator.blurScale) {
  9799. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  9800. }
  9801. if (parsedShadowGenerator.blurBoxOffset) {
  9802. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  9803. }
  9804. }
  9805. if (parsedShadowGenerator.bias !== undefined) {
  9806. shadowGenerator.bias = parsedShadowGenerator.bias;
  9807. }
  9808. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  9809. return shadowGenerator;
  9810. };
  9811. ShadowGenerator._FILTER_NONE = 0;
  9812. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  9813. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  9814. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  9815. return ShadowGenerator;
  9816. })();
  9817. BABYLON.ShadowGenerator = ShadowGenerator;
  9818. })(BABYLON || (BABYLON = {}));
  9819. var BABYLON;
  9820. (function (BABYLON) {
  9821. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  9822. if (boxMin.x > sphereCenter.x + sphereRadius)
  9823. return false;
  9824. if (sphereCenter.x - sphereRadius > boxMax.x)
  9825. return false;
  9826. if (boxMin.y > sphereCenter.y + sphereRadius)
  9827. return false;
  9828. if (sphereCenter.y - sphereRadius > boxMax.y)
  9829. return false;
  9830. if (boxMin.z > sphereCenter.z + sphereRadius)
  9831. return false;
  9832. if (sphereCenter.z - sphereRadius > boxMax.z)
  9833. return false;
  9834. return true;
  9835. };
  9836. var getLowestRoot = function (a, b, c, maxR) {
  9837. var determinant = b * b - 4.0 * a * c;
  9838. var result = { root: 0, found: false };
  9839. if (determinant < 0)
  9840. return result;
  9841. var sqrtD = Math.sqrt(determinant);
  9842. var r1 = (-b - sqrtD) / (2.0 * a);
  9843. var r2 = (-b + sqrtD) / (2.0 * a);
  9844. if (r1 > r2) {
  9845. var temp = r2;
  9846. r2 = r1;
  9847. r1 = temp;
  9848. }
  9849. if (r1 > 0 && r1 < maxR) {
  9850. result.root = r1;
  9851. result.found = true;
  9852. return result;
  9853. }
  9854. if (r2 > 0 && r2 < maxR) {
  9855. result.root = r2;
  9856. result.found = true;
  9857. return result;
  9858. }
  9859. return result;
  9860. };
  9861. var Collider = (function () {
  9862. function Collider() {
  9863. this.radius = new BABYLON.Vector3(1, 1, 1);
  9864. this.retry = 0;
  9865. this.basePointWorld = BABYLON.Vector3.Zero();
  9866. this.velocityWorld = BABYLON.Vector3.Zero();
  9867. this.normalizedVelocity = BABYLON.Vector3.Zero();
  9868. this._collisionPoint = BABYLON.Vector3.Zero();
  9869. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  9870. this._tempVector = BABYLON.Vector3.Zero();
  9871. this._tempVector2 = BABYLON.Vector3.Zero();
  9872. this._tempVector3 = BABYLON.Vector3.Zero();
  9873. this._tempVector4 = BABYLON.Vector3.Zero();
  9874. this._edge = BABYLON.Vector3.Zero();
  9875. this._baseToVertex = BABYLON.Vector3.Zero();
  9876. this._destinationPoint = BABYLON.Vector3.Zero();
  9877. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  9878. this._displacementVector = BABYLON.Vector3.Zero();
  9879. }
  9880. // Methods
  9881. Collider.prototype._initialize = function (source, dir, e) {
  9882. this.velocity = dir;
  9883. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  9884. this.basePoint = source;
  9885. source.multiplyToRef(this.radius, this.basePointWorld);
  9886. dir.multiplyToRef(this.radius, this.velocityWorld);
  9887. this.velocityWorldLength = this.velocityWorld.length();
  9888. this.epsilon = e;
  9889. this.collisionFound = false;
  9890. };
  9891. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  9892. pa.subtractToRef(point, this._tempVector);
  9893. pb.subtractToRef(point, this._tempVector2);
  9894. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  9895. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9896. if (d < 0)
  9897. return false;
  9898. pc.subtractToRef(point, this._tempVector3);
  9899. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  9900. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9901. if (d < 0)
  9902. return false;
  9903. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  9904. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9905. return d >= 0;
  9906. };
  9907. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  9908. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  9909. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  9910. if (distance > this.velocityWorldLength + max + sphereRadius) {
  9911. return false;
  9912. }
  9913. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  9914. return false;
  9915. return true;
  9916. };
  9917. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  9918. var t0;
  9919. var embeddedInPlane = false;
  9920. //defensive programming, actually not needed.
  9921. if (!trianglePlaneArray) {
  9922. trianglePlaneArray = [];
  9923. }
  9924. if (!trianglePlaneArray[faceIndex]) {
  9925. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  9926. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  9927. }
  9928. var trianglePlane = trianglePlaneArray[faceIndex];
  9929. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  9930. return;
  9931. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  9932. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  9933. if (normalDotVelocity == 0) {
  9934. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  9935. return;
  9936. embeddedInPlane = true;
  9937. t0 = 0;
  9938. }
  9939. else {
  9940. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9941. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9942. if (t0 > t1) {
  9943. var temp = t1;
  9944. t1 = t0;
  9945. t0 = temp;
  9946. }
  9947. if (t0 > 1.0 || t1 < 0.0)
  9948. return;
  9949. if (t0 < 0)
  9950. t0 = 0;
  9951. if (t0 > 1.0)
  9952. t0 = 1.0;
  9953. }
  9954. this._collisionPoint.copyFromFloats(0, 0, 0);
  9955. var found = false;
  9956. var t = 1.0;
  9957. if (!embeddedInPlane) {
  9958. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  9959. this.velocity.scaleToRef(t0, this._tempVector);
  9960. this._planeIntersectionPoint.addInPlace(this._tempVector);
  9961. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  9962. found = true;
  9963. t = t0;
  9964. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  9965. }
  9966. }
  9967. if (!found) {
  9968. var velocitySquaredLength = this.velocity.lengthSquared();
  9969. var a = velocitySquaredLength;
  9970. this.basePoint.subtractToRef(p1, this._tempVector);
  9971. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9972. var c = this._tempVector.lengthSquared() - 1.0;
  9973. var lowestRoot = getLowestRoot(a, b, c, t);
  9974. if (lowestRoot.found) {
  9975. t = lowestRoot.root;
  9976. found = true;
  9977. this._collisionPoint.copyFrom(p1);
  9978. }
  9979. this.basePoint.subtractToRef(p2, this._tempVector);
  9980. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9981. c = this._tempVector.lengthSquared() - 1.0;
  9982. lowestRoot = getLowestRoot(a, b, c, t);
  9983. if (lowestRoot.found) {
  9984. t = lowestRoot.root;
  9985. found = true;
  9986. this._collisionPoint.copyFrom(p2);
  9987. }
  9988. this.basePoint.subtractToRef(p3, this._tempVector);
  9989. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9990. c = this._tempVector.lengthSquared() - 1.0;
  9991. lowestRoot = getLowestRoot(a, b, c, t);
  9992. if (lowestRoot.found) {
  9993. t = lowestRoot.root;
  9994. found = true;
  9995. this._collisionPoint.copyFrom(p3);
  9996. }
  9997. p2.subtractToRef(p1, this._edge);
  9998. p1.subtractToRef(this.basePoint, this._baseToVertex);
  9999. var edgeSquaredLength = this._edge.lengthSquared();
  10000. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  10001. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  10002. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  10003. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  10004. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  10005. lowestRoot = getLowestRoot(a, b, c, t);
  10006. if (lowestRoot.found) {
  10007. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  10008. if (f >= 0.0 && f <= 1.0) {
  10009. t = lowestRoot.root;
  10010. found = true;
  10011. this._edge.scaleInPlace(f);
  10012. p1.addToRef(this._edge, this._collisionPoint);
  10013. }
  10014. }
  10015. p3.subtractToRef(p2, this._edge);
  10016. p2.subtractToRef(this.basePoint, this._baseToVertex);
  10017. edgeSquaredLength = this._edge.lengthSquared();
  10018. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  10019. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  10020. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  10021. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  10022. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  10023. lowestRoot = getLowestRoot(a, b, c, t);
  10024. if (lowestRoot.found) {
  10025. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  10026. if (f >= 0.0 && f <= 1.0) {
  10027. t = lowestRoot.root;
  10028. found = true;
  10029. this._edge.scaleInPlace(f);
  10030. p2.addToRef(this._edge, this._collisionPoint);
  10031. }
  10032. }
  10033. p1.subtractToRef(p3, this._edge);
  10034. p3.subtractToRef(this.basePoint, this._baseToVertex);
  10035. edgeSquaredLength = this._edge.lengthSquared();
  10036. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  10037. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  10038. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  10039. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  10040. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  10041. lowestRoot = getLowestRoot(a, b, c, t);
  10042. if (lowestRoot.found) {
  10043. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  10044. if (f >= 0.0 && f <= 1.0) {
  10045. t = lowestRoot.root;
  10046. found = true;
  10047. this._edge.scaleInPlace(f);
  10048. p3.addToRef(this._edge, this._collisionPoint);
  10049. }
  10050. }
  10051. }
  10052. if (found) {
  10053. var distToCollision = t * this.velocity.length();
  10054. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  10055. if (!this.intersectionPoint) {
  10056. this.intersectionPoint = this._collisionPoint.clone();
  10057. }
  10058. else {
  10059. this.intersectionPoint.copyFrom(this._collisionPoint);
  10060. }
  10061. this.nearestDistance = distToCollision;
  10062. this.collisionFound = true;
  10063. }
  10064. }
  10065. };
  10066. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  10067. for (var i = indexStart; i < indexEnd; i += 3) {
  10068. var p1 = pts[indices[i] - decal];
  10069. var p2 = pts[indices[i + 1] - decal];
  10070. var p3 = pts[indices[i + 2] - decal];
  10071. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  10072. }
  10073. };
  10074. Collider.prototype._getResponse = function (pos, vel) {
  10075. pos.addToRef(vel, this._destinationPoint);
  10076. vel.scaleInPlace((this.nearestDistance / vel.length()));
  10077. this.basePoint.addToRef(vel, pos);
  10078. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  10079. this._slidePlaneNormal.normalize();
  10080. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  10081. pos.addInPlace(this._displacementVector);
  10082. this.intersectionPoint.addInPlace(this._displacementVector);
  10083. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  10084. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  10085. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  10086. };
  10087. return Collider;
  10088. })();
  10089. BABYLON.Collider = Collider;
  10090. })(BABYLON || (BABYLON = {}));
  10091. var BABYLON;
  10092. (function (BABYLON) {
  10093. //WebWorker code will be inserted to this variable.
  10094. BABYLON.CollisionWorker = "";
  10095. (function (WorkerTaskType) {
  10096. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  10097. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  10098. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  10099. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  10100. var WorkerTaskType = BABYLON.WorkerTaskType;
  10101. (function (WorkerReplyType) {
  10102. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  10103. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  10104. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  10105. var WorkerReplyType = BABYLON.WorkerReplyType;
  10106. var CollisionCoordinatorWorker = (function () {
  10107. function CollisionCoordinatorWorker() {
  10108. var _this = this;
  10109. this._scaledPosition = BABYLON.Vector3.Zero();
  10110. this._scaledVelocity = BABYLON.Vector3.Zero();
  10111. this.onMeshUpdated = function (mesh) {
  10112. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  10113. };
  10114. this.onGeometryUpdated = function (geometry) {
  10115. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  10116. };
  10117. this._afterRender = function () {
  10118. if (!_this._init)
  10119. return;
  10120. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  10121. return;
  10122. }
  10123. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  10124. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  10125. if (_this._runningUpdated > 4) {
  10126. return;
  10127. }
  10128. ++_this._runningUpdated;
  10129. var payload = {
  10130. updatedMeshes: _this._addUpdateMeshesList,
  10131. updatedGeometries: _this._addUpdateGeometriesList,
  10132. removedGeometries: _this._toRemoveGeometryArray,
  10133. removedMeshes: _this._toRemoveMeshesArray
  10134. };
  10135. var message = {
  10136. payload: payload,
  10137. taskType: WorkerTaskType.UPDATE
  10138. };
  10139. var serializable = [];
  10140. for (var id in payload.updatedGeometries) {
  10141. if (payload.updatedGeometries.hasOwnProperty(id)) {
  10142. //prepare transferables
  10143. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  10144. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  10145. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  10146. }
  10147. }
  10148. _this._worker.postMessage(message, serializable);
  10149. _this._addUpdateMeshesList = {};
  10150. _this._addUpdateGeometriesList = {};
  10151. _this._toRemoveGeometryArray = [];
  10152. _this._toRemoveMeshesArray = [];
  10153. };
  10154. this._onMessageFromWorker = function (e) {
  10155. var returnData = e.data;
  10156. if (returnData.error != WorkerReplyType.SUCCESS) {
  10157. //TODO what errors can be returned from the worker?
  10158. BABYLON.Tools.Warn("error returned from worker!");
  10159. return;
  10160. }
  10161. switch (returnData.taskType) {
  10162. case WorkerTaskType.INIT:
  10163. _this._init = true;
  10164. //Update the worked with ALL of the scene's current state
  10165. _this._scene.meshes.forEach(function (mesh) {
  10166. _this.onMeshAdded(mesh);
  10167. });
  10168. _this._scene.getGeometries().forEach(function (geometry) {
  10169. _this.onGeometryAdded(geometry);
  10170. });
  10171. break;
  10172. case WorkerTaskType.UPDATE:
  10173. _this._runningUpdated--;
  10174. break;
  10175. case WorkerTaskType.COLLIDE:
  10176. _this._runningCollisionTask = false;
  10177. var returnPayload = returnData.payload;
  10178. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  10179. return;
  10180. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  10181. //cleanup
  10182. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  10183. break;
  10184. }
  10185. };
  10186. this._collisionsCallbackArray = [];
  10187. this._init = false;
  10188. this._runningUpdated = 0;
  10189. this._runningCollisionTask = false;
  10190. this._addUpdateMeshesList = {};
  10191. this._addUpdateGeometriesList = {};
  10192. this._toRemoveGeometryArray = [];
  10193. this._toRemoveMeshesArray = [];
  10194. }
  10195. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  10196. if (!this._init)
  10197. return;
  10198. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  10199. return;
  10200. position.divideToRef(collider.radius, this._scaledPosition);
  10201. velocity.divideToRef(collider.radius, this._scaledVelocity);
  10202. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  10203. var payload = {
  10204. collider: {
  10205. position: this._scaledPosition.asArray(),
  10206. velocity: this._scaledVelocity.asArray(),
  10207. radius: collider.radius.asArray()
  10208. },
  10209. collisionId: collisionIndex,
  10210. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  10211. maximumRetry: maximumRetry
  10212. };
  10213. var message = {
  10214. payload: payload,
  10215. taskType: WorkerTaskType.COLLIDE
  10216. };
  10217. this._worker.postMessage(message);
  10218. };
  10219. CollisionCoordinatorWorker.prototype.init = function (scene) {
  10220. this._scene = scene;
  10221. this._scene.registerAfterRender(this._afterRender);
  10222. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  10223. this._worker = new Worker(workerUrl);
  10224. this._worker.onmessage = this._onMessageFromWorker;
  10225. var message = {
  10226. payload: {},
  10227. taskType: WorkerTaskType.INIT
  10228. };
  10229. this._worker.postMessage(message);
  10230. };
  10231. CollisionCoordinatorWorker.prototype.destroy = function () {
  10232. this._scene.unregisterAfterRender(this._afterRender);
  10233. this._worker.terminate();
  10234. };
  10235. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  10236. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  10237. this.onMeshUpdated(mesh);
  10238. };
  10239. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  10240. this._toRemoveMeshesArray.push(mesh.uniqueId);
  10241. };
  10242. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  10243. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  10244. geometry.onGeometryUpdated = this.onGeometryUpdated;
  10245. this.onGeometryUpdated(geometry);
  10246. };
  10247. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  10248. this._toRemoveGeometryArray.push(geometry.id);
  10249. };
  10250. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  10251. var submeshes = [];
  10252. if (mesh.subMeshes) {
  10253. submeshes = mesh.subMeshes.map(function (sm, idx) {
  10254. return {
  10255. position: idx,
  10256. verticesStart: sm.verticesStart,
  10257. verticesCount: sm.verticesCount,
  10258. indexStart: sm.indexStart,
  10259. indexCount: sm.indexCount,
  10260. hasMaterial: !!sm.getMaterial(),
  10261. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  10262. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  10263. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  10264. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  10265. };
  10266. });
  10267. }
  10268. var geometryId = null;
  10269. if (mesh instanceof BABYLON.Mesh) {
  10270. geometryId = mesh.geometry ? mesh.geometry.id : null;
  10271. }
  10272. else if (mesh instanceof BABYLON.InstancedMesh) {
  10273. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  10274. }
  10275. return {
  10276. uniqueId: mesh.uniqueId,
  10277. id: mesh.id,
  10278. name: mesh.name,
  10279. geometryId: geometryId,
  10280. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  10281. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  10282. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  10283. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  10284. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  10285. subMeshes: submeshes,
  10286. checkCollisions: mesh.checkCollisions
  10287. };
  10288. };
  10289. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  10290. return {
  10291. id: geometry.id,
  10292. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  10293. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  10294. indices: new Int32Array(geometry.getIndices() || []),
  10295. };
  10296. };
  10297. return CollisionCoordinatorWorker;
  10298. })();
  10299. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  10300. var CollisionCoordinatorLegacy = (function () {
  10301. function CollisionCoordinatorLegacy() {
  10302. this._scaledPosition = BABYLON.Vector3.Zero();
  10303. this._scaledVelocity = BABYLON.Vector3.Zero();
  10304. this._finalPosition = BABYLON.Vector3.Zero();
  10305. }
  10306. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  10307. position.divideToRef(collider.radius, this._scaledPosition);
  10308. velocity.divideToRef(collider.radius, this._scaledVelocity);
  10309. collider.collidedMesh = null;
  10310. collider.retry = 0;
  10311. collider.initialVelocity = this._scaledVelocity;
  10312. collider.initialPosition = this._scaledPosition;
  10313. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  10314. this._finalPosition.multiplyInPlace(collider.radius);
  10315. //run the callback
  10316. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  10317. };
  10318. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  10319. this._scene = scene;
  10320. };
  10321. CollisionCoordinatorLegacy.prototype.destroy = function () {
  10322. //Legacy need no destruction method.
  10323. };
  10324. //No update in legacy mode
  10325. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  10326. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  10327. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  10328. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  10329. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  10330. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  10331. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  10332. if (excludedMesh === void 0) { excludedMesh = null; }
  10333. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  10334. if (collider.retry >= maximumRetry) {
  10335. finalPosition.copyFrom(position);
  10336. return;
  10337. }
  10338. collider._initialize(position, velocity, closeDistance);
  10339. // Check all meshes
  10340. for (var index = 0; index < this._scene.meshes.length; index++) {
  10341. var mesh = this._scene.meshes[index];
  10342. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  10343. mesh._checkCollision(collider);
  10344. }
  10345. }
  10346. if (!collider.collisionFound) {
  10347. position.addToRef(velocity, finalPosition);
  10348. return;
  10349. }
  10350. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  10351. collider._getResponse(position, velocity);
  10352. }
  10353. if (velocity.length() <= closeDistance) {
  10354. finalPosition.copyFrom(position);
  10355. return;
  10356. }
  10357. collider.retry++;
  10358. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  10359. };
  10360. return CollisionCoordinatorLegacy;
  10361. })();
  10362. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  10363. })(BABYLON || (BABYLON = {}));
  10364. var BABYLON;
  10365. (function (BABYLON) {
  10366. var Camera = (function (_super) {
  10367. __extends(Camera, _super);
  10368. function Camera(name, position, scene) {
  10369. _super.call(this, name, scene);
  10370. this.upVector = BABYLON.Vector3.Up();
  10371. this.orthoLeft = null;
  10372. this.orthoRight = null;
  10373. this.orthoBottom = null;
  10374. this.orthoTop = null;
  10375. this.fov = 0.8;
  10376. this.minZ = 1.0;
  10377. this.maxZ = 10000.0;
  10378. this.inertia = 0.9;
  10379. this.mode = Camera.PERSPECTIVE_CAMERA;
  10380. this.isIntermediate = false;
  10381. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  10382. this.layerMask = 0x0FFFFFFF;
  10383. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  10384. // Camera rig members
  10385. this.cameraRigMode = Camera.RIG_MODE_NONE;
  10386. this._rigCameras = new Array();
  10387. // Cache
  10388. this._computedViewMatrix = BABYLON.Matrix.Identity();
  10389. this._projectionMatrix = new BABYLON.Matrix();
  10390. this._postProcesses = new Array();
  10391. this._postProcessesTakenIndices = [];
  10392. this._activeMeshes = new BABYLON.SmartArray(256);
  10393. this._globalPosition = BABYLON.Vector3.Zero();
  10394. scene.addCamera(this);
  10395. if (!scene.activeCamera) {
  10396. scene.activeCamera = this;
  10397. }
  10398. this.position = position;
  10399. }
  10400. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  10401. get: function () {
  10402. return Camera._PERSPECTIVE_CAMERA;
  10403. },
  10404. enumerable: true,
  10405. configurable: true
  10406. });
  10407. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  10408. get: function () {
  10409. return Camera._ORTHOGRAPHIC_CAMERA;
  10410. },
  10411. enumerable: true,
  10412. configurable: true
  10413. });
  10414. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  10415. get: function () {
  10416. return Camera._FOVMODE_VERTICAL_FIXED;
  10417. },
  10418. enumerable: true,
  10419. configurable: true
  10420. });
  10421. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  10422. get: function () {
  10423. return Camera._FOVMODE_HORIZONTAL_FIXED;
  10424. },
  10425. enumerable: true,
  10426. configurable: true
  10427. });
  10428. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  10429. get: function () {
  10430. return Camera._RIG_MODE_NONE;
  10431. },
  10432. enumerable: true,
  10433. configurable: true
  10434. });
  10435. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  10436. get: function () {
  10437. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  10438. },
  10439. enumerable: true,
  10440. configurable: true
  10441. });
  10442. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  10443. get: function () {
  10444. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  10445. },
  10446. enumerable: true,
  10447. configurable: true
  10448. });
  10449. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  10450. get: function () {
  10451. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  10452. },
  10453. enumerable: true,
  10454. configurable: true
  10455. });
  10456. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  10457. get: function () {
  10458. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  10459. },
  10460. enumerable: true,
  10461. configurable: true
  10462. });
  10463. Object.defineProperty(Camera, "RIG_MODE_VR", {
  10464. get: function () {
  10465. return Camera._RIG_MODE_VR;
  10466. },
  10467. enumerable: true,
  10468. configurable: true
  10469. });
  10470. Object.defineProperty(Camera.prototype, "globalPosition", {
  10471. get: function () {
  10472. return this._globalPosition;
  10473. },
  10474. enumerable: true,
  10475. configurable: true
  10476. });
  10477. Camera.prototype.getActiveMeshes = function () {
  10478. return this._activeMeshes;
  10479. };
  10480. Camera.prototype.isActiveMesh = function (mesh) {
  10481. return (this._activeMeshes.indexOf(mesh) !== -1);
  10482. };
  10483. //Cache
  10484. Camera.prototype._initCache = function () {
  10485. _super.prototype._initCache.call(this);
  10486. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10487. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10488. this._cache.mode = undefined;
  10489. this._cache.minZ = undefined;
  10490. this._cache.maxZ = undefined;
  10491. this._cache.fov = undefined;
  10492. this._cache.aspectRatio = undefined;
  10493. this._cache.orthoLeft = undefined;
  10494. this._cache.orthoRight = undefined;
  10495. this._cache.orthoBottom = undefined;
  10496. this._cache.orthoTop = undefined;
  10497. this._cache.renderWidth = undefined;
  10498. this._cache.renderHeight = undefined;
  10499. };
  10500. Camera.prototype._updateCache = function (ignoreParentClass) {
  10501. if (!ignoreParentClass) {
  10502. _super.prototype._updateCache.call(this);
  10503. }
  10504. var engine = this.getEngine();
  10505. this._cache.position.copyFrom(this.position);
  10506. this._cache.upVector.copyFrom(this.upVector);
  10507. this._cache.mode = this.mode;
  10508. this._cache.minZ = this.minZ;
  10509. this._cache.maxZ = this.maxZ;
  10510. this._cache.fov = this.fov;
  10511. this._cache.aspectRatio = engine.getAspectRatio(this);
  10512. this._cache.orthoLeft = this.orthoLeft;
  10513. this._cache.orthoRight = this.orthoRight;
  10514. this._cache.orthoBottom = this.orthoBottom;
  10515. this._cache.orthoTop = this.orthoTop;
  10516. this._cache.renderWidth = engine.getRenderWidth();
  10517. this._cache.renderHeight = engine.getRenderHeight();
  10518. };
  10519. Camera.prototype._updateFromScene = function () {
  10520. this.updateCache();
  10521. this._update();
  10522. };
  10523. // Synchronized
  10524. Camera.prototype._isSynchronized = function () {
  10525. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  10526. };
  10527. Camera.prototype._isSynchronizedViewMatrix = function () {
  10528. if (!_super.prototype._isSynchronized.call(this))
  10529. return false;
  10530. return this._cache.position.equals(this.position)
  10531. && this._cache.upVector.equals(this.upVector)
  10532. && this.isSynchronizedWithParent();
  10533. };
  10534. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  10535. var check = this._cache.mode === this.mode
  10536. && this._cache.minZ === this.minZ
  10537. && this._cache.maxZ === this.maxZ;
  10538. if (!check) {
  10539. return false;
  10540. }
  10541. var engine = this.getEngine();
  10542. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  10543. check = this._cache.fov === this.fov
  10544. && this._cache.aspectRatio === engine.getAspectRatio(this);
  10545. }
  10546. else {
  10547. check = this._cache.orthoLeft === this.orthoLeft
  10548. && this._cache.orthoRight === this.orthoRight
  10549. && this._cache.orthoBottom === this.orthoBottom
  10550. && this._cache.orthoTop === this.orthoTop
  10551. && this._cache.renderWidth === engine.getRenderWidth()
  10552. && this._cache.renderHeight === engine.getRenderHeight();
  10553. }
  10554. return check;
  10555. };
  10556. // Controls
  10557. Camera.prototype.attachControl = function (element, noPreventDefault) {
  10558. };
  10559. Camera.prototype.detachControl = function (element) {
  10560. };
  10561. Camera.prototype._update = function () {
  10562. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  10563. this._updateRigCameras();
  10564. }
  10565. this._checkInputs();
  10566. };
  10567. Camera.prototype._checkInputs = function () {
  10568. };
  10569. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  10570. if (insertAt === void 0) { insertAt = null; }
  10571. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  10572. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  10573. return 0;
  10574. }
  10575. if (insertAt == null || insertAt < 0) {
  10576. this._postProcesses.push(postProcess);
  10577. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  10578. return this._postProcesses.length - 1;
  10579. }
  10580. var add = 0;
  10581. var i;
  10582. var start;
  10583. if (this._postProcesses[insertAt]) {
  10584. start = this._postProcesses.length - 1;
  10585. for (i = start; i >= insertAt + 1; --i) {
  10586. this._postProcesses[i + 1] = this._postProcesses[i];
  10587. }
  10588. add = 1;
  10589. }
  10590. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  10591. if (this._postProcessesTakenIndices[i] < insertAt) {
  10592. continue;
  10593. }
  10594. start = this._postProcessesTakenIndices.length - 1;
  10595. for (var j = start; j >= i; --j) {
  10596. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  10597. }
  10598. this._postProcessesTakenIndices[i] = insertAt;
  10599. break;
  10600. }
  10601. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) === -1) {
  10602. this._postProcessesTakenIndices.push(insertAt);
  10603. }
  10604. var result = insertAt + add;
  10605. this._postProcesses[result] = postProcess;
  10606. return result;
  10607. };
  10608. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  10609. if (atIndices === void 0) { atIndices = null; }
  10610. var result = [];
  10611. var i;
  10612. var index;
  10613. if (!atIndices) {
  10614. var length = this._postProcesses.length;
  10615. for (i = 0; i < length; i++) {
  10616. if (this._postProcesses[i] !== postProcess) {
  10617. continue;
  10618. }
  10619. delete this._postProcesses[i];
  10620. index = this._postProcessesTakenIndices.indexOf(i);
  10621. this._postProcessesTakenIndices.splice(index, 1);
  10622. }
  10623. }
  10624. else {
  10625. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  10626. for (i = 0; i < atIndices.length; i++) {
  10627. var foundPostProcess = this._postProcesses[atIndices[i]];
  10628. if (foundPostProcess !== postProcess) {
  10629. result.push(i);
  10630. continue;
  10631. }
  10632. delete this._postProcesses[atIndices[i]];
  10633. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  10634. this._postProcessesTakenIndices.splice(index, 1);
  10635. }
  10636. }
  10637. return result;
  10638. };
  10639. Camera.prototype.getWorldMatrix = function () {
  10640. if (!this._worldMatrix) {
  10641. this._worldMatrix = BABYLON.Matrix.Identity();
  10642. }
  10643. var viewMatrix = this.getViewMatrix();
  10644. viewMatrix.invertToRef(this._worldMatrix);
  10645. return this._worldMatrix;
  10646. };
  10647. Camera.prototype._getViewMatrix = function () {
  10648. return BABYLON.Matrix.Identity();
  10649. };
  10650. Camera.prototype.getViewMatrix = function (force) {
  10651. this._computedViewMatrix = this._computeViewMatrix(force);
  10652. if (!force && this._isSynchronizedViewMatrix()) {
  10653. return this._computedViewMatrix;
  10654. }
  10655. if (!this.parent || !this.parent.getWorldMatrix) {
  10656. this._globalPosition.copyFrom(this.position);
  10657. }
  10658. else {
  10659. if (!this._worldMatrix) {
  10660. this._worldMatrix = BABYLON.Matrix.Identity();
  10661. }
  10662. this._computedViewMatrix.invertToRef(this._worldMatrix);
  10663. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  10664. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  10665. this._computedViewMatrix.invert();
  10666. this._markSyncedWithParent();
  10667. }
  10668. this._currentRenderId = this.getScene().getRenderId();
  10669. return this._computedViewMatrix;
  10670. };
  10671. Camera.prototype._computeViewMatrix = function (force) {
  10672. if (!force && this._isSynchronizedViewMatrix()) {
  10673. return this._computedViewMatrix;
  10674. }
  10675. this._computedViewMatrix = this._getViewMatrix();
  10676. this._currentRenderId = this.getScene().getRenderId();
  10677. return this._computedViewMatrix;
  10678. };
  10679. Camera.prototype.getProjectionMatrix = function (force) {
  10680. if (!force && this._isSynchronizedProjectionMatrix()) {
  10681. return this._projectionMatrix;
  10682. }
  10683. var engine = this.getEngine();
  10684. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  10685. if (this.minZ <= 0) {
  10686. this.minZ = 0.1;
  10687. }
  10688. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  10689. return this._projectionMatrix;
  10690. }
  10691. var halfWidth = engine.getRenderWidth() / 2.0;
  10692. var halfHeight = engine.getRenderHeight() / 2.0;
  10693. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  10694. return this._projectionMatrix;
  10695. };
  10696. Camera.prototype.dispose = function () {
  10697. // Animations
  10698. this.getScene().stopAnimation(this);
  10699. // Remove from scene
  10700. this.getScene().removeCamera(this);
  10701. while (this._rigCameras.length > 0) {
  10702. this._rigCameras.pop().dispose();
  10703. }
  10704. // Postprocesses
  10705. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  10706. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  10707. }
  10708. };
  10709. // ---- Camera rigs section ----
  10710. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  10711. while (this._rigCameras.length > 0) {
  10712. this._rigCameras.pop().dispose();
  10713. }
  10714. this.cameraRigMode = mode;
  10715. this._cameraRigParams = {};
  10716. switch (this.cameraRigMode) {
  10717. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10718. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10719. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10720. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10721. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  10722. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  10723. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  10724. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  10725. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10726. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10727. break;
  10728. }
  10729. var postProcesses = new Array();
  10730. switch (this.cameraRigMode) {
  10731. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10732. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]));
  10733. this._rigCameras[0].isIntermediate = true;
  10734. postProcesses.push(new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras[1]));
  10735. postProcesses[1].onApply = function (effect) {
  10736. effect.setTextureFromPostProcess("leftSampler", postProcesses[0]);
  10737. };
  10738. break;
  10739. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10740. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10741. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10742. var isStereoscopicHoriz = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED);
  10743. var firstCamIndex = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : 0;
  10744. var secondCamIndex = 1 - firstCamIndex;
  10745. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[firstCamIndex]));
  10746. this._rigCameras[firstCamIndex].isIntermediate = true;
  10747. postProcesses.push(new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras[secondCamIndex], postProcesses[0], isStereoscopicHoriz));
  10748. break;
  10749. case Camera.RIG_MODE_VR:
  10750. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10751. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10752. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  10753. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  10754. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  10755. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10756. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  10757. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  10758. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  10759. if (metrics.compensateDistortion) {
  10760. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics));
  10761. }
  10762. this._rigCameras[1]._cameraRigParams.vrMetrics = this._rigCameras[0]._cameraRigParams.vrMetrics;
  10763. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  10764. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10765. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  10766. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  10767. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  10768. if (metrics.compensateDistortion) {
  10769. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics));
  10770. }
  10771. break;
  10772. }
  10773. this._update();
  10774. };
  10775. Camera.prototype._getVRProjectionMatrix = function () {
  10776. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  10777. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  10778. return this._projectionMatrix;
  10779. };
  10780. Camera.prototype.setCameraRigParameter = function (name, value) {
  10781. this._cameraRigParams[name] = value;
  10782. //provisionnally:
  10783. if (name === "interaxialDistance") {
  10784. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  10785. }
  10786. };
  10787. /**
  10788. * May needs to be overridden by children so sub has required properties to be copied
  10789. */
  10790. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  10791. return null;
  10792. };
  10793. /**
  10794. * May needs to be overridden by children
  10795. */
  10796. Camera.prototype._updateRigCameras = function () {
  10797. for (var i = 0; i < this._rigCameras.length; i++) {
  10798. this._rigCameras[i].minZ = this.minZ;
  10799. this._rigCameras[i].maxZ = this.maxZ;
  10800. this._rigCameras[i].fov = this.fov;
  10801. }
  10802. // only update viewport when ANAGLYPH
  10803. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  10804. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  10805. }
  10806. };
  10807. Camera.prototype.serialize = function () {
  10808. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  10809. // Type
  10810. serializationObject.type = this.getTypeName();
  10811. // Parent
  10812. if (this.parent) {
  10813. serializationObject.parentId = this.parent.id;
  10814. }
  10815. // Animations
  10816. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  10817. serializationObject.ranges = this.serializeAnimationRanges();
  10818. return serializationObject;
  10819. };
  10820. Camera.prototype.getTypeName = function () {
  10821. return "Camera";
  10822. };
  10823. Camera.prototype.clone = function (name) {
  10824. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getTypeName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  10825. };
  10826. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  10827. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  10828. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  10829. switch (type) {
  10830. case "ArcRotateCamera":
  10831. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  10832. case "DeviceOrientationCamera":
  10833. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  10834. case "FollowCamera":
  10835. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  10836. case "ArcFollowCamera":
  10837. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  10838. case "GamepadCamera":
  10839. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  10840. case "TouchCamera":
  10841. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  10842. case "VirtualJoysticksCamera":
  10843. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  10844. case "WebVRFreeCamera":
  10845. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  10846. case "VRDeviceOrientationFreeCamera":
  10847. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  10848. case "AnaglyphArcRotateCamera":
  10849. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  10850. case "AnaglyphFreeCamera":
  10851. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  10852. case "AnaglyphGamepadCamera":
  10853. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  10854. case "AnaglyphUniversalCamera":
  10855. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  10856. case "StereoscopicArcRotateCamera":
  10857. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  10858. case "StereoscopicFreeCamera":
  10859. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  10860. case "StereoscopicGamepadCamera":
  10861. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  10862. case "StereoscopicUniversalCamera":
  10863. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  10864. case "FreeCamera":
  10865. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  10866. default:
  10867. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  10868. }
  10869. };
  10870. Camera.Parse = function (parsedCamera, scene) {
  10871. var type = parsedCamera.type;
  10872. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  10873. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  10874. // Parent
  10875. if (parsedCamera.parentId) {
  10876. camera._waitingParentId = parsedCamera.parentId;
  10877. }
  10878. // Target
  10879. if (parsedCamera.target) {
  10880. if (camera.setTarget) {
  10881. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  10882. }
  10883. }
  10884. // Apply 3d rig, when found
  10885. if (parsedCamera.cameraRigMode) {
  10886. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  10887. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  10888. }
  10889. // Animations
  10890. if (parsedCamera.animations) {
  10891. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  10892. var parsedAnimation = parsedCamera.animations[animationIndex];
  10893. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  10894. }
  10895. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  10896. }
  10897. if (parsedCamera.autoAnimate) {
  10898. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  10899. }
  10900. return camera;
  10901. };
  10902. // Statics
  10903. Camera._PERSPECTIVE_CAMERA = 0;
  10904. Camera._ORTHOGRAPHIC_CAMERA = 1;
  10905. Camera._FOVMODE_VERTICAL_FIXED = 0;
  10906. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  10907. Camera._RIG_MODE_NONE = 0;
  10908. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  10909. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  10910. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  10911. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  10912. Camera._RIG_MODE_VR = 20;
  10913. __decorate([
  10914. BABYLON.serializeAsVector3()
  10915. ], Camera.prototype, "position", void 0);
  10916. __decorate([
  10917. BABYLON.serialize()
  10918. ], Camera.prototype, "upVector", void 0);
  10919. __decorate([
  10920. BABYLON.serialize()
  10921. ], Camera.prototype, "orthoLeft", void 0);
  10922. __decorate([
  10923. BABYLON.serialize()
  10924. ], Camera.prototype, "orthoRight", void 0);
  10925. __decorate([
  10926. BABYLON.serialize()
  10927. ], Camera.prototype, "orthoBottom", void 0);
  10928. __decorate([
  10929. BABYLON.serialize()
  10930. ], Camera.prototype, "orthoTop", void 0);
  10931. __decorate([
  10932. BABYLON.serialize()
  10933. ], Camera.prototype, "fov", void 0);
  10934. __decorate([
  10935. BABYLON.serialize()
  10936. ], Camera.prototype, "minZ", void 0);
  10937. __decorate([
  10938. BABYLON.serialize()
  10939. ], Camera.prototype, "maxZ", void 0);
  10940. __decorate([
  10941. BABYLON.serialize()
  10942. ], Camera.prototype, "inertia", void 0);
  10943. __decorate([
  10944. BABYLON.serialize()
  10945. ], Camera.prototype, "mode", void 0);
  10946. __decorate([
  10947. BABYLON.serialize()
  10948. ], Camera.prototype, "layerMask", void 0);
  10949. __decorate([
  10950. BABYLON.serialize()
  10951. ], Camera.prototype, "fovMode", void 0);
  10952. __decorate([
  10953. BABYLON.serialize()
  10954. ], Camera.prototype, "cameraRigMode", void 0);
  10955. __decorate([
  10956. BABYLON.serialize()
  10957. ], Camera.prototype, "interaxialDistance", void 0);
  10958. __decorate([
  10959. BABYLON.serialize()
  10960. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  10961. return Camera;
  10962. })(BABYLON.Node);
  10963. BABYLON.Camera = Camera;
  10964. })(BABYLON || (BABYLON = {}));
  10965. var BABYLON;
  10966. (function (BABYLON) {
  10967. var TargetCamera = (function (_super) {
  10968. __extends(TargetCamera, _super);
  10969. function TargetCamera(name, position, scene) {
  10970. _super.call(this, name, position, scene);
  10971. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10972. this.cameraRotation = new BABYLON.Vector2(0, 0);
  10973. this.rotation = new BABYLON.Vector3(0, 0, 0);
  10974. this.speed = 2.0;
  10975. this.noRotationConstraint = false;
  10976. this.lockedTarget = null;
  10977. this._currentTarget = BABYLON.Vector3.Zero();
  10978. this._viewMatrix = BABYLON.Matrix.Zero();
  10979. this._camMatrix = BABYLON.Matrix.Zero();
  10980. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  10981. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  10982. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  10983. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  10984. this._lookAtTemp = BABYLON.Matrix.Zero();
  10985. this._tempMatrix = BABYLON.Matrix.Zero();
  10986. }
  10987. TargetCamera.prototype.getFrontPosition = function (distance) {
  10988. var direction = this.getTarget().subtract(this.position);
  10989. direction.normalize();
  10990. direction.scaleInPlace(distance);
  10991. return this.globalPosition.add(direction);
  10992. };
  10993. TargetCamera.prototype._getLockedTargetPosition = function () {
  10994. if (!this.lockedTarget) {
  10995. return null;
  10996. }
  10997. return this.lockedTarget.position || this.lockedTarget;
  10998. };
  10999. // Cache
  11000. TargetCamera.prototype._initCache = function () {
  11001. _super.prototype._initCache.call(this);
  11002. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  11003. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  11004. };
  11005. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  11006. if (!ignoreParentClass) {
  11007. _super.prototype._updateCache.call(this);
  11008. }
  11009. var lockedTargetPosition = this._getLockedTargetPosition();
  11010. if (!lockedTargetPosition) {
  11011. this._cache.lockedTarget = null;
  11012. }
  11013. else {
  11014. if (!this._cache.lockedTarget) {
  11015. this._cache.lockedTarget = lockedTargetPosition.clone();
  11016. }
  11017. else {
  11018. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  11019. }
  11020. }
  11021. this._cache.rotation.copyFrom(this.rotation);
  11022. };
  11023. // Synchronized
  11024. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  11025. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  11026. return false;
  11027. }
  11028. var lockedTargetPosition = this._getLockedTargetPosition();
  11029. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  11030. && this._cache.rotation.equals(this.rotation);
  11031. };
  11032. // Methods
  11033. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  11034. var engine = this.getEngine();
  11035. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  11036. };
  11037. // Target
  11038. TargetCamera.prototype.setTarget = function (target) {
  11039. this.upVector.normalize();
  11040. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  11041. this._camMatrix.invert();
  11042. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  11043. var vDir = target.subtract(this.position);
  11044. if (vDir.x >= 0.0) {
  11045. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  11046. }
  11047. else {
  11048. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  11049. }
  11050. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  11051. if (isNaN(this.rotation.x)) {
  11052. this.rotation.x = 0;
  11053. }
  11054. if (isNaN(this.rotation.y)) {
  11055. this.rotation.y = 0;
  11056. }
  11057. if (isNaN(this.rotation.z)) {
  11058. this.rotation.z = 0;
  11059. }
  11060. };
  11061. TargetCamera.prototype.getTarget = function () {
  11062. return this._currentTarget;
  11063. };
  11064. TargetCamera.prototype._decideIfNeedsToMove = function () {
  11065. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  11066. };
  11067. TargetCamera.prototype._updatePosition = function () {
  11068. this.position.addInPlace(this.cameraDirection);
  11069. };
  11070. TargetCamera.prototype._checkInputs = function () {
  11071. var needToMove = this._decideIfNeedsToMove();
  11072. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  11073. // Move
  11074. if (needToMove) {
  11075. this._updatePosition();
  11076. }
  11077. // Rotate
  11078. if (needToRotate) {
  11079. this.rotation.x += this.cameraRotation.x;
  11080. this.rotation.y += this.cameraRotation.y;
  11081. if (!this.noRotationConstraint) {
  11082. var limit = (Math.PI / 2) * 0.95;
  11083. if (this.rotation.x > limit)
  11084. this.rotation.x = limit;
  11085. if (this.rotation.x < -limit)
  11086. this.rotation.x = -limit;
  11087. }
  11088. }
  11089. // Inertia
  11090. if (needToMove) {
  11091. if (Math.abs(this.cameraDirection.x) < BABYLON.Epsilon) {
  11092. this.cameraDirection.x = 0;
  11093. }
  11094. if (Math.abs(this.cameraDirection.y) < BABYLON.Epsilon) {
  11095. this.cameraDirection.y = 0;
  11096. }
  11097. if (Math.abs(this.cameraDirection.z) < BABYLON.Epsilon) {
  11098. this.cameraDirection.z = 0;
  11099. }
  11100. this.cameraDirection.scaleInPlace(this.inertia);
  11101. }
  11102. if (needToRotate) {
  11103. if (Math.abs(this.cameraRotation.x) < BABYLON.Epsilon) {
  11104. this.cameraRotation.x = 0;
  11105. }
  11106. if (Math.abs(this.cameraRotation.y) < BABYLON.Epsilon) {
  11107. this.cameraRotation.y = 0;
  11108. }
  11109. this.cameraRotation.scaleInPlace(this.inertia);
  11110. }
  11111. _super.prototype._checkInputs.call(this);
  11112. };
  11113. TargetCamera.prototype._getViewMatrix = function () {
  11114. if (!this.lockedTarget) {
  11115. // Compute
  11116. if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
  11117. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  11118. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  11119. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  11120. this._lookAtTemp.invert();
  11121. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  11122. }
  11123. else {
  11124. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  11125. }
  11126. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  11127. // Computing target and final matrix
  11128. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  11129. }
  11130. else {
  11131. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  11132. }
  11133. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  11134. return this._viewMatrix;
  11135. };
  11136. TargetCamera.prototype._getVRViewMatrix = function () {
  11137. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  11138. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  11139. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._cameraRigParams.vrActualUp);
  11140. // Computing target and final matrix
  11141. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  11142. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._cameraRigParams.vrActualUp, this._cameraRigParams.vrWorkMatrix);
  11143. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._viewMatrix);
  11144. return this._viewMatrix;
  11145. };
  11146. /**
  11147. * @override
  11148. * Override Camera.createRigCamera
  11149. */
  11150. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  11151. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  11152. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  11153. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  11154. rigCamera._cameraRigParams = {};
  11155. rigCamera._cameraRigParams.vrActualUp = new BABYLON.Vector3(0, 0, 0);
  11156. rigCamera._getViewMatrix = rigCamera._getVRViewMatrix;
  11157. }
  11158. return rigCamera;
  11159. }
  11160. return null;
  11161. };
  11162. /**
  11163. * @override
  11164. * Override Camera._updateRigCameras
  11165. */
  11166. TargetCamera.prototype._updateRigCameras = function () {
  11167. switch (this.cameraRigMode) {
  11168. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11169. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11170. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11171. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11172. case BABYLON.Camera.RIG_MODE_VR:
  11173. var camLeft = this._rigCameras[0];
  11174. var camRight = this._rigCameras[1];
  11175. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  11176. camLeft.rotation.x = camRight.rotation.x = this.rotation.x;
  11177. camLeft.rotation.y = camRight.rotation.y = this.rotation.y;
  11178. camLeft.rotation.z = camRight.rotation.z = this.rotation.z;
  11179. camLeft.position.copyFrom(this.position);
  11180. camRight.position.copyFrom(this.position);
  11181. }
  11182. else {
  11183. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  11184. this._getRigCamPosition(-this._cameraRigParams.stereoHalfAngle, camLeft.position);
  11185. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle, camRight.position);
  11186. camLeft.setTarget(this.getTarget());
  11187. camRight.setTarget(this.getTarget());
  11188. }
  11189. break;
  11190. }
  11191. _super.prototype._updateRigCameras.call(this);
  11192. };
  11193. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  11194. if (!this._rigCamTransformMatrix) {
  11195. this._rigCamTransformMatrix = new BABYLON.Matrix();
  11196. }
  11197. var target = this.getTarget();
  11198. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  11199. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  11200. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  11201. };
  11202. TargetCamera.prototype.getTypeName = function () {
  11203. return "TargetCamera";
  11204. };
  11205. __decorate([
  11206. BABYLON.serializeAsVector3()
  11207. ], TargetCamera.prototype, "rotation", void 0);
  11208. __decorate([
  11209. BABYLON.serialize()
  11210. ], TargetCamera.prototype, "speed", void 0);
  11211. __decorate([
  11212. BABYLON.serializeAsMeshReference("lockedTargetId")
  11213. ], TargetCamera.prototype, "lockedTarget", void 0);
  11214. return TargetCamera;
  11215. })(BABYLON.Camera);
  11216. BABYLON.TargetCamera = TargetCamera;
  11217. })(BABYLON || (BABYLON = {}));
  11218. var BABYLON;
  11219. (function (BABYLON) {
  11220. var FreeCamera = (function (_super) {
  11221. __extends(FreeCamera, _super);
  11222. function FreeCamera(name, position, scene) {
  11223. var _this = this;
  11224. _super.call(this, name, position, scene);
  11225. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  11226. this.keysUp = [38];
  11227. this.keysDown = [40];
  11228. this.keysLeft = [37];
  11229. this.keysRight = [39];
  11230. this.checkCollisions = false;
  11231. this.applyGravity = false;
  11232. this.angularSensibility = 2000.0;
  11233. this._keys = [];
  11234. this._collider = new BABYLON.Collider();
  11235. this._needMoveForGravity = false;
  11236. this._oldPosition = BABYLON.Vector3.Zero();
  11237. this._diffPosition = BABYLON.Vector3.Zero();
  11238. this._newPosition = BABYLON.Vector3.Zero();
  11239. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  11240. if (collidedMesh === void 0) { collidedMesh = null; }
  11241. //TODO move this to the collision coordinator!
  11242. if (_this.getScene().workerCollisions)
  11243. newPosition.multiplyInPlace(_this._collider.radius);
  11244. var updatePosition = function (newPos) {
  11245. _this._newPosition.copyFrom(newPos);
  11246. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  11247. var oldPosition = _this.position.clone();
  11248. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  11249. _this.position.addInPlace(_this._diffPosition);
  11250. if (_this.onCollide && collidedMesh) {
  11251. _this.onCollide(collidedMesh);
  11252. }
  11253. }
  11254. };
  11255. updatePosition(newPosition);
  11256. };
  11257. }
  11258. FreeCamera.prototype._onLostFocus = function (e) {
  11259. this._keys = [];
  11260. };
  11261. // Controls
  11262. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  11263. var _this = this;
  11264. var previousPosition;
  11265. var engine = this.getEngine();
  11266. if (this._attachedElement) {
  11267. return;
  11268. }
  11269. this._attachedElement = element;
  11270. if (this._onMouseDown === undefined) {
  11271. this._onMouseDown = function (evt) {
  11272. previousPosition = {
  11273. x: evt.clientX,
  11274. y: evt.clientY
  11275. };
  11276. if (!noPreventDefault) {
  11277. evt.preventDefault();
  11278. }
  11279. };
  11280. this._onMouseUp = function (evt) {
  11281. previousPosition = null;
  11282. if (!noPreventDefault) {
  11283. evt.preventDefault();
  11284. }
  11285. };
  11286. this._onMouseOut = function (evt) {
  11287. previousPosition = null;
  11288. _this._keys = [];
  11289. if (!noPreventDefault) {
  11290. evt.preventDefault();
  11291. }
  11292. };
  11293. this._onMouseMove = function (evt) {
  11294. if (!previousPosition && !engine.isPointerLock) {
  11295. return;
  11296. }
  11297. var offsetX;
  11298. var offsetY;
  11299. if (!engine.isPointerLock) {
  11300. offsetX = evt.clientX - previousPosition.x;
  11301. offsetY = evt.clientY - previousPosition.y;
  11302. }
  11303. else {
  11304. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  11305. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  11306. }
  11307. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  11308. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  11309. previousPosition = {
  11310. x: evt.clientX,
  11311. y: evt.clientY
  11312. };
  11313. if (!noPreventDefault) {
  11314. evt.preventDefault();
  11315. }
  11316. };
  11317. this._onKeyDown = function (evt) {
  11318. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11319. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11320. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11321. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11322. var index = _this._keys.indexOf(evt.keyCode);
  11323. if (index === -1) {
  11324. _this._keys.push(evt.keyCode);
  11325. }
  11326. if (!noPreventDefault) {
  11327. evt.preventDefault();
  11328. }
  11329. }
  11330. };
  11331. this._onKeyUp = function (evt) {
  11332. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11333. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11334. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11335. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11336. var index = _this._keys.indexOf(evt.keyCode);
  11337. if (index >= 0) {
  11338. _this._keys.splice(index, 1);
  11339. }
  11340. if (!noPreventDefault) {
  11341. evt.preventDefault();
  11342. }
  11343. }
  11344. };
  11345. this._reset = function () {
  11346. _this._keys = [];
  11347. previousPosition = null;
  11348. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  11349. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  11350. };
  11351. }
  11352. element.addEventListener("mousedown", this._onMouseDown, false);
  11353. element.addEventListener("mouseup", this._onMouseUp, false);
  11354. element.addEventListener("mouseout", this._onMouseOut, false);
  11355. element.addEventListener("mousemove", this._onMouseMove, false);
  11356. BABYLON.Tools.RegisterTopRootEvents([
  11357. { name: "keydown", handler: this._onKeyDown },
  11358. { name: "keyup", handler: this._onKeyUp },
  11359. { name: "blur", handler: this._onLostFocus }
  11360. ]);
  11361. };
  11362. FreeCamera.prototype.detachControl = function (element) {
  11363. if (this._attachedElement !== element) {
  11364. return;
  11365. }
  11366. element.removeEventListener("mousedown", this._onMouseDown);
  11367. element.removeEventListener("mouseup", this._onMouseUp);
  11368. element.removeEventListener("mouseout", this._onMouseOut);
  11369. element.removeEventListener("mousemove", this._onMouseMove);
  11370. BABYLON.Tools.UnregisterTopRootEvents([
  11371. { name: "keydown", handler: this._onKeyDown },
  11372. { name: "keyup", handler: this._onKeyUp },
  11373. { name: "blur", handler: this._onLostFocus }
  11374. ]);
  11375. this._attachedElement = null;
  11376. if (this._reset) {
  11377. this._reset();
  11378. }
  11379. };
  11380. FreeCamera.prototype._collideWithWorld = function (velocity) {
  11381. var globalPosition;
  11382. if (this.parent) {
  11383. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  11384. }
  11385. else {
  11386. globalPosition = this.position;
  11387. }
  11388. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  11389. this._collider.radius = this.ellipsoid;
  11390. //no need for clone, as long as gravity is not on.
  11391. var actualVelocity = velocity;
  11392. //add gravity to the velocity to prevent the dual-collision checking
  11393. if (this.applyGravity) {
  11394. //this prevents mending with cameraDirection, a global variable of the free camera class.
  11395. actualVelocity = velocity.add(this.getScene().gravity);
  11396. }
  11397. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  11398. };
  11399. FreeCamera.prototype._checkInputs = function () {
  11400. if (!this._localDirection) {
  11401. this._localDirection = BABYLON.Vector3.Zero();
  11402. this._transformedDirection = BABYLON.Vector3.Zero();
  11403. }
  11404. // Keyboard
  11405. for (var index = 0; index < this._keys.length; index++) {
  11406. var keyCode = this._keys[index];
  11407. var speed = this._computeLocalCameraSpeed();
  11408. if (this.keysLeft.indexOf(keyCode) !== -1) {
  11409. this._localDirection.copyFromFloats(-speed, 0, 0);
  11410. }
  11411. else if (this.keysUp.indexOf(keyCode) !== -1) {
  11412. this._localDirection.copyFromFloats(0, 0, speed);
  11413. }
  11414. else if (this.keysRight.indexOf(keyCode) !== -1) {
  11415. this._localDirection.copyFromFloats(speed, 0, 0);
  11416. }
  11417. else if (this.keysDown.indexOf(keyCode) !== -1) {
  11418. this._localDirection.copyFromFloats(0, 0, -speed);
  11419. }
  11420. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  11421. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  11422. this.cameraDirection.addInPlace(this._transformedDirection);
  11423. }
  11424. _super.prototype._checkInputs.call(this);
  11425. };
  11426. FreeCamera.prototype._decideIfNeedsToMove = function () {
  11427. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  11428. };
  11429. FreeCamera.prototype._updatePosition = function () {
  11430. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  11431. this._collideWithWorld(this.cameraDirection);
  11432. }
  11433. else {
  11434. this.position.addInPlace(this.cameraDirection);
  11435. }
  11436. };
  11437. FreeCamera.prototype.getTypeName = function () {
  11438. return "FreeCamera";
  11439. };
  11440. __decorate([
  11441. BABYLON.serializeAsVector3()
  11442. ], FreeCamera.prototype, "ellipsoid", void 0);
  11443. __decorate([
  11444. BABYLON.serialize()
  11445. ], FreeCamera.prototype, "keysUp", void 0);
  11446. __decorate([
  11447. BABYLON.serialize()
  11448. ], FreeCamera.prototype, "keysDown", void 0);
  11449. __decorate([
  11450. BABYLON.serialize()
  11451. ], FreeCamera.prototype, "keysLeft", void 0);
  11452. __decorate([
  11453. BABYLON.serialize()
  11454. ], FreeCamera.prototype, "keysRight", void 0);
  11455. __decorate([
  11456. BABYLON.serialize()
  11457. ], FreeCamera.prototype, "checkCollisions", void 0);
  11458. __decorate([
  11459. BABYLON.serialize()
  11460. ], FreeCamera.prototype, "applyGravity", void 0);
  11461. __decorate([
  11462. BABYLON.serialize()
  11463. ], FreeCamera.prototype, "angularSensibility", void 0);
  11464. return FreeCamera;
  11465. })(BABYLON.TargetCamera);
  11466. BABYLON.FreeCamera = FreeCamera;
  11467. })(BABYLON || (BABYLON = {}));
  11468. var BABYLON;
  11469. (function (BABYLON) {
  11470. var FollowCamera = (function (_super) {
  11471. __extends(FollowCamera, _super);
  11472. function FollowCamera(name, position, scene, target) {
  11473. _super.call(this, name, position, scene);
  11474. this.radius = 12;
  11475. this.rotationOffset = 0;
  11476. this.heightOffset = 4;
  11477. this.cameraAcceleration = 0.05;
  11478. this.maxCameraSpeed = 20;
  11479. this.target = target;
  11480. }
  11481. FollowCamera.prototype.getRadians = function (degrees) {
  11482. return degrees * Math.PI / 180;
  11483. };
  11484. FollowCamera.prototype.follow = function (cameraTarget) {
  11485. if (!cameraTarget)
  11486. return;
  11487. var yRotation;
  11488. if (cameraTarget.rotationQuaternion) {
  11489. var rotMatrix = new BABYLON.Matrix();
  11490. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  11491. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  11492. }
  11493. else {
  11494. yRotation = cameraTarget.rotation.y;
  11495. }
  11496. var radians = this.getRadians(this.rotationOffset) + yRotation;
  11497. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  11498. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  11499. var dx = targetX - this.position.x;
  11500. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  11501. var dz = (targetZ) - this.position.z;
  11502. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  11503. var vy = dy * this.cameraAcceleration;
  11504. var vz = dz * this.cameraAcceleration * 2;
  11505. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  11506. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  11507. }
  11508. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  11509. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  11510. }
  11511. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  11512. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  11513. }
  11514. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  11515. this.setTarget(cameraTarget.position);
  11516. };
  11517. FollowCamera.prototype._checkInputs = function () {
  11518. _super.prototype._checkInputs.call(this);
  11519. this.follow(this.target);
  11520. };
  11521. FollowCamera.prototype.getTypeName = function () {
  11522. return "FollowCamera";
  11523. };
  11524. __decorate([
  11525. BABYLON.serialize()
  11526. ], FollowCamera.prototype, "radius", void 0);
  11527. __decorate([
  11528. BABYLON.serialize()
  11529. ], FollowCamera.prototype, "rotationOffset", void 0);
  11530. __decorate([
  11531. BABYLON.serialize()
  11532. ], FollowCamera.prototype, "heightOffset", void 0);
  11533. __decorate([
  11534. BABYLON.serialize()
  11535. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  11536. __decorate([
  11537. BABYLON.serialize()
  11538. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  11539. __decorate([
  11540. BABYLON.serializeAsMeshReference("lockedTargetId")
  11541. ], FollowCamera.prototype, "target", void 0);
  11542. return FollowCamera;
  11543. })(BABYLON.TargetCamera);
  11544. BABYLON.FollowCamera = FollowCamera;
  11545. var ArcFollowCamera = (function (_super) {
  11546. __extends(ArcFollowCamera, _super);
  11547. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  11548. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  11549. this.alpha = alpha;
  11550. this.beta = beta;
  11551. this.radius = radius;
  11552. this.target = target;
  11553. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  11554. this.follow();
  11555. }
  11556. ArcFollowCamera.prototype.follow = function () {
  11557. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  11558. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  11559. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  11560. this.position = this.target.position.add(this._cartesianCoordinates);
  11561. this.setTarget(this.target.position);
  11562. };
  11563. ArcFollowCamera.prototype._checkInputs = function () {
  11564. _super.prototype._checkInputs.call(this);
  11565. this.follow();
  11566. };
  11567. ArcFollowCamera.prototype.getTypeName = function () {
  11568. return "ArcFollowCamera";
  11569. };
  11570. return ArcFollowCamera;
  11571. })(BABYLON.TargetCamera);
  11572. BABYLON.ArcFollowCamera = ArcFollowCamera;
  11573. })(BABYLON || (BABYLON = {}));
  11574. var BABYLON;
  11575. (function (BABYLON) {
  11576. // We're mainly based on the logic defined into the FreeCamera code
  11577. var TouchCamera = (function (_super) {
  11578. __extends(TouchCamera, _super);
  11579. function TouchCamera(name, position, scene) {
  11580. _super.call(this, name, position, scene);
  11581. this._offsetX = null;
  11582. this._offsetY = null;
  11583. this._pointerCount = 0;
  11584. this._pointerPressed = [];
  11585. this.touchAngularSensibility = 200000.0;
  11586. this.touchMoveSensibility = 250.0;
  11587. }
  11588. TouchCamera.prototype._onLostFocus = function (e) {
  11589. this._offsetX = null;
  11590. this._offsetY = null;
  11591. _super.prototype._onLostFocus.call(this, e);
  11592. };
  11593. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  11594. var _this = this;
  11595. var previousPosition;
  11596. if (this._attachedCanvas) {
  11597. return;
  11598. }
  11599. if (this._onPointerDown === undefined) {
  11600. this._onPointerDown = function (evt) {
  11601. if (evt.pointerType === "mouse") {
  11602. return;
  11603. }
  11604. if (!noPreventDefault) {
  11605. evt.preventDefault();
  11606. }
  11607. _this._pointerPressed.push(evt.pointerId);
  11608. if (_this._pointerPressed.length !== 1) {
  11609. return;
  11610. }
  11611. previousPosition = {
  11612. x: evt.clientX,
  11613. y: evt.clientY
  11614. };
  11615. };
  11616. this._onPointerUp = function (evt) {
  11617. if (evt.pointerType === "mouse") {
  11618. return;
  11619. }
  11620. if (!noPreventDefault) {
  11621. evt.preventDefault();
  11622. }
  11623. var index = _this._pointerPressed.indexOf(evt.pointerId);
  11624. if (index === -1) {
  11625. return;
  11626. }
  11627. _this._pointerPressed.splice(index, 1);
  11628. if (index != 0) {
  11629. return;
  11630. }
  11631. previousPosition = null;
  11632. _this._offsetX = null;
  11633. _this._offsetY = null;
  11634. };
  11635. this._onPointerMove = function (evt) {
  11636. if (evt.pointerType === "mouse") {
  11637. return;
  11638. }
  11639. if (!noPreventDefault) {
  11640. evt.preventDefault();
  11641. }
  11642. if (!previousPosition) {
  11643. return;
  11644. }
  11645. var index = _this._pointerPressed.indexOf(evt.pointerId);
  11646. if (index != 0) {
  11647. return;
  11648. }
  11649. _this._offsetX = evt.clientX - previousPosition.x;
  11650. _this._offsetY = -(evt.clientY - previousPosition.y);
  11651. };
  11652. }
  11653. canvas.addEventListener("pointerdown", this._onPointerDown);
  11654. canvas.addEventListener("pointerup", this._onPointerUp);
  11655. canvas.addEventListener("pointerout", this._onPointerUp);
  11656. canvas.addEventListener("pointermove", this._onPointerMove);
  11657. _super.prototype.attachControl.call(this, canvas);
  11658. };
  11659. TouchCamera.prototype.detachControl = function (canvas) {
  11660. if (this._attachedCanvas !== canvas) {
  11661. return;
  11662. }
  11663. canvas.removeEventListener("pointerdown", this._onPointerDown);
  11664. canvas.removeEventListener("pointerup", this._onPointerUp);
  11665. canvas.removeEventListener("pointerout", this._onPointerUp);
  11666. canvas.removeEventListener("pointermove", this._onPointerMove);
  11667. _super.prototype.detachControl.call(this, canvas);
  11668. };
  11669. TouchCamera.prototype._checkInputs = function () {
  11670. if (this._offsetX) {
  11671. this.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  11672. if (this._pointerPressed.length > 1) {
  11673. this.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  11674. }
  11675. else {
  11676. var speed = this._computeLocalCameraSpeed();
  11677. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  11678. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  11679. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  11680. }
  11681. }
  11682. _super.prototype._checkInputs.call(this);
  11683. };
  11684. TouchCamera.prototype.getTypeName = function () {
  11685. return "TouchCamera";
  11686. };
  11687. __decorate([
  11688. BABYLON.serialize()
  11689. ], TouchCamera.prototype, "touchAngularSensibility", void 0);
  11690. __decorate([
  11691. BABYLON.serialize()
  11692. ], TouchCamera.prototype, "touchMoveSensibility", void 0);
  11693. return TouchCamera;
  11694. })(BABYLON.FreeCamera);
  11695. BABYLON.TouchCamera = TouchCamera;
  11696. })(BABYLON || (BABYLON = {}));
  11697. var BABYLON;
  11698. (function (BABYLON) {
  11699. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  11700. var ArcRotateCamera = (function (_super) {
  11701. __extends(ArcRotateCamera, _super);
  11702. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  11703. var _this = this;
  11704. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  11705. this.inertialAlphaOffset = 0;
  11706. this.inertialBetaOffset = 0;
  11707. this.inertialRadiusOffset = 0;
  11708. this.lowerAlphaLimit = null;
  11709. this.upperAlphaLimit = null;
  11710. this.lowerBetaLimit = 0.01;
  11711. this.upperBetaLimit = Math.PI;
  11712. this.lowerRadiusLimit = null;
  11713. this.upperRadiusLimit = null;
  11714. this.angularSensibilityX = 1000.0;
  11715. this.angularSensibilityY = 1000.0;
  11716. this.wheelPrecision = 3.0;
  11717. this.pinchPrecision = 2.0;
  11718. this.panningSensibility = 50.0;
  11719. this.inertialPanningX = 0;
  11720. this.inertialPanningY = 0;
  11721. this.keysUp = [38];
  11722. this.keysDown = [40];
  11723. this.keysLeft = [37];
  11724. this.keysRight = [39];
  11725. this.zoomOnFactor = 1;
  11726. this.targetScreenOffset = BABYLON.Vector2.Zero();
  11727. this.pinchInwards = true;
  11728. this.allowUpsideDown = true;
  11729. this._keys = [];
  11730. this._viewMatrix = new BABYLON.Matrix();
  11731. // Panning
  11732. this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  11733. this._isRightClick = false;
  11734. this._isCtrlPushed = false;
  11735. this.checkCollisions = false;
  11736. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  11737. this._collider = new BABYLON.Collider();
  11738. this._previousPosition = BABYLON.Vector3.Zero();
  11739. this._collisionVelocity = BABYLON.Vector3.Zero();
  11740. this._newPosition = BABYLON.Vector3.Zero();
  11741. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  11742. if (collidedMesh === void 0) { collidedMesh = null; }
  11743. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  11744. newPosition.multiplyInPlace(_this._collider.radius);
  11745. }
  11746. if (!collidedMesh) {
  11747. _this._previousPosition.copyFrom(_this.position);
  11748. }
  11749. else {
  11750. _this.setPosition(newPosition);
  11751. if (_this.onCollide) {
  11752. _this.onCollide(collidedMesh);
  11753. }
  11754. }
  11755. // Recompute because of constraints
  11756. var cosa = Math.cos(_this.alpha);
  11757. var sina = Math.sin(_this.alpha);
  11758. var cosb = Math.cos(_this.beta);
  11759. var sinb = Math.sin(_this.beta);
  11760. if (sinb === 0) {
  11761. sinb = 0.0001;
  11762. }
  11763. var target = _this._getTargetPosition();
  11764. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  11765. _this.position.copyFrom(_this._newPosition);
  11766. var up = _this.upVector;
  11767. if (_this.allowUpsideDown && _this.beta < 0) {
  11768. up = up.clone();
  11769. up = up.negate();
  11770. }
  11771. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  11772. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  11773. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  11774. _this._collisionTriggered = false;
  11775. };
  11776. if (!target) {
  11777. this.target = BABYLON.Vector3.Zero();
  11778. }
  11779. else {
  11780. this.target = target;
  11781. }
  11782. this.alpha = alpha;
  11783. this.beta = beta;
  11784. this.radius = radius;
  11785. this.getViewMatrix();
  11786. }
  11787. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibility", {
  11788. //deprecated angularSensibility support
  11789. get: function () {
  11790. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  11791. return Math.max(this.angularSensibilityX, this.angularSensibilityY);
  11792. },
  11793. //deprecated angularSensibility support
  11794. set: function (value) {
  11795. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  11796. this.angularSensibilityX = value;
  11797. this.angularSensibilityY = value;
  11798. },
  11799. enumerable: true,
  11800. configurable: true
  11801. });
  11802. // Cache
  11803. ArcRotateCamera.prototype._initCache = function () {
  11804. _super.prototype._initCache.call(this);
  11805. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  11806. this._cache.alpha = undefined;
  11807. this._cache.beta = undefined;
  11808. this._cache.radius = undefined;
  11809. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  11810. };
  11811. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  11812. if (!ignoreParentClass) {
  11813. _super.prototype._updateCache.call(this);
  11814. }
  11815. this._cache.target.copyFrom(this._getTargetPosition());
  11816. this._cache.alpha = this.alpha;
  11817. this._cache.beta = this.beta;
  11818. this._cache.radius = this.radius;
  11819. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  11820. };
  11821. ArcRotateCamera.prototype._getTargetPosition = function () {
  11822. if (this.target.getAbsolutePosition) {
  11823. return this.target.getAbsolutePosition();
  11824. }
  11825. return this.target;
  11826. };
  11827. // Synchronized
  11828. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  11829. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  11830. return false;
  11831. return this._cache.target.equals(this.target)
  11832. && this._cache.alpha === this.alpha
  11833. && this._cache.beta === this.beta
  11834. && this._cache.radius === this.radius
  11835. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  11836. };
  11837. // Methods
  11838. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning) {
  11839. var _this = this;
  11840. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  11841. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  11842. var previousPinchDistance = 0;
  11843. var pointers = new BABYLON.SmartCollection();
  11844. if (this._attachedElement) {
  11845. return;
  11846. }
  11847. this._attachedElement = element;
  11848. var engine = this.getEngine();
  11849. if (this._onPointerDown === undefined) {
  11850. this._onPointerDown = function (evt) {
  11851. // Manage panning with right click
  11852. _this._isRightClick = evt.button === 2;
  11853. // manage pointers
  11854. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  11855. cacheSoloPointer = pointers.item(evt.pointerId);
  11856. if (!noPreventDefault) {
  11857. evt.preventDefault();
  11858. }
  11859. };
  11860. this._onPointerUp = function (evt) {
  11861. cacheSoloPointer = null;
  11862. previousPinchDistance = 0;
  11863. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  11864. //but emptying completly pointers collection is required to fix a bug on iPhone :
  11865. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  11866. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  11867. pointers.empty();
  11868. if (!noPreventDefault) {
  11869. evt.preventDefault();
  11870. }
  11871. };
  11872. this._onContextMenu = function (evt) {
  11873. evt.preventDefault();
  11874. };
  11875. this._onPointerMove = function (evt) {
  11876. if (!noPreventDefault) {
  11877. evt.preventDefault();
  11878. }
  11879. switch (pointers.count) {
  11880. case 1:
  11881. if (_this.panningSensibility !== 0 && ((_this._isCtrlPushed && useCtrlForPanning) || (!useCtrlForPanning && _this._isRightClick))) {
  11882. _this.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  11883. _this.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  11884. }
  11885. else {
  11886. var offsetX = evt.clientX - cacheSoloPointer.x;
  11887. var offsetY = evt.clientY - cacheSoloPointer.y;
  11888. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  11889. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  11890. }
  11891. cacheSoloPointer.x = evt.clientX;
  11892. cacheSoloPointer.y = evt.clientY;
  11893. break;
  11894. case 2:
  11895. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  11896. pointers.item(evt.pointerId).x = evt.clientX;
  11897. pointers.item(evt.pointerId).y = evt.clientY;
  11898. var direction = _this.pinchInwards ? 1 : -1;
  11899. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  11900. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  11901. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  11902. if (previousPinchDistance === 0) {
  11903. previousPinchDistance = pinchSquaredDistance;
  11904. return;
  11905. }
  11906. if (pinchSquaredDistance !== previousPinchDistance) {
  11907. _this.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (_this.pinchPrecision * _this.wheelPrecision * ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) * direction);
  11908. previousPinchDistance = pinchSquaredDistance;
  11909. }
  11910. break;
  11911. default:
  11912. if (pointers.item(evt.pointerId)) {
  11913. pointers.item(evt.pointerId).x = evt.clientX;
  11914. pointers.item(evt.pointerId).y = evt.clientY;
  11915. }
  11916. }
  11917. };
  11918. this._onMouseMove = function (evt) {
  11919. if (!engine.isPointerLock) {
  11920. return;
  11921. }
  11922. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  11923. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  11924. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  11925. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  11926. if (!noPreventDefault) {
  11927. evt.preventDefault();
  11928. }
  11929. };
  11930. this._wheel = function (event) {
  11931. var delta = 0;
  11932. if (event.wheelDelta) {
  11933. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  11934. }
  11935. else if (event.detail) {
  11936. delta = -event.detail / _this.wheelPrecision;
  11937. }
  11938. if (delta)
  11939. _this.inertialRadiusOffset += delta;
  11940. if (event.preventDefault) {
  11941. if (!noPreventDefault) {
  11942. event.preventDefault();
  11943. }
  11944. }
  11945. };
  11946. this._onKeyDown = function (evt) {
  11947. _this._isCtrlPushed = evt.ctrlKey;
  11948. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11949. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11950. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11951. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11952. var index = _this._keys.indexOf(evt.keyCode);
  11953. if (index === -1) {
  11954. _this._keys.push(evt.keyCode);
  11955. }
  11956. if (evt.preventDefault) {
  11957. if (!noPreventDefault) {
  11958. evt.preventDefault();
  11959. }
  11960. }
  11961. }
  11962. };
  11963. this._onKeyUp = function (evt) {
  11964. _this._isCtrlPushed = evt.ctrlKey;
  11965. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11966. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11967. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11968. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11969. var index = _this._keys.indexOf(evt.keyCode);
  11970. if (index >= 0) {
  11971. _this._keys.splice(index, 1);
  11972. }
  11973. if (evt.preventDefault) {
  11974. if (!noPreventDefault) {
  11975. evt.preventDefault();
  11976. }
  11977. }
  11978. }
  11979. };
  11980. this._onLostFocus = function () {
  11981. _this._keys = [];
  11982. pointers.empty();
  11983. previousPinchDistance = 0;
  11984. cacheSoloPointer = null;
  11985. };
  11986. this._onGestureStart = function (e) {
  11987. if (window.MSGesture === undefined) {
  11988. return;
  11989. }
  11990. if (!_this._MSGestureHandler) {
  11991. _this._MSGestureHandler = new MSGesture();
  11992. _this._MSGestureHandler.target = element;
  11993. }
  11994. _this._MSGestureHandler.addPointer(e.pointerId);
  11995. };
  11996. this._onGesture = function (e) {
  11997. _this.radius *= e.scale;
  11998. if (e.preventDefault) {
  11999. if (!noPreventDefault) {
  12000. e.stopPropagation();
  12001. e.preventDefault();
  12002. }
  12003. }
  12004. };
  12005. this._reset = function () {
  12006. _this._keys = [];
  12007. _this.inertialAlphaOffset = 0;
  12008. _this.inertialBetaOffset = 0;
  12009. _this.inertialRadiusOffset = 0;
  12010. pointers.empty();
  12011. previousPinchDistance = 0;
  12012. cacheSoloPointer = null;
  12013. };
  12014. }
  12015. if (!useCtrlForPanning) {
  12016. element.addEventListener("contextmenu", this._onContextMenu, false);
  12017. }
  12018. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  12019. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  12020. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  12021. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  12022. element.addEventListener("mousemove", this._onMouseMove, false);
  12023. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  12024. element.addEventListener("MSGestureChange", this._onGesture, false);
  12025. element.addEventListener('mousewheel', this._wheel, false);
  12026. element.addEventListener('DOMMouseScroll', this._wheel, false);
  12027. BABYLON.Tools.RegisterTopRootEvents([
  12028. { name: "keydown", handler: this._onKeyDown },
  12029. { name: "keyup", handler: this._onKeyUp },
  12030. { name: "blur", handler: this._onLostFocus }
  12031. ]);
  12032. };
  12033. ArcRotateCamera.prototype.detachControl = function (element) {
  12034. if (this._attachedElement !== element) {
  12035. return;
  12036. }
  12037. element.removeEventListener("contextmenu", this._onContextMenu);
  12038. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  12039. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  12040. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  12041. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  12042. element.removeEventListener("mousemove", this._onMouseMove);
  12043. element.removeEventListener("MSPointerDown", this._onGestureStart);
  12044. element.removeEventListener("MSGestureChange", this._onGesture);
  12045. element.removeEventListener('mousewheel', this._wheel);
  12046. element.removeEventListener('DOMMouseScroll', this._wheel);
  12047. BABYLON.Tools.UnregisterTopRootEvents([
  12048. { name: "keydown", handler: this._onKeyDown },
  12049. { name: "keyup", handler: this._onKeyUp },
  12050. { name: "blur", handler: this._onLostFocus }
  12051. ]);
  12052. this._MSGestureHandler = null;
  12053. this._attachedElement = null;
  12054. if (this._reset) {
  12055. this._reset();
  12056. }
  12057. };
  12058. ArcRotateCamera.prototype._checkInputs = function () {
  12059. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  12060. if (this._collisionTriggered) {
  12061. return;
  12062. }
  12063. // Keyboard
  12064. for (var index = 0; index < this._keys.length; index++) {
  12065. var keyCode = this._keys[index];
  12066. if (this.keysLeft.indexOf(keyCode) !== -1) {
  12067. this.inertialAlphaOffset -= 0.01;
  12068. }
  12069. else if (this.keysUp.indexOf(keyCode) !== -1) {
  12070. this.inertialBetaOffset -= 0.01;
  12071. }
  12072. else if (this.keysRight.indexOf(keyCode) !== -1) {
  12073. this.inertialAlphaOffset += 0.01;
  12074. }
  12075. else if (this.keysDown.indexOf(keyCode) !== -1) {
  12076. this.inertialBetaOffset += 0.01;
  12077. }
  12078. }
  12079. // Inertia
  12080. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  12081. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  12082. this.beta += this.inertialBetaOffset;
  12083. this.radius -= this.inertialRadiusOffset;
  12084. this.inertialAlphaOffset *= this.inertia;
  12085. this.inertialBetaOffset *= this.inertia;
  12086. this.inertialRadiusOffset *= this.inertia;
  12087. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  12088. this.inertialAlphaOffset = 0;
  12089. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  12090. this.inertialBetaOffset = 0;
  12091. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Epsilon)
  12092. this.inertialRadiusOffset = 0;
  12093. }
  12094. // Panning inertia
  12095. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  12096. if (!this._localDirection) {
  12097. this._localDirection = BABYLON.Vector3.Zero();
  12098. this._transformedDirection = BABYLON.Vector3.Zero();
  12099. }
  12100. this.inertialPanningX *= this.inertia;
  12101. this.inertialPanningY *= this.inertia;
  12102. if (Math.abs(this.inertialPanningX) < BABYLON.Epsilon)
  12103. this.inertialPanningX = 0;
  12104. if (Math.abs(this.inertialPanningY) < BABYLON.Epsilon)
  12105. this.inertialPanningY = 0;
  12106. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  12107. this._localDirection.multiplyInPlace(this.panningAxis);
  12108. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  12109. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  12110. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  12111. if (!this.panningAxis.y) {
  12112. this._transformedDirection.y = 0;
  12113. }
  12114. this.target.addInPlace(this._transformedDirection);
  12115. }
  12116. // Limits
  12117. this._checkLimits();
  12118. _super.prototype._checkInputs.call(this);
  12119. };
  12120. ArcRotateCamera.prototype._checkLimits = function () {
  12121. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  12122. if (this.allowUpsideDown && this.beta > Math.PI) {
  12123. this.beta = this.beta - (2 * Math.PI);
  12124. }
  12125. }
  12126. else {
  12127. if (this.beta < this.lowerBetaLimit) {
  12128. this.beta = this.lowerBetaLimit;
  12129. }
  12130. }
  12131. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  12132. if (this.allowUpsideDown && this.beta < -Math.PI) {
  12133. this.beta = this.beta + (2 * Math.PI);
  12134. }
  12135. }
  12136. else {
  12137. if (this.beta > this.upperBetaLimit) {
  12138. this.beta = this.upperBetaLimit;
  12139. }
  12140. }
  12141. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  12142. this.alpha = this.lowerAlphaLimit;
  12143. }
  12144. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  12145. this.alpha = this.upperAlphaLimit;
  12146. }
  12147. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  12148. this.radius = this.lowerRadiusLimit;
  12149. }
  12150. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  12151. this.radius = this.upperRadiusLimit;
  12152. }
  12153. };
  12154. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  12155. var radiusv3 = this.position.subtract(this._getTargetPosition());
  12156. this.radius = radiusv3.length();
  12157. // Alpha
  12158. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  12159. if (radiusv3.z < 0) {
  12160. this.alpha = 2 * Math.PI - this.alpha;
  12161. }
  12162. // Beta
  12163. this.beta = Math.acos(radiusv3.y / this.radius);
  12164. this._checkLimits();
  12165. };
  12166. ArcRotateCamera.prototype.setPosition = function (position) {
  12167. if (this.position.equals(position)) {
  12168. return;
  12169. }
  12170. this.position = position;
  12171. this.rebuildAnglesAndRadius();
  12172. };
  12173. ArcRotateCamera.prototype.setTarget = function (target) {
  12174. if (this._getTargetPosition().equals(target)) {
  12175. return;
  12176. }
  12177. this.target = target;
  12178. this.rebuildAnglesAndRadius();
  12179. };
  12180. ArcRotateCamera.prototype._getViewMatrix = function () {
  12181. // Compute
  12182. var cosa = Math.cos(this.alpha);
  12183. var sina = Math.sin(this.alpha);
  12184. var cosb = Math.cos(this.beta);
  12185. var sinb = Math.sin(this.beta);
  12186. if (sinb === 0) {
  12187. sinb = 0.0001;
  12188. }
  12189. var target = this._getTargetPosition();
  12190. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  12191. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  12192. this._collider.radius = this.collisionRadius;
  12193. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  12194. this._collisionTriggered = true;
  12195. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  12196. }
  12197. else {
  12198. this.position.copyFrom(this._newPosition);
  12199. var up = this.upVector;
  12200. if (this.allowUpsideDown && this.beta < 0) {
  12201. up = up.clone();
  12202. up = up.negate();
  12203. }
  12204. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  12205. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  12206. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  12207. }
  12208. return this._viewMatrix;
  12209. };
  12210. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  12211. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  12212. meshes = meshes || this.getScene().meshes;
  12213. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  12214. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  12215. this.radius = distance * this.zoomOnFactor;
  12216. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  12217. };
  12218. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  12219. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  12220. var meshesOrMinMaxVector;
  12221. var distance;
  12222. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  12223. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  12224. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  12225. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  12226. }
  12227. else {
  12228. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  12229. distance = meshesOrMinMaxVectorAndDistance.distance;
  12230. }
  12231. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  12232. if (!doNotUpdateMaxZ) {
  12233. this.maxZ = distance * 2;
  12234. }
  12235. };
  12236. /**
  12237. * @override
  12238. * Override Camera.createRigCamera
  12239. */
  12240. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  12241. switch (this.cameraRigMode) {
  12242. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  12243. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  12244. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  12245. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  12246. case BABYLON.Camera.RIG_MODE_VR:
  12247. var alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  12248. return new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  12249. }
  12250. return null;
  12251. };
  12252. /**
  12253. * @override
  12254. * Override Camera._updateRigCameras
  12255. */
  12256. ArcRotateCamera.prototype._updateRigCameras = function () {
  12257. switch (this.cameraRigMode) {
  12258. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  12259. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  12260. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  12261. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  12262. case BABYLON.Camera.RIG_MODE_VR:
  12263. var camLeft = this._rigCameras[0];
  12264. var camRight = this._rigCameras[1];
  12265. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  12266. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  12267. camLeft.beta = camRight.beta = this.beta;
  12268. camLeft.radius = camRight.radius = this.radius;
  12269. break;
  12270. }
  12271. _super.prototype._updateRigCameras.call(this);
  12272. };
  12273. ArcRotateCamera.prototype.getTypeName = function () {
  12274. return "ArcRotateCamera";
  12275. };
  12276. __decorate([
  12277. BABYLON.serialize()
  12278. ], ArcRotateCamera.prototype, "alpha", void 0);
  12279. __decorate([
  12280. BABYLON.serialize()
  12281. ], ArcRotateCamera.prototype, "beta", void 0);
  12282. __decorate([
  12283. BABYLON.serialize()
  12284. ], ArcRotateCamera.prototype, "radius", void 0);
  12285. __decorate([
  12286. BABYLON.serializeAsVector3()
  12287. ], ArcRotateCamera.prototype, "target", void 0);
  12288. __decorate([
  12289. BABYLON.serialize()
  12290. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  12291. __decorate([
  12292. BABYLON.serialize()
  12293. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  12294. __decorate([
  12295. BABYLON.serialize()
  12296. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  12297. __decorate([
  12298. BABYLON.serialize()
  12299. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  12300. __decorate([
  12301. BABYLON.serialize()
  12302. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  12303. __decorate([
  12304. BABYLON.serialize()
  12305. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  12306. __decorate([
  12307. BABYLON.serialize()
  12308. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  12309. __decorate([
  12310. BABYLON.serialize()
  12311. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  12312. __decorate([
  12313. BABYLON.serialize()
  12314. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  12315. __decorate([
  12316. BABYLON.serialize()
  12317. ], ArcRotateCamera.prototype, "angularSensibilityX", void 0);
  12318. __decorate([
  12319. BABYLON.serialize()
  12320. ], ArcRotateCamera.prototype, "angularSensibilityY", void 0);
  12321. __decorate([
  12322. BABYLON.serialize()
  12323. ], ArcRotateCamera.prototype, "wheelPrecision", void 0);
  12324. __decorate([
  12325. BABYLON.serialize()
  12326. ], ArcRotateCamera.prototype, "pinchPrecision", void 0);
  12327. __decorate([
  12328. BABYLON.serialize()
  12329. ], ArcRotateCamera.prototype, "panningSensibility", void 0);
  12330. __decorate([
  12331. BABYLON.serialize()
  12332. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  12333. __decorate([
  12334. BABYLON.serialize()
  12335. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  12336. __decorate([
  12337. BABYLON.serialize()
  12338. ], ArcRotateCamera.prototype, "keysUp", void 0);
  12339. __decorate([
  12340. BABYLON.serialize()
  12341. ], ArcRotateCamera.prototype, "keysDown", void 0);
  12342. __decorate([
  12343. BABYLON.serialize()
  12344. ], ArcRotateCamera.prototype, "keysLeft", void 0);
  12345. __decorate([
  12346. BABYLON.serialize()
  12347. ], ArcRotateCamera.prototype, "keysRight", void 0);
  12348. __decorate([
  12349. BABYLON.serialize()
  12350. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  12351. __decorate([
  12352. BABYLON.serialize()
  12353. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  12354. return ArcRotateCamera;
  12355. })(BABYLON.TargetCamera);
  12356. BABYLON.ArcRotateCamera = ArcRotateCamera;
  12357. })(BABYLON || (BABYLON = {}));
  12358. var BABYLON;
  12359. (function (BABYLON) {
  12360. var RenderingManager = (function () {
  12361. function RenderingManager(scene) {
  12362. this._renderingGroups = new Array();
  12363. this._scene = scene;
  12364. }
  12365. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  12366. if (this._scene._activeParticleSystems.length === 0) {
  12367. return;
  12368. }
  12369. // Particles
  12370. var activeCamera = this._scene.activeCamera;
  12371. var beforeParticlesDate = BABYLON.Tools.Now;
  12372. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  12373. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  12374. if (particleSystem.renderingGroupId !== index) {
  12375. continue;
  12376. }
  12377. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  12378. continue;
  12379. }
  12380. this._clearDepthBuffer();
  12381. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  12382. this._scene._activeParticles += particleSystem.render();
  12383. }
  12384. }
  12385. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  12386. };
  12387. RenderingManager.prototype._renderSprites = function (index) {
  12388. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  12389. return;
  12390. }
  12391. // Sprites
  12392. var activeCamera = this._scene.activeCamera;
  12393. var beforeSpritessDate = BABYLON.Tools.Now;
  12394. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  12395. var spriteManager = this._scene.spriteManagers[id];
  12396. if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  12397. this._clearDepthBuffer();
  12398. spriteManager.render();
  12399. }
  12400. }
  12401. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  12402. };
  12403. RenderingManager.prototype._clearDepthBuffer = function () {
  12404. if (this._depthBufferAlreadyCleaned) {
  12405. return;
  12406. }
  12407. this._scene.getEngine().clear(0, false, true);
  12408. this._depthBufferAlreadyCleaned = true;
  12409. };
  12410. RenderingManager.prototype._renderSpritesAndParticles = function () {
  12411. if (this._currentRenderSprites) {
  12412. this._renderSprites(this._currentIndex);
  12413. }
  12414. if (this._currentRenderParticles) {
  12415. this._renderParticles(this._currentIndex, this._currentActiveMeshes);
  12416. }
  12417. };
  12418. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  12419. this._currentActiveMeshes = activeMeshes;
  12420. this._currentRenderParticles = renderParticles;
  12421. this._currentRenderSprites = renderSprites;
  12422. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  12423. this._depthBufferAlreadyCleaned = index == 0;
  12424. var renderingGroup = this._renderingGroups[index];
  12425. var needToStepBack = false;
  12426. this._currentIndex = index;
  12427. if (renderingGroup) {
  12428. this._clearDepthBuffer();
  12429. if (!renderingGroup.onBeforeTransparentRendering) {
  12430. renderingGroup.onBeforeTransparentRendering = this._renderSpritesAndParticles.bind(this);
  12431. }
  12432. if (!renderingGroup.render(customRenderFunction)) {
  12433. this._renderingGroups.splice(index, 1);
  12434. needToStepBack = true;
  12435. this._renderSpritesAndParticles();
  12436. }
  12437. }
  12438. else {
  12439. this._renderSpritesAndParticles();
  12440. }
  12441. if (needToStepBack) {
  12442. index--;
  12443. }
  12444. }
  12445. };
  12446. RenderingManager.prototype.reset = function () {
  12447. this._renderingGroups.forEach(function (renderingGroup, index, array) {
  12448. if (renderingGroup) {
  12449. renderingGroup.prepare();
  12450. }
  12451. });
  12452. };
  12453. RenderingManager.prototype.dispatch = function (subMesh) {
  12454. var mesh = subMesh.getMesh();
  12455. var renderingGroupId = mesh.renderingGroupId || 0;
  12456. if (!this._renderingGroups[renderingGroupId]) {
  12457. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  12458. }
  12459. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  12460. };
  12461. RenderingManager.MAX_RENDERINGGROUPS = 4;
  12462. return RenderingManager;
  12463. })();
  12464. BABYLON.RenderingManager = RenderingManager;
  12465. })(BABYLON || (BABYLON = {}));
  12466. var BABYLON;
  12467. (function (BABYLON) {
  12468. var RenderingGroup = (function () {
  12469. function RenderingGroup(index, scene) {
  12470. this.index = index;
  12471. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  12472. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  12473. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  12474. this._scene = scene;
  12475. }
  12476. RenderingGroup.prototype.render = function (customRenderFunction) {
  12477. if (customRenderFunction) {
  12478. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  12479. return true;
  12480. }
  12481. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  12482. if (this.onBeforeTransparentRendering) {
  12483. this.onBeforeTransparentRendering();
  12484. }
  12485. return false;
  12486. }
  12487. var engine = this._scene.getEngine();
  12488. // Opaque
  12489. var subIndex;
  12490. var submesh;
  12491. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  12492. submesh = this._opaqueSubMeshes.data[subIndex];
  12493. submesh.render(false);
  12494. }
  12495. // Alpha test
  12496. engine.setAlphaTesting(true);
  12497. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  12498. submesh = this._alphaTestSubMeshes.data[subIndex];
  12499. submesh.render(false);
  12500. }
  12501. engine.setAlphaTesting(false);
  12502. if (this.onBeforeTransparentRendering) {
  12503. this.onBeforeTransparentRendering();
  12504. }
  12505. // Transparent
  12506. if (this._transparentSubMeshes.length) {
  12507. // Sorting
  12508. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  12509. submesh = this._transparentSubMeshes.data[subIndex];
  12510. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  12511. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.globalPosition).length();
  12512. }
  12513. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  12514. sortedArray.sort(function (a, b) {
  12515. // Alpha index first
  12516. if (a._alphaIndex > b._alphaIndex) {
  12517. return 1;
  12518. }
  12519. if (a._alphaIndex < b._alphaIndex) {
  12520. return -1;
  12521. }
  12522. // Then distance to camera
  12523. if (a._distanceToCamera < b._distanceToCamera) {
  12524. return 1;
  12525. }
  12526. if (a._distanceToCamera > b._distanceToCamera) {
  12527. return -1;
  12528. }
  12529. return 0;
  12530. });
  12531. // Rendering
  12532. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  12533. submesh = sortedArray[subIndex];
  12534. submesh.render(true);
  12535. }
  12536. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12537. }
  12538. return true;
  12539. };
  12540. RenderingGroup.prototype.prepare = function () {
  12541. this._opaqueSubMeshes.reset();
  12542. this._transparentSubMeshes.reset();
  12543. this._alphaTestSubMeshes.reset();
  12544. };
  12545. RenderingGroup.prototype.dispatch = function (subMesh) {
  12546. var material = subMesh.getMaterial();
  12547. var mesh = subMesh.getMesh();
  12548. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  12549. this._transparentSubMeshes.push(subMesh);
  12550. }
  12551. else if (material.needAlphaTesting()) {
  12552. this._alphaTestSubMeshes.push(subMesh);
  12553. }
  12554. else {
  12555. this._opaqueSubMeshes.push(subMesh); // Opaque
  12556. }
  12557. };
  12558. return RenderingGroup;
  12559. })();
  12560. BABYLON.RenderingGroup = RenderingGroup;
  12561. })(BABYLON || (BABYLON = {}));
  12562. var BABYLON;
  12563. (function (BABYLON) {
  12564. /**
  12565. * Represents a scene to be rendered by the engine.
  12566. * @see http://doc.babylonjs.com/page.php?p=21911
  12567. */
  12568. var Scene = (function () {
  12569. /**
  12570. * @constructor
  12571. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  12572. */
  12573. function Scene(engine) {
  12574. // Members
  12575. this.autoClear = true;
  12576. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  12577. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  12578. this.forceWireframe = false;
  12579. this.forcePointsCloud = false;
  12580. this.forceShowBoundingBoxes = false;
  12581. this.animationsEnabled = true;
  12582. this.constantlyUpdateMeshUnderPointer = false;
  12583. // Animations
  12584. this.animations = [];
  12585. 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
  12586. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  12587. this._startingPointerTime = 0;
  12588. // Fog
  12589. /**
  12590. * is fog enabled on this scene.
  12591. * @type {boolean}
  12592. */
  12593. this.fogEnabled = true;
  12594. this.fogMode = Scene.FOGMODE_NONE;
  12595. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  12596. this.fogDensity = 0.1;
  12597. this.fogStart = 0;
  12598. this.fogEnd = 1000.0;
  12599. // Lights
  12600. /**
  12601. * is shadow enabled on this scene.
  12602. * @type {boolean}
  12603. */
  12604. this.shadowsEnabled = true;
  12605. /**
  12606. * is light enabled on this scene.
  12607. * @type {boolean}
  12608. */
  12609. this.lightsEnabled = true;
  12610. /**
  12611. * All of the lights added to this scene.
  12612. * @see BABYLON.Light
  12613. * @type {BABYLON.Light[]}
  12614. */
  12615. this.lights = new Array();
  12616. // Cameras
  12617. /**
  12618. * All of the cameras added to this scene.
  12619. * @see BABYLON.Camera
  12620. * @type {BABYLON.Camera[]}
  12621. */
  12622. this.cameras = new Array();
  12623. this.activeCameras = new Array();
  12624. // Meshes
  12625. /**
  12626. * All of the (abstract) meshes added to this scene.
  12627. * @see BABYLON.AbstractMesh
  12628. * @type {BABYLON.AbstractMesh[]}
  12629. */
  12630. this.meshes = new Array();
  12631. // Geometries
  12632. this._geometries = new Array();
  12633. this.materials = new Array();
  12634. this.multiMaterials = new Array();
  12635. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  12636. // Textures
  12637. this.texturesEnabled = true;
  12638. this.textures = new Array();
  12639. // Particles
  12640. this.particlesEnabled = true;
  12641. this.particleSystems = new Array();
  12642. // Sprites
  12643. this.spritesEnabled = true;
  12644. this.spriteManagers = new Array();
  12645. // Layers
  12646. this.layers = new Array();
  12647. // Skeletons
  12648. this.skeletonsEnabled = true;
  12649. this.skeletons = new Array();
  12650. // Lens flares
  12651. this.lensFlaresEnabled = true;
  12652. this.lensFlareSystems = new Array();
  12653. // Collisions
  12654. this.collisionsEnabled = true;
  12655. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  12656. // Postprocesses
  12657. this.postProcessesEnabled = true;
  12658. // Customs render targets
  12659. this.renderTargetsEnabled = true;
  12660. this.dumpNextRenderTargets = false;
  12661. this.customRenderTargets = new Array();
  12662. // Imported meshes
  12663. this.importedMeshesFiles = new Array();
  12664. // Probes
  12665. this.probesEnabled = true;
  12666. this.reflectionProbes = new Array();
  12667. this._actionManagers = new Array();
  12668. this._meshesForIntersections = new BABYLON.SmartArray(256);
  12669. // Procedural textures
  12670. this.proceduralTexturesEnabled = true;
  12671. this._proceduralTextures = new Array();
  12672. this.soundTracks = new Array();
  12673. this._audioEnabled = true;
  12674. this._headphone = false;
  12675. this._totalVertices = 0;
  12676. this._activeIndices = 0;
  12677. this._activeParticles = 0;
  12678. this._lastFrameDuration = 0;
  12679. this._evaluateActiveMeshesDuration = 0;
  12680. this._renderTargetsDuration = 0;
  12681. this._particlesDuration = 0;
  12682. this._renderDuration = 0;
  12683. this._spritesDuration = 0;
  12684. this._animationRatio = 0;
  12685. this._renderId = 0;
  12686. this._executeWhenReadyTimeoutId = -1;
  12687. this._toBeDisposed = new BABYLON.SmartArray(256);
  12688. this._onReadyCallbacks = new Array();
  12689. this._pendingData = []; //ANY
  12690. this._onBeforeRenderCallbacks = new Array();
  12691. this._onAfterRenderCallbacks = new Array();
  12692. this._activeMeshes = new BABYLON.SmartArray(256);
  12693. this._processedMaterials = new BABYLON.SmartArray(256);
  12694. this._renderTargets = new BABYLON.SmartArray(256);
  12695. this._activeParticleSystems = new BABYLON.SmartArray(256);
  12696. this._activeSkeletons = new BABYLON.SmartArray(32);
  12697. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  12698. this._activeBones = 0;
  12699. this._activeAnimatables = new Array();
  12700. this._transformMatrix = BABYLON.Matrix.Zero();
  12701. this._edgesRenderers = new BABYLON.SmartArray(16);
  12702. this._uniqueIdCounter = 0;
  12703. this._engine = engine;
  12704. engine.scenes.push(this);
  12705. this._renderingManager = new BABYLON.RenderingManager(this);
  12706. this.postProcessManager = new BABYLON.PostProcessManager(this);
  12707. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  12708. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  12709. if (BABYLON.OutlineRenderer) {
  12710. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  12711. }
  12712. this.attachControl();
  12713. this._debugLayer = new BABYLON.DebugLayer(this);
  12714. if (BABYLON.SoundTrack) {
  12715. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  12716. }
  12717. //simplification queue
  12718. if (BABYLON.SimplificationQueue) {
  12719. this.simplificationQueue = new BABYLON.SimplificationQueue();
  12720. }
  12721. //collision coordinator initialization. For now legacy per default.
  12722. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  12723. }
  12724. Object.defineProperty(Scene, "FOGMODE_NONE", {
  12725. get: function () {
  12726. return Scene._FOGMODE_NONE;
  12727. },
  12728. enumerable: true,
  12729. configurable: true
  12730. });
  12731. Object.defineProperty(Scene, "FOGMODE_EXP", {
  12732. get: function () {
  12733. return Scene._FOGMODE_EXP;
  12734. },
  12735. enumerable: true,
  12736. configurable: true
  12737. });
  12738. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  12739. get: function () {
  12740. return Scene._FOGMODE_EXP2;
  12741. },
  12742. enumerable: true,
  12743. configurable: true
  12744. });
  12745. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  12746. get: function () {
  12747. return Scene._FOGMODE_LINEAR;
  12748. },
  12749. enumerable: true,
  12750. configurable: true
  12751. });
  12752. Object.defineProperty(Scene.prototype, "debugLayer", {
  12753. // Properties
  12754. get: function () {
  12755. return this._debugLayer;
  12756. },
  12757. enumerable: true,
  12758. configurable: true
  12759. });
  12760. Object.defineProperty(Scene.prototype, "workerCollisions", {
  12761. get: function () {
  12762. return this._workerCollisions;
  12763. },
  12764. set: function (enabled) {
  12765. enabled = (enabled && !!Worker);
  12766. this._workerCollisions = enabled;
  12767. if (this.collisionCoordinator) {
  12768. this.collisionCoordinator.destroy();
  12769. }
  12770. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  12771. this.collisionCoordinator.init(this);
  12772. },
  12773. enumerable: true,
  12774. configurable: true
  12775. });
  12776. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  12777. get: function () {
  12778. return this._selectionOctree;
  12779. },
  12780. enumerable: true,
  12781. configurable: true
  12782. });
  12783. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  12784. /**
  12785. * The mesh that is currently under the pointer.
  12786. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  12787. */
  12788. get: function () {
  12789. return this._pointerOverMesh;
  12790. },
  12791. enumerable: true,
  12792. configurable: true
  12793. });
  12794. Object.defineProperty(Scene.prototype, "pointerX", {
  12795. /**
  12796. * Current on-screen X position of the pointer
  12797. * @return {number} X position of the pointer
  12798. */
  12799. get: function () {
  12800. return this._pointerX;
  12801. },
  12802. enumerable: true,
  12803. configurable: true
  12804. });
  12805. Object.defineProperty(Scene.prototype, "pointerY", {
  12806. /**
  12807. * Current on-screen Y position of the pointer
  12808. * @return {number} Y position of the pointer
  12809. */
  12810. get: function () {
  12811. return this._pointerY;
  12812. },
  12813. enumerable: true,
  12814. configurable: true
  12815. });
  12816. Scene.prototype.getCachedMaterial = function () {
  12817. return this._cachedMaterial;
  12818. };
  12819. Scene.prototype.getBoundingBoxRenderer = function () {
  12820. return this._boundingBoxRenderer;
  12821. };
  12822. Scene.prototype.getOutlineRenderer = function () {
  12823. return this._outlineRenderer;
  12824. };
  12825. Scene.prototype.getEngine = function () {
  12826. return this._engine;
  12827. };
  12828. Scene.prototype.getTotalVertices = function () {
  12829. return this._totalVertices;
  12830. };
  12831. Scene.prototype.getActiveIndices = function () {
  12832. return this._activeIndices;
  12833. };
  12834. Scene.prototype.getActiveParticles = function () {
  12835. return this._activeParticles;
  12836. };
  12837. Scene.prototype.getActiveBones = function () {
  12838. return this._activeBones;
  12839. };
  12840. // Stats
  12841. Scene.prototype.getLastFrameDuration = function () {
  12842. return this._lastFrameDuration;
  12843. };
  12844. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  12845. return this._evaluateActiveMeshesDuration;
  12846. };
  12847. Scene.prototype.getActiveMeshes = function () {
  12848. return this._activeMeshes;
  12849. };
  12850. Scene.prototype.getRenderTargetsDuration = function () {
  12851. return this._renderTargetsDuration;
  12852. };
  12853. Scene.prototype.getRenderDuration = function () {
  12854. return this._renderDuration;
  12855. };
  12856. Scene.prototype.getParticlesDuration = function () {
  12857. return this._particlesDuration;
  12858. };
  12859. Scene.prototype.getSpritesDuration = function () {
  12860. return this._spritesDuration;
  12861. };
  12862. Scene.prototype.getAnimationRatio = function () {
  12863. return this._animationRatio;
  12864. };
  12865. Scene.prototype.getRenderId = function () {
  12866. return this._renderId;
  12867. };
  12868. Scene.prototype.incrementRenderId = function () {
  12869. this._renderId++;
  12870. };
  12871. Scene.prototype._updatePointerPosition = function (evt) {
  12872. var canvasRect = this._engine.getRenderingCanvasClientRect();
  12873. this._pointerX = evt.clientX - canvasRect.left;
  12874. this._pointerY = evt.clientY - canvasRect.top;
  12875. this._unTranslatedPointerX = this._pointerX;
  12876. this._unTranslatedPointerY = this._pointerY;
  12877. if (this.cameraToUseForPointers) {
  12878. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  12879. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  12880. }
  12881. };
  12882. // Pointers handling
  12883. Scene.prototype.attachControl = function () {
  12884. var _this = this;
  12885. var spritePredicate = function (sprite) {
  12886. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  12887. };
  12888. this._onPointerMove = function (evt) {
  12889. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  12890. return;
  12891. }
  12892. var canvas = _this._engine.getRenderingCanvas();
  12893. _this._updatePointerPosition(evt);
  12894. if (!_this.pointerMovePredicate) {
  12895. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || mesh.actionManager !== null && mesh.actionManager !== undefined); };
  12896. }
  12897. // Meshes
  12898. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  12899. if (pickResult.hit && pickResult.pickedMesh) {
  12900. _this.setPointerOverSprite(null);
  12901. _this.setPointerOverMesh(pickResult.pickedMesh);
  12902. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  12903. canvas.style.cursor = "pointer";
  12904. }
  12905. else {
  12906. canvas.style.cursor = "";
  12907. }
  12908. }
  12909. else {
  12910. _this.setPointerOverMesh(null);
  12911. // Sprites
  12912. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  12913. if (pickResult.hit && pickResult.pickedSprite) {
  12914. canvas.style.cursor = "pointer";
  12915. _this.setPointerOverSprite(pickResult.pickedSprite);
  12916. }
  12917. else {
  12918. _this.setPointerOverSprite(null);
  12919. // Restore pointer
  12920. canvas.style.cursor = "";
  12921. }
  12922. }
  12923. if (_this.onPointerMove) {
  12924. _this.onPointerMove(evt, pickResult);
  12925. }
  12926. };
  12927. this._onPointerDown = function (evt) {
  12928. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  12929. return;
  12930. }
  12931. _this._updatePointerPosition(evt);
  12932. _this._startingPointerPosition.x = _this._pointerX;
  12933. _this._startingPointerPosition.y = _this._pointerY;
  12934. _this._startingPointerTime = new Date().getTime();
  12935. if (!_this.pointerDownPredicate) {
  12936. _this.pointerDownPredicate = function (mesh) {
  12937. return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || mesh.actionManager.hasPointerTriggers);
  12938. };
  12939. }
  12940. // Meshes
  12941. _this._pickedDownMesh = null;
  12942. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  12943. if (pickResult.hit && pickResult.pickedMesh) {
  12944. if (pickResult.pickedMesh.actionManager) {
  12945. _this._pickedDownMesh = pickResult.pickedMesh;
  12946. if (pickResult.pickedMesh.actionManager.hasPickTriggers) {
  12947. switch (evt.button) {
  12948. case 0:
  12949. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12950. break;
  12951. case 1:
  12952. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12953. break;
  12954. case 2:
  12955. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12956. break;
  12957. }
  12958. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12959. }
  12960. if (pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  12961. var that = _this;
  12962. window.setTimeout(function () {
  12963. var pickResult = that.pick(that._unTranslatedPointerX, that._unTranslatedPointerY, function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger); }, false, that.cameraToUseForPointers);
  12964. if (pickResult.hit && pickResult.pickedMesh) {
  12965. if (pickResult.pickedMesh.actionManager) {
  12966. 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)) {
  12967. that._startingPointerTime = 0;
  12968. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12969. }
  12970. }
  12971. }
  12972. }, BABYLON.ActionManager.LongPressDelay);
  12973. }
  12974. }
  12975. }
  12976. if (_this.onPointerDown) {
  12977. _this.onPointerDown(evt, pickResult);
  12978. }
  12979. // Sprites
  12980. _this._pickedDownSprite = null;
  12981. if (_this.spriteManagers.length > 0) {
  12982. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  12983. if (pickResult.hit && pickResult.pickedSprite) {
  12984. if (pickResult.pickedSprite.actionManager) {
  12985. _this._pickedDownSprite = pickResult.pickedSprite;
  12986. switch (evt.button) {
  12987. case 0:
  12988. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12989. break;
  12990. case 1:
  12991. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12992. break;
  12993. case 2:
  12994. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12995. break;
  12996. }
  12997. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  12998. }
  12999. }
  13000. }
  13001. };
  13002. this._onPointerUp = function (evt) {
  13003. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  13004. return;
  13005. }
  13006. _this._updatePointerPosition(evt);
  13007. if (!_this.pointerUpPredicate) {
  13008. _this.pointerUpPredicate = function (mesh) {
  13009. return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || (mesh.actionManager.hasPickTriggers || mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)));
  13010. };
  13011. }
  13012. // Meshes
  13013. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerUpPredicate, false, _this.cameraToUseForPointers);
  13014. if (pickResult.hit && pickResult.pickedMesh) {
  13015. if (_this.onPointerPick && _this._pickedDownMesh != null && pickResult.pickedMesh == _this._pickedDownMesh) {
  13016. _this.onPointerPick(evt, pickResult);
  13017. }
  13018. if (pickResult.pickedMesh.actionManager) {
  13019. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  13020. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  13021. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  13022. }
  13023. }
  13024. }
  13025. if (_this._pickedDownMesh && _this._pickedDownMesh !== pickResult.pickedMesh) {
  13026. _this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(_this._pickedDownMesh, evt));
  13027. }
  13028. if (_this.onPointerUp) {
  13029. _this.onPointerUp(evt, pickResult);
  13030. }
  13031. _this._startingPointerTime = 0;
  13032. // Sprites
  13033. if (_this.spriteManagers.length > 0) {
  13034. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  13035. if (pickResult.hit && pickResult.pickedSprite) {
  13036. if (pickResult.pickedSprite.actionManager) {
  13037. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  13038. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  13039. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  13040. }
  13041. }
  13042. }
  13043. if (_this._pickedDownSprite && _this._pickedDownSprite !== pickResult.pickedSprite) {
  13044. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  13045. }
  13046. }
  13047. };
  13048. this._onKeyDown = function (evt) {
  13049. if (_this.actionManager) {
  13050. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  13051. }
  13052. };
  13053. this._onKeyUp = function (evt) {
  13054. if (_this.actionManager) {
  13055. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  13056. }
  13057. };
  13058. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  13059. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  13060. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  13061. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
  13062. // Wheel
  13063. this._engine.getRenderingCanvas().addEventListener('mousewheel', this._onPointerMove, false);
  13064. this._engine.getRenderingCanvas().addEventListener('DOMMouseScroll', this._onPointerMove, false);
  13065. BABYLON.Tools.RegisterTopRootEvents([
  13066. { name: "keydown", handler: this._onKeyDown },
  13067. { name: "keyup", handler: this._onKeyUp }
  13068. ]);
  13069. };
  13070. Scene.prototype.detachControl = function () {
  13071. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  13072. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  13073. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  13074. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
  13075. // Wheel
  13076. this._engine.getRenderingCanvas().removeEventListener('mousewheel', this._onPointerMove);
  13077. this._engine.getRenderingCanvas().removeEventListener('DOMMouseScroll', this._onPointerMove);
  13078. BABYLON.Tools.UnregisterTopRootEvents([
  13079. { name: "keydown", handler: this._onKeyDown },
  13080. { name: "keyup", handler: this._onKeyUp }
  13081. ]);
  13082. };
  13083. // Ready
  13084. Scene.prototype.isReady = function () {
  13085. if (this._pendingData.length > 0) {
  13086. return false;
  13087. }
  13088. var index;
  13089. for (index = 0; index < this._geometries.length; index++) {
  13090. var geometry = this._geometries[index];
  13091. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  13092. return false;
  13093. }
  13094. }
  13095. for (index = 0; index < this.meshes.length; index++) {
  13096. var mesh = this.meshes[index];
  13097. if (!mesh.isReady()) {
  13098. return false;
  13099. }
  13100. var mat = mesh.material;
  13101. if (mat) {
  13102. if (!mat.isReady(mesh)) {
  13103. return false;
  13104. }
  13105. }
  13106. }
  13107. return true;
  13108. };
  13109. Scene.prototype.resetCachedMaterial = function () {
  13110. this._cachedMaterial = null;
  13111. };
  13112. Scene.prototype.registerBeforeRender = function (func) {
  13113. this._onBeforeRenderCallbacks.push(func);
  13114. };
  13115. Scene.prototype.unregisterBeforeRender = function (func) {
  13116. var index = this._onBeforeRenderCallbacks.indexOf(func);
  13117. if (index > -1) {
  13118. this._onBeforeRenderCallbacks.splice(index, 1);
  13119. }
  13120. };
  13121. Scene.prototype.registerAfterRender = function (func) {
  13122. this._onAfterRenderCallbacks.push(func);
  13123. };
  13124. Scene.prototype.unregisterAfterRender = function (func) {
  13125. var index = this._onAfterRenderCallbacks.indexOf(func);
  13126. if (index > -1) {
  13127. this._onAfterRenderCallbacks.splice(index, 1);
  13128. }
  13129. };
  13130. Scene.prototype._addPendingData = function (data) {
  13131. this._pendingData.push(data);
  13132. };
  13133. Scene.prototype._removePendingData = function (data) {
  13134. var index = this._pendingData.indexOf(data);
  13135. if (index !== -1) {
  13136. this._pendingData.splice(index, 1);
  13137. }
  13138. };
  13139. Scene.prototype.getWaitingItemsCount = function () {
  13140. return this._pendingData.length;
  13141. };
  13142. /**
  13143. * Registers a function to be executed when the scene is ready.
  13144. * @param {Function} func - the function to be executed.
  13145. */
  13146. Scene.prototype.executeWhenReady = function (func) {
  13147. var _this = this;
  13148. this._onReadyCallbacks.push(func);
  13149. if (this._executeWhenReadyTimeoutId !== -1) {
  13150. return;
  13151. }
  13152. this._executeWhenReadyTimeoutId = setTimeout(function () {
  13153. _this._checkIsReady();
  13154. }, 150);
  13155. };
  13156. Scene.prototype._checkIsReady = function () {
  13157. var _this = this;
  13158. if (this.isReady()) {
  13159. this._onReadyCallbacks.forEach(function (func) {
  13160. func();
  13161. });
  13162. this._onReadyCallbacks = [];
  13163. this._executeWhenReadyTimeoutId = -1;
  13164. return;
  13165. }
  13166. this._executeWhenReadyTimeoutId = setTimeout(function () {
  13167. _this._checkIsReady();
  13168. }, 150);
  13169. };
  13170. // Animations
  13171. /**
  13172. * Will start the animation sequence of a given target
  13173. * @param target - the target
  13174. * @param {number} from - from which frame should animation start
  13175. * @param {number} to - till which frame should animation run.
  13176. * @param {boolean} [loop] - should the animation loop
  13177. * @param {number} [speedRatio] - the speed in which to run the animation
  13178. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  13179. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  13180. * @return {BABYLON.Animatable} the animatable object created for this animation
  13181. * @see BABYLON.Animatable
  13182. * @see http://doc.babylonjs.com/page.php?p=22081
  13183. */
  13184. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  13185. if (speedRatio === void 0) { speedRatio = 1.0; }
  13186. this.stopAnimation(target);
  13187. if (!animatable) {
  13188. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  13189. }
  13190. // Local animations
  13191. if (target.animations) {
  13192. animatable.appendAnimations(target, target.animations);
  13193. }
  13194. // Children animations
  13195. if (target.getAnimatables) {
  13196. var animatables = target.getAnimatables();
  13197. for (var index = 0; index < animatables.length; index++) {
  13198. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  13199. }
  13200. }
  13201. animatable.reset();
  13202. return animatable;
  13203. };
  13204. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  13205. if (speedRatio === undefined) {
  13206. speedRatio = 1.0;
  13207. }
  13208. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  13209. return animatable;
  13210. };
  13211. Scene.prototype.getAnimatableByTarget = function (target) {
  13212. for (var index = 0; index < this._activeAnimatables.length; index++) {
  13213. if (this._activeAnimatables[index].target === target) {
  13214. return this._activeAnimatables[index];
  13215. }
  13216. }
  13217. return null;
  13218. };
  13219. Object.defineProperty(Scene.prototype, "Animatables", {
  13220. get: function () {
  13221. return this._activeAnimatables;
  13222. },
  13223. enumerable: true,
  13224. configurable: true
  13225. });
  13226. /**
  13227. * Will stop the animation of the given target
  13228. * @param target - the target
  13229. * @see beginAnimation
  13230. */
  13231. Scene.prototype.stopAnimation = function (target) {
  13232. var animatable = this.getAnimatableByTarget(target);
  13233. if (animatable) {
  13234. animatable.stop();
  13235. }
  13236. };
  13237. Scene.prototype._animate = function () {
  13238. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  13239. return;
  13240. }
  13241. if (!this._animationStartDate) {
  13242. if (this._pendingData.length > 0) {
  13243. return;
  13244. }
  13245. this._animationStartDate = BABYLON.Tools.Now;
  13246. }
  13247. // Getting time
  13248. var now = BABYLON.Tools.Now;
  13249. var delay = now - this._animationStartDate;
  13250. for (var index = 0; index < this._activeAnimatables.length; index++) {
  13251. this._activeAnimatables[index]._animate(delay);
  13252. }
  13253. };
  13254. // Matrix
  13255. Scene.prototype.getViewMatrix = function () {
  13256. return this._viewMatrix;
  13257. };
  13258. Scene.prototype.getProjectionMatrix = function () {
  13259. return this._projectionMatrix;
  13260. };
  13261. Scene.prototype.getTransformMatrix = function () {
  13262. return this._transformMatrix;
  13263. };
  13264. Scene.prototype.setTransformMatrix = function (view, projection) {
  13265. this._viewMatrix = view;
  13266. this._projectionMatrix = projection;
  13267. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  13268. };
  13269. // Methods
  13270. Scene.prototype.addMesh = function (newMesh) {
  13271. newMesh.uniqueId = this._uniqueIdCounter++;
  13272. var position = this.meshes.push(newMesh);
  13273. //notify the collision coordinator
  13274. this.collisionCoordinator.onMeshAdded(newMesh);
  13275. if (this.onNewMeshAdded) {
  13276. this.onNewMeshAdded(newMesh, position, this);
  13277. }
  13278. };
  13279. Scene.prototype.removeMesh = function (toRemove) {
  13280. var index = this.meshes.indexOf(toRemove);
  13281. if (index !== -1) {
  13282. // Remove from the scene if mesh found
  13283. this.meshes.splice(index, 1);
  13284. }
  13285. //notify the collision coordinator
  13286. this.collisionCoordinator.onMeshRemoved(toRemove);
  13287. if (this.onMeshRemoved) {
  13288. this.onMeshRemoved(toRemove);
  13289. }
  13290. return index;
  13291. };
  13292. Scene.prototype.removeSkeleton = function (toRemove) {
  13293. var index = this.skeletons.indexOf(toRemove);
  13294. if (index !== -1) {
  13295. // Remove from the scene if mesh found
  13296. this.skeletons.splice(index, 1);
  13297. }
  13298. return index;
  13299. };
  13300. Scene.prototype.removeLight = function (toRemove) {
  13301. var index = this.lights.indexOf(toRemove);
  13302. if (index !== -1) {
  13303. // Remove from the scene if mesh found
  13304. this.lights.splice(index, 1);
  13305. }
  13306. if (this.onLightRemoved) {
  13307. this.onLightRemoved(toRemove);
  13308. }
  13309. return index;
  13310. };
  13311. Scene.prototype.removeCamera = function (toRemove) {
  13312. var index = this.cameras.indexOf(toRemove);
  13313. if (index !== -1) {
  13314. // Remove from the scene if mesh found
  13315. this.cameras.splice(index, 1);
  13316. }
  13317. // Remove from activeCameras
  13318. var index2 = this.activeCameras.indexOf(toRemove);
  13319. if (index2 !== -1) {
  13320. // Remove from the scene if mesh found
  13321. this.activeCameras.splice(index2, 1);
  13322. }
  13323. // Reset the activeCamera
  13324. if (this.activeCamera === toRemove) {
  13325. if (this.cameras.length > 0) {
  13326. this.activeCamera = this.cameras[0];
  13327. }
  13328. else {
  13329. this.activeCamera = null;
  13330. }
  13331. }
  13332. if (this.onCameraRemoved) {
  13333. this.onCameraRemoved(toRemove);
  13334. }
  13335. return index;
  13336. };
  13337. Scene.prototype.addLight = function (newLight) {
  13338. newLight.uniqueId = this._uniqueIdCounter++;
  13339. var position = this.lights.push(newLight);
  13340. if (this.onNewLightAdded) {
  13341. this.onNewLightAdded(newLight, position, this);
  13342. }
  13343. };
  13344. Scene.prototype.addCamera = function (newCamera) {
  13345. newCamera.uniqueId = this._uniqueIdCounter++;
  13346. var position = this.cameras.push(newCamera);
  13347. if (this.onNewCameraAdded) {
  13348. this.onNewCameraAdded(newCamera, position, this);
  13349. }
  13350. };
  13351. /**
  13352. * Switch active camera
  13353. * @param {Camera} newCamera - new active camera
  13354. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  13355. */
  13356. Scene.prototype.swithActiveCamera = function (newCamera, attachControl) {
  13357. if (attachControl === void 0) { attachControl = true; }
  13358. var canvas = this._engine.getRenderingCanvas();
  13359. this.activeCamera.detachControl(canvas);
  13360. this.activeCamera = newCamera;
  13361. if (attachControl) {
  13362. newCamera.attachControl(canvas);
  13363. }
  13364. };
  13365. /**
  13366. * sets the active camera of the scene using its ID
  13367. * @param {string} id - the camera's ID
  13368. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  13369. * @see activeCamera
  13370. */
  13371. Scene.prototype.setActiveCameraByID = function (id) {
  13372. var camera = this.getCameraByID(id);
  13373. if (camera) {
  13374. this.activeCamera = camera;
  13375. return camera;
  13376. }
  13377. return null;
  13378. };
  13379. /**
  13380. * sets the active camera of the scene using its name
  13381. * @param {string} name - the camera's name
  13382. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  13383. * @see activeCamera
  13384. */
  13385. Scene.prototype.setActiveCameraByName = function (name) {
  13386. var camera = this.getCameraByName(name);
  13387. if (camera) {
  13388. this.activeCamera = camera;
  13389. return camera;
  13390. }
  13391. return null;
  13392. };
  13393. /**
  13394. * get a material using its id
  13395. * @param {string} the material's ID
  13396. * @return {BABYLON.Material|null} the material or null if none found.
  13397. */
  13398. Scene.prototype.getMaterialByID = function (id) {
  13399. for (var index = 0; index < this.materials.length; index++) {
  13400. if (this.materials[index].id === id) {
  13401. return this.materials[index];
  13402. }
  13403. }
  13404. return null;
  13405. };
  13406. /**
  13407. * get a material using its name
  13408. * @param {string} the material's name
  13409. * @return {BABYLON.Material|null} the material or null if none found.
  13410. */
  13411. Scene.prototype.getMaterialByName = function (name) {
  13412. for (var index = 0; index < this.materials.length; index++) {
  13413. if (this.materials[index].name === name) {
  13414. return this.materials[index];
  13415. }
  13416. }
  13417. return null;
  13418. };
  13419. Scene.prototype.getLensFlareSystemByName = function (name) {
  13420. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  13421. if (this.lensFlareSystems[index].name === name) {
  13422. return this.lensFlareSystems[index];
  13423. }
  13424. }
  13425. return null;
  13426. };
  13427. Scene.prototype.getCameraByID = function (id) {
  13428. for (var index = 0; index < this.cameras.length; index++) {
  13429. if (this.cameras[index].id === id) {
  13430. return this.cameras[index];
  13431. }
  13432. }
  13433. return null;
  13434. };
  13435. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  13436. for (var index = 0; index < this.cameras.length; index++) {
  13437. if (this.cameras[index].uniqueId === uniqueId) {
  13438. return this.cameras[index];
  13439. }
  13440. }
  13441. return null;
  13442. };
  13443. /**
  13444. * get a camera using its name
  13445. * @param {string} the camera's name
  13446. * @return {BABYLON.Camera|null} the camera or null if none found.
  13447. */
  13448. Scene.prototype.getCameraByName = function (name) {
  13449. for (var index = 0; index < this.cameras.length; index++) {
  13450. if (this.cameras[index].name === name) {
  13451. return this.cameras[index];
  13452. }
  13453. }
  13454. return null;
  13455. };
  13456. /**
  13457. * get a bone using its id
  13458. * @param {string} the bone's id
  13459. * @return {BABYLON.Bone|null} the bone or null if not found
  13460. */
  13461. Scene.prototype.getBoneByID = function (id) {
  13462. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  13463. var skeleton = this.skeletons[skeletonIndex];
  13464. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  13465. if (skeleton.bones[boneIndex].id === id) {
  13466. return skeleton.bones[boneIndex];
  13467. }
  13468. }
  13469. }
  13470. return null;
  13471. };
  13472. /**
  13473. * get a bone using its id
  13474. * @param {string} the bone's name
  13475. * @return {BABYLON.Bone|null} the bone or null if not found
  13476. */
  13477. Scene.prototype.getBoneByName = function (name) {
  13478. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  13479. var skeleton = this.skeletons[skeletonIndex];
  13480. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  13481. if (skeleton.bones[boneIndex].name === name) {
  13482. return skeleton.bones[boneIndex];
  13483. }
  13484. }
  13485. }
  13486. return null;
  13487. };
  13488. /**
  13489. * get a light node using its name
  13490. * @param {string} the light's name
  13491. * @return {BABYLON.Light|null} the light or null if none found.
  13492. */
  13493. Scene.prototype.getLightByName = function (name) {
  13494. for (var index = 0; index < this.lights.length; index++) {
  13495. if (this.lights[index].name === name) {
  13496. return this.lights[index];
  13497. }
  13498. }
  13499. return null;
  13500. };
  13501. /**
  13502. * get a light node using its ID
  13503. * @param {string} the light's id
  13504. * @return {BABYLON.Light|null} the light or null if none found.
  13505. */
  13506. Scene.prototype.getLightByID = function (id) {
  13507. for (var index = 0; index < this.lights.length; index++) {
  13508. if (this.lights[index].id === id) {
  13509. return this.lights[index];
  13510. }
  13511. }
  13512. return null;
  13513. };
  13514. /**
  13515. * get a light node using its scene-generated unique ID
  13516. * @param {number} the light's unique id
  13517. * @return {BABYLON.Light|null} the light or null if none found.
  13518. */
  13519. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  13520. for (var index = 0; index < this.lights.length; index++) {
  13521. if (this.lights[index].uniqueId === uniqueId) {
  13522. return this.lights[index];
  13523. }
  13524. }
  13525. return null;
  13526. };
  13527. /**
  13528. * get a particle system by id
  13529. * @param id {number} the particle system id
  13530. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  13531. */
  13532. Scene.prototype.getParticleSystemByID = function (id) {
  13533. for (var index = 0; index < this.particleSystems.length; index++) {
  13534. if (this.particleSystems[index].id === id) {
  13535. return this.particleSystems[index];
  13536. }
  13537. }
  13538. return null;
  13539. };
  13540. /**
  13541. * get a geometry using its ID
  13542. * @param {string} the geometry's id
  13543. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  13544. */
  13545. Scene.prototype.getGeometryByID = function (id) {
  13546. for (var index = 0; index < this._geometries.length; index++) {
  13547. if (this._geometries[index].id === id) {
  13548. return this._geometries[index];
  13549. }
  13550. }
  13551. return null;
  13552. };
  13553. /**
  13554. * add a new geometry to this scene.
  13555. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  13556. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  13557. * @return {boolean} was the geometry added or not
  13558. */
  13559. Scene.prototype.pushGeometry = function (geometry, force) {
  13560. if (!force && this.getGeometryByID(geometry.id)) {
  13561. return false;
  13562. }
  13563. this._geometries.push(geometry);
  13564. //notify the collision coordinator
  13565. this.collisionCoordinator.onGeometryAdded(geometry);
  13566. if (this.onGeometryAdded) {
  13567. this.onGeometryAdded(geometry);
  13568. }
  13569. return true;
  13570. };
  13571. /**
  13572. * Removes an existing geometry
  13573. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  13574. * @return {boolean} was the geometry removed or not
  13575. */
  13576. Scene.prototype.removeGeometry = function (geometry) {
  13577. var index = this._geometries.indexOf(geometry);
  13578. if (index > -1) {
  13579. this._geometries.splice(index, 1);
  13580. //notify the collision coordinator
  13581. this.collisionCoordinator.onGeometryDeleted(geometry);
  13582. if (this.onGeometryRemoved) {
  13583. this.onGeometryRemoved(geometry);
  13584. }
  13585. return true;
  13586. }
  13587. return false;
  13588. };
  13589. Scene.prototype.getGeometries = function () {
  13590. return this._geometries;
  13591. };
  13592. /**
  13593. * Get the first added mesh found of a given ID
  13594. * @param {string} id - the id to search for
  13595. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  13596. */
  13597. Scene.prototype.getMeshByID = function (id) {
  13598. for (var index = 0; index < this.meshes.length; index++) {
  13599. if (this.meshes[index].id === id) {
  13600. return this.meshes[index];
  13601. }
  13602. }
  13603. return null;
  13604. };
  13605. /**
  13606. * Get a mesh with its auto-generated unique id
  13607. * @param {number} uniqueId - the unique id to search for
  13608. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  13609. */
  13610. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  13611. for (var index = 0; index < this.meshes.length; index++) {
  13612. if (this.meshes[index].uniqueId === uniqueId) {
  13613. return this.meshes[index];
  13614. }
  13615. }
  13616. return null;
  13617. };
  13618. /**
  13619. * Get a the last added mesh found of a given ID
  13620. * @param {string} id - the id to search for
  13621. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  13622. */
  13623. Scene.prototype.getLastMeshByID = function (id) {
  13624. for (var index = this.meshes.length - 1; index >= 0; index--) {
  13625. if (this.meshes[index].id === id) {
  13626. return this.meshes[index];
  13627. }
  13628. }
  13629. return null;
  13630. };
  13631. /**
  13632. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  13633. * @param {string} id - the id to search for
  13634. * @return {BABYLON.Node|null} the node found or null if not found at all.
  13635. */
  13636. Scene.prototype.getLastEntryByID = function (id) {
  13637. var index;
  13638. for (index = this.meshes.length - 1; index >= 0; index--) {
  13639. if (this.meshes[index].id === id) {
  13640. return this.meshes[index];
  13641. }
  13642. }
  13643. for (index = this.cameras.length - 1; index >= 0; index--) {
  13644. if (this.cameras[index].id === id) {
  13645. return this.cameras[index];
  13646. }
  13647. }
  13648. for (index = this.lights.length - 1; index >= 0; index--) {
  13649. if (this.lights[index].id === id) {
  13650. return this.lights[index];
  13651. }
  13652. }
  13653. return null;
  13654. };
  13655. Scene.prototype.getNodeByID = function (id) {
  13656. var mesh = this.getMeshByID(id);
  13657. if (mesh) {
  13658. return mesh;
  13659. }
  13660. var light = this.getLightByID(id);
  13661. if (light) {
  13662. return light;
  13663. }
  13664. var camera = this.getCameraByID(id);
  13665. if (camera) {
  13666. return camera;
  13667. }
  13668. var bone = this.getBoneByID(id);
  13669. return bone;
  13670. };
  13671. Scene.prototype.getNodeByName = function (name) {
  13672. var mesh = this.getMeshByName(name);
  13673. if (mesh) {
  13674. return mesh;
  13675. }
  13676. var light = this.getLightByName(name);
  13677. if (light) {
  13678. return light;
  13679. }
  13680. var camera = this.getCameraByName(name);
  13681. if (camera) {
  13682. return camera;
  13683. }
  13684. var bone = this.getBoneByName(name);
  13685. return bone;
  13686. };
  13687. Scene.prototype.getMeshByName = function (name) {
  13688. for (var index = 0; index < this.meshes.length; index++) {
  13689. if (this.meshes[index].name === name) {
  13690. return this.meshes[index];
  13691. }
  13692. }
  13693. return null;
  13694. };
  13695. Scene.prototype.getSoundByName = function (name) {
  13696. var index;
  13697. if (BABYLON.AudioEngine) {
  13698. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  13699. if (this.mainSoundTrack.soundCollection[index].name === name) {
  13700. return this.mainSoundTrack.soundCollection[index];
  13701. }
  13702. }
  13703. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  13704. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  13705. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  13706. return this.soundTracks[sdIndex].soundCollection[index];
  13707. }
  13708. }
  13709. }
  13710. }
  13711. return null;
  13712. };
  13713. Scene.prototype.getLastSkeletonByID = function (id) {
  13714. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  13715. if (this.skeletons[index].id === id) {
  13716. return this.skeletons[index];
  13717. }
  13718. }
  13719. return null;
  13720. };
  13721. Scene.prototype.getSkeletonById = function (id) {
  13722. for (var index = 0; index < this.skeletons.length; index++) {
  13723. if (this.skeletons[index].id === id) {
  13724. return this.skeletons[index];
  13725. }
  13726. }
  13727. return null;
  13728. };
  13729. Scene.prototype.getSkeletonByName = function (name) {
  13730. for (var index = 0; index < this.skeletons.length; index++) {
  13731. if (this.skeletons[index].name === name) {
  13732. return this.skeletons[index];
  13733. }
  13734. }
  13735. return null;
  13736. };
  13737. Scene.prototype.isActiveMesh = function (mesh) {
  13738. return (this._activeMeshes.indexOf(mesh) !== -1);
  13739. };
  13740. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  13741. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  13742. var material = subMesh.getMaterial();
  13743. if (mesh.showSubMeshesBoundingBox) {
  13744. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  13745. }
  13746. if (material) {
  13747. // Render targets
  13748. if (material.getRenderTargetTextures) {
  13749. if (this._processedMaterials.indexOf(material) === -1) {
  13750. this._processedMaterials.push(material);
  13751. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  13752. }
  13753. }
  13754. // Dispatch
  13755. this._activeIndices += subMesh.indexCount;
  13756. this._renderingManager.dispatch(subMesh);
  13757. }
  13758. }
  13759. };
  13760. Scene.prototype._evaluateActiveMeshes = function () {
  13761. this.activeCamera._activeMeshes.reset();
  13762. this._activeMeshes.reset();
  13763. this._renderingManager.reset();
  13764. this._processedMaterials.reset();
  13765. this._activeParticleSystems.reset();
  13766. this._activeSkeletons.reset();
  13767. this._softwareSkinnedMeshes.reset();
  13768. this._boundingBoxRenderer.reset();
  13769. this._edgesRenderers.reset();
  13770. if (!this._frustumPlanes) {
  13771. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  13772. }
  13773. else {
  13774. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  13775. }
  13776. // Meshes
  13777. var meshes;
  13778. var len;
  13779. if (this._selectionOctree) {
  13780. var selection = this._selectionOctree.select(this._frustumPlanes);
  13781. meshes = selection.data;
  13782. len = selection.length;
  13783. }
  13784. else {
  13785. len = this.meshes.length;
  13786. meshes = this.meshes;
  13787. }
  13788. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  13789. var mesh = meshes[meshIndex];
  13790. if (mesh.isBlocked) {
  13791. continue;
  13792. }
  13793. this._totalVertices += mesh.getTotalVertices();
  13794. if (!mesh.isReady() || !mesh.isEnabled()) {
  13795. continue;
  13796. }
  13797. mesh.computeWorldMatrix();
  13798. // Intersections
  13799. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  13800. this._meshesForIntersections.pushNoDuplicate(mesh);
  13801. }
  13802. // Switch to current LOD
  13803. var meshLOD = mesh.getLOD(this.activeCamera);
  13804. if (!meshLOD) {
  13805. continue;
  13806. }
  13807. mesh._preActivate();
  13808. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  13809. this._activeMeshes.push(mesh);
  13810. this.activeCamera._activeMeshes.push(mesh);
  13811. mesh._activate(this._renderId);
  13812. this._activeMesh(meshLOD);
  13813. }
  13814. }
  13815. // Particle systems
  13816. var beforeParticlesDate = BABYLON.Tools.Now;
  13817. if (this.particlesEnabled) {
  13818. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  13819. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  13820. var particleSystem = this.particleSystems[particleIndex];
  13821. if (!particleSystem.isStarted()) {
  13822. continue;
  13823. }
  13824. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  13825. this._activeParticleSystems.push(particleSystem);
  13826. particleSystem.animate();
  13827. }
  13828. }
  13829. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  13830. }
  13831. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  13832. };
  13833. Scene.prototype._activeMesh = function (mesh) {
  13834. if (mesh.skeleton && this.skeletonsEnabled) {
  13835. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  13836. if (!mesh.computeBonesUsingShaders) {
  13837. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  13838. }
  13839. }
  13840. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  13841. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  13842. }
  13843. if (mesh._edgesRenderer) {
  13844. this._edgesRenderers.push(mesh._edgesRenderer);
  13845. }
  13846. if (mesh && mesh.subMeshes) {
  13847. // Submeshes Octrees
  13848. var len;
  13849. var subMeshes;
  13850. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  13851. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  13852. len = intersections.length;
  13853. subMeshes = intersections.data;
  13854. }
  13855. else {
  13856. subMeshes = mesh.subMeshes;
  13857. len = subMeshes.length;
  13858. }
  13859. for (var subIndex = 0; subIndex < len; subIndex++) {
  13860. var subMesh = subMeshes[subIndex];
  13861. this._evaluateSubMesh(subMesh, mesh);
  13862. }
  13863. }
  13864. };
  13865. Scene.prototype.updateTransformMatrix = function (force) {
  13866. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  13867. };
  13868. Scene.prototype._renderForCamera = function (camera) {
  13869. var engine = this._engine;
  13870. this.activeCamera = camera;
  13871. if (!this.activeCamera)
  13872. throw new Error("Active camera not set");
  13873. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13874. // Viewport
  13875. engine.setViewport(this.activeCamera.viewport);
  13876. // Camera
  13877. this.resetCachedMaterial();
  13878. this._renderId++;
  13879. this.updateTransformMatrix();
  13880. if (this.beforeCameraRender) {
  13881. this.beforeCameraRender(this.activeCamera);
  13882. }
  13883. // Meshes
  13884. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  13885. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  13886. this._evaluateActiveMeshes();
  13887. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  13888. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  13889. // Skeletons
  13890. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  13891. var skeleton = this._activeSkeletons.data[skeletonIndex];
  13892. skeleton.prepare();
  13893. }
  13894. // Software skinning
  13895. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  13896. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  13897. mesh.applySkeleton(mesh.skeleton);
  13898. }
  13899. // Render targets
  13900. var beforeRenderTargetDate = BABYLON.Tools.Now;
  13901. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  13902. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13903. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  13904. var renderTarget = this._renderTargets.data[renderIndex];
  13905. if (renderTarget._shouldRender()) {
  13906. this._renderId++;
  13907. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  13908. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  13909. }
  13910. }
  13911. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13912. this._renderId++;
  13913. engine.restoreDefaultFramebuffer(); // Restore back buffer
  13914. }
  13915. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  13916. // Prepare Frame
  13917. this.postProcessManager._prepareFrame();
  13918. var beforeRenderDate = BABYLON.Tools.Now;
  13919. // Backgrounds
  13920. var layerIndex;
  13921. var layer;
  13922. if (this.layers.length) {
  13923. engine.setDepthBuffer(false);
  13924. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13925. layer = this.layers[layerIndex];
  13926. if (layer.isBackground) {
  13927. layer.render();
  13928. }
  13929. }
  13930. engine.setDepthBuffer(true);
  13931. }
  13932. // Render
  13933. BABYLON.Tools.StartPerformanceCounter("Main render");
  13934. this._renderingManager.render(null, null, true, true);
  13935. BABYLON.Tools.EndPerformanceCounter("Main render");
  13936. // Bounding boxes
  13937. this._boundingBoxRenderer.render();
  13938. // Edges
  13939. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  13940. this._edgesRenderers.data[edgesRendererIndex].render();
  13941. }
  13942. // Lens flares
  13943. if (this.lensFlaresEnabled) {
  13944. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13945. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  13946. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  13947. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  13948. lensFlareSystem.render();
  13949. }
  13950. }
  13951. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13952. }
  13953. // Foregrounds
  13954. if (this.layers.length) {
  13955. engine.setDepthBuffer(false);
  13956. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13957. layer = this.layers[layerIndex];
  13958. if (!layer.isBackground) {
  13959. layer.render();
  13960. }
  13961. }
  13962. engine.setDepthBuffer(true);
  13963. }
  13964. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  13965. // Finalize frame
  13966. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  13967. // Update camera
  13968. this.activeCamera._updateFromScene();
  13969. // Reset some special arrays
  13970. this._renderTargets.reset();
  13971. if (this.afterCameraRender) {
  13972. this.afterCameraRender(this.activeCamera);
  13973. }
  13974. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13975. };
  13976. Scene.prototype._processSubCameras = function (camera) {
  13977. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  13978. this._renderForCamera(camera);
  13979. return;
  13980. }
  13981. // rig cameras
  13982. for (var index = 0; index < camera._rigCameras.length; index++) {
  13983. this._renderForCamera(camera._rigCameras[index]);
  13984. }
  13985. this.activeCamera = camera;
  13986. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  13987. // Update camera
  13988. this.activeCamera._updateFromScene();
  13989. };
  13990. Scene.prototype._checkIntersections = function () {
  13991. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  13992. var sourceMesh = this._meshesForIntersections.data[index];
  13993. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  13994. var action = sourceMesh.actionManager.actions[actionIndex];
  13995. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13996. var parameters = action.getTriggerParameter();
  13997. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  13998. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  13999. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  14000. if (areIntersecting && currentIntersectionInProgress === -1) {
  14001. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  14002. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  14003. sourceMesh._intersectionsInProgress.push(otherMesh);
  14004. }
  14005. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  14006. sourceMesh._intersectionsInProgress.push(otherMesh);
  14007. }
  14008. }
  14009. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  14010. //They intersected, and now they don't.
  14011. //is this trigger an exit trigger? execute an event.
  14012. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  14013. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  14014. }
  14015. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  14016. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  14017. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  14018. }
  14019. }
  14020. }
  14021. }
  14022. }
  14023. };
  14024. Scene.prototype.render = function () {
  14025. var startDate = BABYLON.Tools.Now;
  14026. this._particlesDuration = 0;
  14027. this._spritesDuration = 0;
  14028. this._activeParticles = 0;
  14029. this._renderDuration = 0;
  14030. this._renderTargetsDuration = 0;
  14031. this._evaluateActiveMeshesDuration = 0;
  14032. this._totalVertices = 0;
  14033. this._activeIndices = 0;
  14034. this._activeBones = 0;
  14035. this.getEngine().resetDrawCalls();
  14036. this._meshesForIntersections.reset();
  14037. this.resetCachedMaterial();
  14038. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  14039. // Actions
  14040. if (this.actionManager) {
  14041. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  14042. }
  14043. //Simplification Queue
  14044. if (this.simplificationQueue && !this.simplificationQueue.running) {
  14045. this.simplificationQueue.executeNext();
  14046. }
  14047. // Animations
  14048. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  14049. this._animationRatio = deltaTime * (60.0 / 1000.0);
  14050. this._animate();
  14051. // Physics
  14052. if (this._physicsEngine) {
  14053. BABYLON.Tools.StartPerformanceCounter("Physics");
  14054. this._physicsEngine._step(deltaTime / 1000.0);
  14055. BABYLON.Tools.EndPerformanceCounter("Physics");
  14056. }
  14057. // Before render
  14058. if (this.beforeRender) {
  14059. this.beforeRender();
  14060. }
  14061. var callbackIndex;
  14062. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  14063. this._onBeforeRenderCallbacks[callbackIndex]();
  14064. }
  14065. // Customs render targets
  14066. var beforeRenderTargetDate = BABYLON.Tools.Now;
  14067. var engine = this.getEngine();
  14068. var currentActiveCamera = this.activeCamera;
  14069. if (this.renderTargetsEnabled) {
  14070. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  14071. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  14072. var renderTarget = this.customRenderTargets[customIndex];
  14073. if (renderTarget._shouldRender()) {
  14074. this._renderId++;
  14075. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  14076. if (!this.activeCamera)
  14077. throw new Error("Active camera not set");
  14078. // Viewport
  14079. engine.setViewport(this.activeCamera.viewport);
  14080. // Camera
  14081. this.updateTransformMatrix();
  14082. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  14083. }
  14084. }
  14085. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  14086. this._renderId++;
  14087. }
  14088. if (this.customRenderTargets.length > 0) {
  14089. engine.restoreDefaultFramebuffer();
  14090. }
  14091. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  14092. this.activeCamera = currentActiveCamera;
  14093. // Procedural textures
  14094. if (this.proceduralTexturesEnabled) {
  14095. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  14096. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  14097. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  14098. if (proceduralTexture._shouldRender()) {
  14099. proceduralTexture.render();
  14100. }
  14101. }
  14102. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  14103. }
  14104. // Clear
  14105. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  14106. // Shadows
  14107. if (this.shadowsEnabled) {
  14108. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  14109. var light = this.lights[lightIndex];
  14110. var shadowGenerator = light.getShadowGenerator();
  14111. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  14112. this._renderTargets.push(shadowGenerator.getShadowMap());
  14113. }
  14114. }
  14115. }
  14116. // Depth renderer
  14117. if (this._depthRenderer) {
  14118. this._renderTargets.push(this._depthRenderer.getDepthMap());
  14119. }
  14120. // RenderPipeline
  14121. this.postProcessRenderPipelineManager.update();
  14122. // Multi-cameras?
  14123. if (this.activeCameras.length > 0) {
  14124. var currentRenderId = this._renderId;
  14125. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  14126. this._renderId = currentRenderId;
  14127. if (cameraIndex > 0) {
  14128. this._engine.clear(0, false, true);
  14129. }
  14130. this._processSubCameras(this.activeCameras[cameraIndex]);
  14131. }
  14132. }
  14133. else {
  14134. if (!this.activeCamera) {
  14135. throw new Error("No camera defined");
  14136. }
  14137. this._processSubCameras(this.activeCamera);
  14138. }
  14139. // Intersection checks
  14140. this._checkIntersections();
  14141. // Update the audio listener attached to the camera
  14142. if (BABYLON.AudioEngine) {
  14143. this._updateAudioParameters();
  14144. }
  14145. // After render
  14146. if (this.afterRender) {
  14147. this.afterRender();
  14148. }
  14149. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  14150. this._onAfterRenderCallbacks[callbackIndex]();
  14151. }
  14152. // Cleaning
  14153. for (var index = 0; index < this._toBeDisposed.length; index++) {
  14154. this._toBeDisposed.data[index].dispose();
  14155. this._toBeDisposed[index] = null;
  14156. }
  14157. this._toBeDisposed.reset();
  14158. if (this.dumpNextRenderTargets) {
  14159. this.dumpNextRenderTargets = false;
  14160. }
  14161. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  14162. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  14163. };
  14164. Scene.prototype._updateAudioParameters = function () {
  14165. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  14166. return;
  14167. }
  14168. var listeningCamera;
  14169. var audioEngine = BABYLON.Engine.audioEngine;
  14170. if (this.activeCameras.length > 0) {
  14171. listeningCamera = this.activeCameras[0];
  14172. }
  14173. else {
  14174. listeningCamera = this.activeCamera;
  14175. }
  14176. if (listeningCamera && audioEngine.canUseWebAudio) {
  14177. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  14178. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  14179. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  14180. cameraDirection.normalize();
  14181. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  14182. var i;
  14183. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  14184. var sound = this.mainSoundTrack.soundCollection[i];
  14185. if (sound.useCustomAttenuation) {
  14186. sound.updateDistanceFromListener();
  14187. }
  14188. }
  14189. for (i = 0; i < this.soundTracks.length; i++) {
  14190. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  14191. sound = this.soundTracks[i].soundCollection[j];
  14192. if (sound.useCustomAttenuation) {
  14193. sound.updateDistanceFromListener();
  14194. }
  14195. }
  14196. }
  14197. }
  14198. };
  14199. Object.defineProperty(Scene.prototype, "audioEnabled", {
  14200. // Audio
  14201. get: function () {
  14202. return this._audioEnabled;
  14203. },
  14204. set: function (value) {
  14205. this._audioEnabled = value;
  14206. if (BABYLON.AudioEngine) {
  14207. if (this._audioEnabled) {
  14208. this._enableAudio();
  14209. }
  14210. else {
  14211. this._disableAudio();
  14212. }
  14213. }
  14214. },
  14215. enumerable: true,
  14216. configurable: true
  14217. });
  14218. Scene.prototype._disableAudio = function () {
  14219. var i;
  14220. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  14221. this.mainSoundTrack.soundCollection[i].pause();
  14222. }
  14223. for (i = 0; i < this.soundTracks.length; i++) {
  14224. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  14225. this.soundTracks[i].soundCollection[j].pause();
  14226. }
  14227. }
  14228. };
  14229. Scene.prototype._enableAudio = function () {
  14230. var i;
  14231. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  14232. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  14233. this.mainSoundTrack.soundCollection[i].play();
  14234. }
  14235. }
  14236. for (i = 0; i < this.soundTracks.length; i++) {
  14237. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  14238. if (this.soundTracks[i].soundCollection[j].isPaused) {
  14239. this.soundTracks[i].soundCollection[j].play();
  14240. }
  14241. }
  14242. }
  14243. };
  14244. Object.defineProperty(Scene.prototype, "headphone", {
  14245. get: function () {
  14246. return this._headphone;
  14247. },
  14248. set: function (value) {
  14249. this._headphone = value;
  14250. if (BABYLON.AudioEngine) {
  14251. if (this._headphone) {
  14252. this._switchAudioModeForHeadphones();
  14253. }
  14254. else {
  14255. this._switchAudioModeForNormalSpeakers();
  14256. }
  14257. }
  14258. },
  14259. enumerable: true,
  14260. configurable: true
  14261. });
  14262. Scene.prototype._switchAudioModeForHeadphones = function () {
  14263. this.mainSoundTrack.switchPanningModelToHRTF();
  14264. for (var i = 0; i < this.soundTracks.length; i++) {
  14265. this.soundTracks[i].switchPanningModelToHRTF();
  14266. }
  14267. };
  14268. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  14269. this.mainSoundTrack.switchPanningModelToEqualPower();
  14270. for (var i = 0; i < this.soundTracks.length; i++) {
  14271. this.soundTracks[i].switchPanningModelToEqualPower();
  14272. }
  14273. };
  14274. Scene.prototype.enableDepthRenderer = function () {
  14275. if (this._depthRenderer) {
  14276. return this._depthRenderer;
  14277. }
  14278. this._depthRenderer = new BABYLON.DepthRenderer(this);
  14279. return this._depthRenderer;
  14280. };
  14281. Scene.prototype.disableDepthRenderer = function () {
  14282. if (!this._depthRenderer) {
  14283. return;
  14284. }
  14285. this._depthRenderer.dispose();
  14286. this._depthRenderer = null;
  14287. };
  14288. Scene.prototype.freezeMaterials = function () {
  14289. for (var i = 0; i < this.materials.length; i++) {
  14290. this.materials[i].freeze();
  14291. }
  14292. };
  14293. Scene.prototype.unfreezeMaterials = function () {
  14294. for (var i = 0; i < this.materials.length; i++) {
  14295. this.materials[i].unfreeze();
  14296. }
  14297. };
  14298. Scene.prototype.dispose = function () {
  14299. this.beforeRender = null;
  14300. this.afterRender = null;
  14301. this.skeletons = [];
  14302. this._boundingBoxRenderer.dispose();
  14303. if (this._depthRenderer) {
  14304. this._depthRenderer.dispose();
  14305. }
  14306. // Debug layer
  14307. this.debugLayer.hide();
  14308. // Events
  14309. if (this.onDispose) {
  14310. this.onDispose();
  14311. }
  14312. this._onBeforeRenderCallbacks = [];
  14313. this._onAfterRenderCallbacks = [];
  14314. this.detachControl();
  14315. // Release sounds & sounds tracks
  14316. if (BABYLON.AudioEngine) {
  14317. this.disposeSounds();
  14318. }
  14319. // Detach cameras
  14320. var canvas = this._engine.getRenderingCanvas();
  14321. var index;
  14322. for (index = 0; index < this.cameras.length; index++) {
  14323. this.cameras[index].detachControl(canvas);
  14324. }
  14325. // Release lights
  14326. while (this.lights.length) {
  14327. this.lights[0].dispose();
  14328. }
  14329. // Release meshes
  14330. while (this.meshes.length) {
  14331. this.meshes[0].dispose(true);
  14332. }
  14333. // Release cameras
  14334. while (this.cameras.length) {
  14335. this.cameras[0].dispose();
  14336. }
  14337. // Release materials
  14338. while (this.materials.length) {
  14339. this.materials[0].dispose();
  14340. }
  14341. // Release particles
  14342. while (this.particleSystems.length) {
  14343. this.particleSystems[0].dispose();
  14344. }
  14345. // Release sprites
  14346. while (this.spriteManagers.length) {
  14347. this.spriteManagers[0].dispose();
  14348. }
  14349. // Release layers
  14350. while (this.layers.length) {
  14351. this.layers[0].dispose();
  14352. }
  14353. // Release textures
  14354. while (this.textures.length) {
  14355. this.textures[0].dispose();
  14356. }
  14357. // Post-processes
  14358. this.postProcessManager.dispose();
  14359. // Physics
  14360. if (this._physicsEngine) {
  14361. this.disablePhysicsEngine();
  14362. }
  14363. // Remove from engine
  14364. index = this._engine.scenes.indexOf(this);
  14365. if (index > -1) {
  14366. this._engine.scenes.splice(index, 1);
  14367. }
  14368. this._engine.wipeCaches();
  14369. };
  14370. // Release sounds & sounds tracks
  14371. Scene.prototype.disposeSounds = function () {
  14372. this.mainSoundTrack.dispose();
  14373. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  14374. this.soundTracks[scIndex].dispose();
  14375. }
  14376. };
  14377. // Octrees
  14378. Scene.prototype.getWorldExtends = function () {
  14379. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14380. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  14381. for (var index = 0; index < this.meshes.length; index++) {
  14382. var mesh = this.meshes[index];
  14383. mesh.computeWorldMatrix(true);
  14384. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  14385. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  14386. BABYLON.Tools.CheckExtends(minBox, min, max);
  14387. BABYLON.Tools.CheckExtends(maxBox, min, max);
  14388. }
  14389. return {
  14390. min: min,
  14391. max: max
  14392. };
  14393. };
  14394. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  14395. if (maxCapacity === void 0) { maxCapacity = 64; }
  14396. if (maxDepth === void 0) { maxDepth = 2; }
  14397. if (!this._selectionOctree) {
  14398. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  14399. }
  14400. var worldExtends = this.getWorldExtends();
  14401. // Update octree
  14402. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  14403. return this._selectionOctree;
  14404. };
  14405. // Picking
  14406. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  14407. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  14408. var engine = this._engine;
  14409. if (!camera) {
  14410. if (!this.activeCamera)
  14411. throw new Error("Active camera not set");
  14412. camera = this.activeCamera;
  14413. }
  14414. var cameraViewport = camera.viewport;
  14415. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  14416. // Moving coordinates to local viewport world
  14417. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  14418. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  14419. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  14420. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  14421. };
  14422. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  14423. var engine = this._engine;
  14424. if (!camera) {
  14425. if (!this.activeCamera)
  14426. throw new Error("Active camera not set");
  14427. camera = this.activeCamera;
  14428. }
  14429. var cameraViewport = camera.viewport;
  14430. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  14431. var identity = BABYLON.Matrix.Identity();
  14432. // Moving coordinates to local viewport world
  14433. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  14434. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  14435. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  14436. };
  14437. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  14438. var pickingInfo = null;
  14439. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  14440. var mesh = this.meshes[meshIndex];
  14441. if (predicate) {
  14442. if (!predicate(mesh)) {
  14443. continue;
  14444. }
  14445. }
  14446. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  14447. continue;
  14448. }
  14449. var world = mesh.getWorldMatrix();
  14450. var ray = rayFunction(world);
  14451. var result = mesh.intersects(ray, fastCheck);
  14452. if (!result || !result.hit)
  14453. continue;
  14454. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  14455. continue;
  14456. pickingInfo = result;
  14457. if (fastCheck) {
  14458. break;
  14459. }
  14460. }
  14461. return pickingInfo || new BABYLON.PickingInfo();
  14462. };
  14463. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  14464. var pickingInfo = null;
  14465. camera = camera || this.activeCamera;
  14466. if (this.spriteManagers.length > 0) {
  14467. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  14468. var spriteManager = this.spriteManagers[spriteIndex];
  14469. if (!spriteManager.isPickable) {
  14470. continue;
  14471. }
  14472. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  14473. if (!result || !result.hit)
  14474. continue;
  14475. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  14476. continue;
  14477. pickingInfo = result;
  14478. if (fastCheck) {
  14479. break;
  14480. }
  14481. }
  14482. }
  14483. return pickingInfo || new BABYLON.PickingInfo();
  14484. };
  14485. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  14486. var _this = this;
  14487. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  14488. /// <param name="x">X position on screen</param>
  14489. /// <param name="y">Y position on screen</param>
  14490. /// <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>
  14491. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  14492. /// <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>
  14493. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  14494. };
  14495. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  14496. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  14497. /// <param name="x">X position on screen</param>
  14498. /// <param name="y">Y position on screen</param>
  14499. /// <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>
  14500. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  14501. /// <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>
  14502. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  14503. };
  14504. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  14505. var _this = this;
  14506. return this._internalPick(function (world) {
  14507. if (!_this._pickWithRayInverseMatrix) {
  14508. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  14509. }
  14510. world.invertToRef(_this._pickWithRayInverseMatrix);
  14511. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  14512. }, predicate, fastCheck);
  14513. };
  14514. Scene.prototype.setPointerOverMesh = function (mesh) {
  14515. if (this._pointerOverMesh === mesh) {
  14516. return;
  14517. }
  14518. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  14519. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  14520. }
  14521. this._pointerOverMesh = mesh;
  14522. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  14523. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  14524. }
  14525. };
  14526. Scene.prototype.getPointerOverMesh = function () {
  14527. return this._pointerOverMesh;
  14528. };
  14529. Scene.prototype.setPointerOverSprite = function (sprite) {
  14530. if (this._pointerOverSprite === sprite) {
  14531. return;
  14532. }
  14533. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  14534. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  14535. }
  14536. this._pointerOverSprite = sprite;
  14537. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  14538. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  14539. }
  14540. };
  14541. Scene.prototype.getPointerOverSprite = function () {
  14542. return this._pointerOverSprite;
  14543. };
  14544. // Physics
  14545. Scene.prototype.getPhysicsEngine = function () {
  14546. return this._physicsEngine;
  14547. };
  14548. /**
  14549. * Enables physics to the current scene
  14550. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  14551. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  14552. * @return {boolean} was the physics engine initialized
  14553. */
  14554. Scene.prototype.enablePhysics = function (gravity, plugin) {
  14555. if (this._physicsEngine) {
  14556. return true;
  14557. }
  14558. try {
  14559. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  14560. return true;
  14561. }
  14562. catch (e) {
  14563. BABYLON.Tools.Error(e.message);
  14564. return false;
  14565. }
  14566. };
  14567. Scene.prototype.disablePhysicsEngine = function () {
  14568. if (!this._physicsEngine) {
  14569. return;
  14570. }
  14571. this._physicsEngine.dispose();
  14572. this._physicsEngine = undefined;
  14573. };
  14574. Scene.prototype.isPhysicsEnabled = function () {
  14575. return this._physicsEngine !== undefined;
  14576. };
  14577. /**
  14578. *
  14579. * Sets the gravity of the physics engine (and NOT of the scene)
  14580. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  14581. */
  14582. Scene.prototype.setGravity = function (gravity) {
  14583. BABYLON.Tools.Warn("Deprecated, please use 'scene.getPhysicsEngine().setGravity()'");
  14584. if (!this._physicsEngine) {
  14585. return;
  14586. }
  14587. this._physicsEngine.setGravity(gravity);
  14588. };
  14589. /**
  14590. * Legacy support, using the new API
  14591. * @Deprecated
  14592. */
  14593. Scene.prototype.createCompoundImpostor = function (parts, options) {
  14594. BABYLON.Tools.Warn("Scene.createCompoundImpostor is deprecated. Please use PhysicsImpostor parent/child");
  14595. if (parts.parts) {
  14596. options = parts;
  14597. parts = parts.parts;
  14598. }
  14599. var mainMesh = parts[0].mesh;
  14600. mainMesh.physicsImpostor = new BABYLON.PhysicsImpostor(mainMesh, parts[0].impostor, options);
  14601. for (var index = 1; index < parts.length; index++) {
  14602. var mesh = parts[index].mesh;
  14603. if (mesh.parent !== mainMesh) {
  14604. mesh.position = mesh.position.subtract(mainMesh.position);
  14605. mesh.parent = mainMesh;
  14606. }
  14607. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parts[index].impostor, options);
  14608. }
  14609. mainMesh.physicsImpostor.forceUpdate();
  14610. };
  14611. Scene.prototype.deleteCompoundImpostor = function (compound) {
  14612. var mesh = compound.parts[0].mesh;
  14613. mesh.physicsImpostor.dispose(true);
  14614. mesh.physicsImpostor = null;
  14615. };
  14616. // Misc.
  14617. Scene.prototype.createDefaultCameraOrLight = function () {
  14618. // Light
  14619. if (this.lights.length === 0) {
  14620. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  14621. }
  14622. // Camera
  14623. if (!this.activeCamera) {
  14624. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  14625. // Compute position
  14626. var worldExtends = this.getWorldExtends();
  14627. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  14628. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  14629. camera.setTarget(worldCenter);
  14630. this.activeCamera = camera;
  14631. }
  14632. };
  14633. // Tags
  14634. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  14635. if (tagsQuery === undefined) {
  14636. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  14637. return list;
  14638. }
  14639. var listByTags = [];
  14640. forEach = forEach || (function (item) { return; });
  14641. for (var i in list) {
  14642. var item = list[i];
  14643. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  14644. listByTags.push(item);
  14645. forEach(item);
  14646. }
  14647. }
  14648. return listByTags;
  14649. };
  14650. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  14651. return this._getByTags(this.meshes, tagsQuery, forEach);
  14652. };
  14653. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  14654. return this._getByTags(this.cameras, tagsQuery, forEach);
  14655. };
  14656. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  14657. return this._getByTags(this.lights, tagsQuery, forEach);
  14658. };
  14659. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  14660. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  14661. };
  14662. // Statics
  14663. Scene._FOGMODE_NONE = 0;
  14664. Scene._FOGMODE_EXP = 1;
  14665. Scene._FOGMODE_EXP2 = 2;
  14666. Scene._FOGMODE_LINEAR = 3;
  14667. Scene.MinDeltaTime = 1.0;
  14668. Scene.MaxDeltaTime = 1000.0;
  14669. return Scene;
  14670. })();
  14671. BABYLON.Scene = Scene;
  14672. })(BABYLON || (BABYLON = {}));
  14673. var BABYLON;
  14674. (function (BABYLON) {
  14675. var VertexBuffer = (function () {
  14676. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  14677. if (engine instanceof BABYLON.Mesh) {
  14678. this._engine = engine.getScene().getEngine();
  14679. }
  14680. else {
  14681. this._engine = engine;
  14682. }
  14683. this._updatable = updatable;
  14684. this._data = data;
  14685. if (!postponeInternalCreation) {
  14686. this.create();
  14687. }
  14688. this._kind = kind;
  14689. if (stride) {
  14690. this._strideSize = stride;
  14691. return;
  14692. }
  14693. // Deduce stride from kind
  14694. switch (kind) {
  14695. case VertexBuffer.PositionKind:
  14696. this._strideSize = 3;
  14697. break;
  14698. case VertexBuffer.NormalKind:
  14699. this._strideSize = 3;
  14700. break;
  14701. case VertexBuffer.UVKind:
  14702. case VertexBuffer.UV2Kind:
  14703. case VertexBuffer.UV3Kind:
  14704. case VertexBuffer.UV4Kind:
  14705. case VertexBuffer.UV5Kind:
  14706. case VertexBuffer.UV6Kind:
  14707. this._strideSize = 2;
  14708. break;
  14709. case VertexBuffer.ColorKind:
  14710. this._strideSize = 4;
  14711. break;
  14712. case VertexBuffer.MatricesIndicesKind:
  14713. case VertexBuffer.MatricesIndicesExtraKind:
  14714. this._strideSize = 4;
  14715. break;
  14716. case VertexBuffer.MatricesWeightsKind:
  14717. case VertexBuffer.MatricesWeightsExtraKind:
  14718. this._strideSize = 4;
  14719. break;
  14720. }
  14721. }
  14722. // Properties
  14723. VertexBuffer.prototype.isUpdatable = function () {
  14724. return this._updatable;
  14725. };
  14726. VertexBuffer.prototype.getData = function () {
  14727. return this._data;
  14728. };
  14729. VertexBuffer.prototype.getBuffer = function () {
  14730. return this._buffer;
  14731. };
  14732. VertexBuffer.prototype.getStrideSize = function () {
  14733. return this._strideSize;
  14734. };
  14735. // Methods
  14736. VertexBuffer.prototype.create = function (data) {
  14737. if (!data && this._buffer) {
  14738. return; // nothing to do
  14739. }
  14740. data = data || this._data;
  14741. if (!this._buffer) {
  14742. if (this._updatable) {
  14743. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  14744. }
  14745. else {
  14746. this._buffer = this._engine.createVertexBuffer(data);
  14747. }
  14748. }
  14749. if (this._updatable) {
  14750. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  14751. this._data = data;
  14752. }
  14753. };
  14754. VertexBuffer.prototype.update = function (data) {
  14755. this.create(data);
  14756. };
  14757. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  14758. if (!this._buffer) {
  14759. return;
  14760. }
  14761. if (this._updatable) {
  14762. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  14763. this._data = null;
  14764. }
  14765. };
  14766. VertexBuffer.prototype.dispose = function () {
  14767. if (!this._buffer) {
  14768. return;
  14769. }
  14770. if (this._engine._releaseBuffer(this._buffer)) {
  14771. this._buffer = null;
  14772. }
  14773. };
  14774. Object.defineProperty(VertexBuffer, "PositionKind", {
  14775. get: function () {
  14776. return VertexBuffer._PositionKind;
  14777. },
  14778. enumerable: true,
  14779. configurable: true
  14780. });
  14781. Object.defineProperty(VertexBuffer, "NormalKind", {
  14782. get: function () {
  14783. return VertexBuffer._NormalKind;
  14784. },
  14785. enumerable: true,
  14786. configurable: true
  14787. });
  14788. Object.defineProperty(VertexBuffer, "UVKind", {
  14789. get: function () {
  14790. return VertexBuffer._UVKind;
  14791. },
  14792. enumerable: true,
  14793. configurable: true
  14794. });
  14795. Object.defineProperty(VertexBuffer, "UV2Kind", {
  14796. get: function () {
  14797. return VertexBuffer._UV2Kind;
  14798. },
  14799. enumerable: true,
  14800. configurable: true
  14801. });
  14802. Object.defineProperty(VertexBuffer, "UV3Kind", {
  14803. get: function () {
  14804. return VertexBuffer._UV3Kind;
  14805. },
  14806. enumerable: true,
  14807. configurable: true
  14808. });
  14809. Object.defineProperty(VertexBuffer, "UV4Kind", {
  14810. get: function () {
  14811. return VertexBuffer._UV4Kind;
  14812. },
  14813. enumerable: true,
  14814. configurable: true
  14815. });
  14816. Object.defineProperty(VertexBuffer, "UV5Kind", {
  14817. get: function () {
  14818. return VertexBuffer._UV5Kind;
  14819. },
  14820. enumerable: true,
  14821. configurable: true
  14822. });
  14823. Object.defineProperty(VertexBuffer, "UV6Kind", {
  14824. get: function () {
  14825. return VertexBuffer._UV6Kind;
  14826. },
  14827. enumerable: true,
  14828. configurable: true
  14829. });
  14830. Object.defineProperty(VertexBuffer, "ColorKind", {
  14831. get: function () {
  14832. return VertexBuffer._ColorKind;
  14833. },
  14834. enumerable: true,
  14835. configurable: true
  14836. });
  14837. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  14838. get: function () {
  14839. return VertexBuffer._MatricesIndicesKind;
  14840. },
  14841. enumerable: true,
  14842. configurable: true
  14843. });
  14844. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  14845. get: function () {
  14846. return VertexBuffer._MatricesWeightsKind;
  14847. },
  14848. enumerable: true,
  14849. configurable: true
  14850. });
  14851. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  14852. get: function () {
  14853. return VertexBuffer._MatricesIndicesExtraKind;
  14854. },
  14855. enumerable: true,
  14856. configurable: true
  14857. });
  14858. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  14859. get: function () {
  14860. return VertexBuffer._MatricesWeightsExtraKind;
  14861. },
  14862. enumerable: true,
  14863. configurable: true
  14864. });
  14865. // Enums
  14866. VertexBuffer._PositionKind = "position";
  14867. VertexBuffer._NormalKind = "normal";
  14868. VertexBuffer._UVKind = "uv";
  14869. VertexBuffer._UV2Kind = "uv2";
  14870. VertexBuffer._UV3Kind = "uv3";
  14871. VertexBuffer._UV4Kind = "uv4";
  14872. VertexBuffer._UV5Kind = "uv5";
  14873. VertexBuffer._UV6Kind = "uv6";
  14874. VertexBuffer._ColorKind = "color";
  14875. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  14876. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  14877. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  14878. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  14879. return VertexBuffer;
  14880. })();
  14881. BABYLON.VertexBuffer = VertexBuffer;
  14882. })(BABYLON || (BABYLON = {}));
  14883. var BABYLON;
  14884. (function (BABYLON) {
  14885. /**
  14886. * Creates an instance based on a source mesh.
  14887. */
  14888. var InstancedMesh = (function (_super) {
  14889. __extends(InstancedMesh, _super);
  14890. function InstancedMesh(name, source) {
  14891. _super.call(this, name, source.getScene());
  14892. source.instances.push(this);
  14893. this._sourceMesh = source;
  14894. this.position.copyFrom(source.position);
  14895. this.rotation.copyFrom(source.rotation);
  14896. this.scaling.copyFrom(source.scaling);
  14897. if (source.rotationQuaternion) {
  14898. this.rotationQuaternion = source.rotationQuaternion.clone();
  14899. }
  14900. this.infiniteDistance = source.infiniteDistance;
  14901. this.setPivotMatrix(source.getPivotMatrix());
  14902. this.refreshBoundingInfo();
  14903. this._syncSubMeshes();
  14904. }
  14905. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  14906. // Methods
  14907. get: function () {
  14908. return this._sourceMesh.receiveShadows;
  14909. },
  14910. enumerable: true,
  14911. configurable: true
  14912. });
  14913. Object.defineProperty(InstancedMesh.prototype, "material", {
  14914. get: function () {
  14915. return this._sourceMesh.material;
  14916. },
  14917. enumerable: true,
  14918. configurable: true
  14919. });
  14920. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  14921. get: function () {
  14922. return this._sourceMesh.visibility;
  14923. },
  14924. enumerable: true,
  14925. configurable: true
  14926. });
  14927. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  14928. get: function () {
  14929. return this._sourceMesh.skeleton;
  14930. },
  14931. enumerable: true,
  14932. configurable: true
  14933. });
  14934. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  14935. get: function () {
  14936. return this._sourceMesh.renderingGroupId;
  14937. },
  14938. enumerable: true,
  14939. configurable: true
  14940. });
  14941. InstancedMesh.prototype.getTotalVertices = function () {
  14942. return this._sourceMesh.getTotalVertices();
  14943. };
  14944. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  14945. get: function () {
  14946. return this._sourceMesh;
  14947. },
  14948. enumerable: true,
  14949. configurable: true
  14950. });
  14951. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  14952. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  14953. };
  14954. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  14955. return this._sourceMesh.isVerticesDataPresent(kind);
  14956. };
  14957. InstancedMesh.prototype.getIndices = function () {
  14958. return this._sourceMesh.getIndices();
  14959. };
  14960. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  14961. get: function () {
  14962. return this._sourceMesh._positions;
  14963. },
  14964. enumerable: true,
  14965. configurable: true
  14966. });
  14967. InstancedMesh.prototype.refreshBoundingInfo = function () {
  14968. var meshBB = this._sourceMesh.getBoundingInfo();
  14969. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  14970. this._updateBoundingInfo();
  14971. };
  14972. InstancedMesh.prototype._preActivate = function () {
  14973. if (this._currentLOD) {
  14974. this._currentLOD._preActivate();
  14975. }
  14976. };
  14977. InstancedMesh.prototype._activate = function (renderId) {
  14978. if (this._currentLOD) {
  14979. this._currentLOD._registerInstanceForRenderId(this, renderId);
  14980. }
  14981. };
  14982. InstancedMesh.prototype.getLOD = function (camera) {
  14983. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  14984. if (this._currentLOD === this.sourceMesh) {
  14985. return this;
  14986. }
  14987. return this._currentLOD;
  14988. };
  14989. InstancedMesh.prototype._syncSubMeshes = function () {
  14990. this.releaseSubMeshes();
  14991. if (this._sourceMesh.subMeshes) {
  14992. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  14993. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  14994. }
  14995. }
  14996. };
  14997. InstancedMesh.prototype._generatePointsArray = function () {
  14998. return this._sourceMesh._generatePointsArray();
  14999. };
  15000. // Clone
  15001. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  15002. var result = this._sourceMesh.createInstance(name);
  15003. // Deep copy
  15004. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  15005. // Bounding info
  15006. this.refreshBoundingInfo();
  15007. // Parent
  15008. if (newParent) {
  15009. result.parent = newParent;
  15010. }
  15011. if (!doNotCloneChildren) {
  15012. // Children
  15013. for (var index = 0; index < this.getScene().meshes.length; index++) {
  15014. var mesh = this.getScene().meshes[index];
  15015. if (mesh.parent === this) {
  15016. mesh.clone(mesh.name, result);
  15017. }
  15018. }
  15019. }
  15020. result.computeWorldMatrix(true);
  15021. return result;
  15022. };
  15023. // Dispoe
  15024. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  15025. // Remove from mesh
  15026. var index = this._sourceMesh.instances.indexOf(this);
  15027. this._sourceMesh.instances.splice(index, 1);
  15028. _super.prototype.dispose.call(this, doNotRecurse);
  15029. };
  15030. return InstancedMesh;
  15031. })(BABYLON.AbstractMesh);
  15032. BABYLON.InstancedMesh = InstancedMesh;
  15033. })(BABYLON || (BABYLON = {}));
  15034. var BABYLON;
  15035. (function (BABYLON) {
  15036. var _InstancesBatch = (function () {
  15037. function _InstancesBatch() {
  15038. this.mustReturn = false;
  15039. this.visibleInstances = new Array();
  15040. this.renderSelf = new Array();
  15041. }
  15042. return _InstancesBatch;
  15043. })();
  15044. BABYLON._InstancesBatch = _InstancesBatch;
  15045. var Mesh = (function (_super) {
  15046. __extends(Mesh, _super);
  15047. /**
  15048. * @constructor
  15049. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  15050. * @param {Scene} scene - The scene to add this mesh to.
  15051. * @param {Node} parent - The parent of this mesh, if it has one
  15052. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  15053. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  15054. * When false, achieved by calling a clone(), also passing False.
  15055. * This will make creation of children, recursive.
  15056. */
  15057. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  15058. if (parent === void 0) { parent = null; }
  15059. _super.call(this, name, scene);
  15060. // Members
  15061. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  15062. this.instances = new Array();
  15063. this._LODLevels = new Array();
  15064. this._onBeforeRenderCallbacks = new Array();
  15065. this._onAfterRenderCallbacks = new Array();
  15066. this._visibleInstances = {};
  15067. this._renderIdForInstances = new Array();
  15068. this._batchCache = new _InstancesBatch();
  15069. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  15070. this._sideOrientation = Mesh._DEFAULTSIDE;
  15071. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  15072. if (source) {
  15073. // Geometry
  15074. if (source._geometry) {
  15075. source._geometry.applyToMesh(this);
  15076. }
  15077. // Deep copy
  15078. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], ["_poseMatrix"]);
  15079. // Pivot
  15080. this.setPivotMatrix(source.getPivotMatrix());
  15081. this.id = name + "." + source.id;
  15082. // Material
  15083. this.material = source.material;
  15084. var index;
  15085. if (!doNotCloneChildren) {
  15086. // Children
  15087. for (index = 0; index < scene.meshes.length; index++) {
  15088. var mesh = scene.meshes[index];
  15089. if (mesh.parent === source) {
  15090. // doNotCloneChildren is always going to be False
  15091. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  15092. }
  15093. }
  15094. }
  15095. // Particles
  15096. for (index = 0; index < scene.particleSystems.length; index++) {
  15097. var system = scene.particleSystems[index];
  15098. if (system.emitter === source) {
  15099. system.clone(system.name, this);
  15100. }
  15101. }
  15102. this.computeWorldMatrix(true);
  15103. }
  15104. // Parent
  15105. if (parent !== null) {
  15106. this.parent = parent;
  15107. }
  15108. }
  15109. Object.defineProperty(Mesh, "FRONTSIDE", {
  15110. get: function () {
  15111. return Mesh._FRONTSIDE;
  15112. },
  15113. enumerable: true,
  15114. configurable: true
  15115. });
  15116. Object.defineProperty(Mesh, "BACKSIDE", {
  15117. get: function () {
  15118. return Mesh._BACKSIDE;
  15119. },
  15120. enumerable: true,
  15121. configurable: true
  15122. });
  15123. Object.defineProperty(Mesh, "DOUBLESIDE", {
  15124. get: function () {
  15125. return Mesh._DOUBLESIDE;
  15126. },
  15127. enumerable: true,
  15128. configurable: true
  15129. });
  15130. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  15131. get: function () {
  15132. return Mesh._DEFAULTSIDE;
  15133. },
  15134. enumerable: true,
  15135. configurable: true
  15136. });
  15137. Object.defineProperty(Mesh, "NO_CAP", {
  15138. get: function () {
  15139. return Mesh._NO_CAP;
  15140. },
  15141. enumerable: true,
  15142. configurable: true
  15143. });
  15144. Object.defineProperty(Mesh, "CAP_START", {
  15145. get: function () {
  15146. return Mesh._CAP_START;
  15147. },
  15148. enumerable: true,
  15149. configurable: true
  15150. });
  15151. Object.defineProperty(Mesh, "CAP_END", {
  15152. get: function () {
  15153. return Mesh._CAP_END;
  15154. },
  15155. enumerable: true,
  15156. configurable: true
  15157. });
  15158. Object.defineProperty(Mesh, "CAP_ALL", {
  15159. get: function () {
  15160. return Mesh._CAP_ALL;
  15161. },
  15162. enumerable: true,
  15163. configurable: true
  15164. });
  15165. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  15166. // Methods
  15167. get: function () {
  15168. return this._LODLevels.length > 0;
  15169. },
  15170. enumerable: true,
  15171. configurable: true
  15172. });
  15173. Mesh.prototype._sortLODLevels = function () {
  15174. this._LODLevels.sort(function (a, b) {
  15175. if (a.distance < b.distance) {
  15176. return 1;
  15177. }
  15178. if (a.distance > b.distance) {
  15179. return -1;
  15180. }
  15181. return 0;
  15182. });
  15183. };
  15184. /**
  15185. * Add a mesh as LOD level triggered at the given distance.
  15186. * @param {number} distance - the distance from the center of the object to show this level
  15187. * @param {Mesh} mesh - the mesh to be added as LOD level
  15188. * @return {Mesh} this mesh (for chaining)
  15189. */
  15190. Mesh.prototype.addLODLevel = function (distance, mesh) {
  15191. if (mesh && mesh._masterMesh) {
  15192. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  15193. return this;
  15194. }
  15195. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  15196. this._LODLevels.push(level);
  15197. if (mesh) {
  15198. mesh._masterMesh = this;
  15199. }
  15200. this._sortLODLevels();
  15201. return this;
  15202. };
  15203. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  15204. for (var index = 0; index < this._LODLevels.length; index++) {
  15205. var level = this._LODLevels[index];
  15206. if (level.distance === distance) {
  15207. return level.mesh;
  15208. }
  15209. }
  15210. return null;
  15211. };
  15212. /**
  15213. * Remove a mesh from the LOD array
  15214. * @param {Mesh} mesh - the mesh to be removed.
  15215. * @return {Mesh} this mesh (for chaining)
  15216. */
  15217. Mesh.prototype.removeLODLevel = function (mesh) {
  15218. for (var index = 0; index < this._LODLevels.length; index++) {
  15219. if (this._LODLevels[index].mesh === mesh) {
  15220. this._LODLevels.splice(index, 1);
  15221. if (mesh) {
  15222. mesh._masterMesh = null;
  15223. }
  15224. }
  15225. }
  15226. this._sortLODLevels();
  15227. return this;
  15228. };
  15229. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  15230. if (!this._LODLevels || this._LODLevels.length === 0) {
  15231. return this;
  15232. }
  15233. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  15234. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  15235. if (this.onLODLevelSelection) {
  15236. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  15237. }
  15238. return this;
  15239. }
  15240. for (var index = 0; index < this._LODLevels.length; index++) {
  15241. var level = this._LODLevels[index];
  15242. if (level.distance < distanceToCamera) {
  15243. if (level.mesh) {
  15244. level.mesh._preActivate();
  15245. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  15246. }
  15247. if (this.onLODLevelSelection) {
  15248. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  15249. }
  15250. return level.mesh;
  15251. }
  15252. }
  15253. if (this.onLODLevelSelection) {
  15254. this.onLODLevelSelection(distanceToCamera, this, this);
  15255. }
  15256. return this;
  15257. };
  15258. Object.defineProperty(Mesh.prototype, "geometry", {
  15259. get: function () {
  15260. return this._geometry;
  15261. },
  15262. enumerable: true,
  15263. configurable: true
  15264. });
  15265. Mesh.prototype.getTotalVertices = function () {
  15266. if (!this._geometry) {
  15267. return 0;
  15268. }
  15269. return this._geometry.getTotalVertices();
  15270. };
  15271. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  15272. if (!this._geometry) {
  15273. return null;
  15274. }
  15275. return this._geometry.getVerticesData(kind, copyWhenShared);
  15276. };
  15277. Mesh.prototype.getVertexBuffer = function (kind) {
  15278. if (!this._geometry) {
  15279. return undefined;
  15280. }
  15281. return this._geometry.getVertexBuffer(kind);
  15282. };
  15283. Mesh.prototype.isVerticesDataPresent = function (kind) {
  15284. if (!this._geometry) {
  15285. if (this._delayInfo) {
  15286. return this._delayInfo.indexOf(kind) !== -1;
  15287. }
  15288. return false;
  15289. }
  15290. return this._geometry.isVerticesDataPresent(kind);
  15291. };
  15292. Mesh.prototype.getVerticesDataKinds = function () {
  15293. if (!this._geometry) {
  15294. var result = [];
  15295. if (this._delayInfo) {
  15296. for (var kind in this._delayInfo) {
  15297. result.push(kind);
  15298. }
  15299. }
  15300. return result;
  15301. }
  15302. return this._geometry.getVerticesDataKinds();
  15303. };
  15304. Mesh.prototype.getTotalIndices = function () {
  15305. if (!this._geometry) {
  15306. return 0;
  15307. }
  15308. return this._geometry.getTotalIndices();
  15309. };
  15310. Mesh.prototype.getIndices = function (copyWhenShared) {
  15311. if (!this._geometry) {
  15312. return [];
  15313. }
  15314. return this._geometry.getIndices(copyWhenShared);
  15315. };
  15316. Object.defineProperty(Mesh.prototype, "isBlocked", {
  15317. get: function () {
  15318. return this._masterMesh !== null && this._masterMesh !== undefined;
  15319. },
  15320. enumerable: true,
  15321. configurable: true
  15322. });
  15323. Mesh.prototype.isReady = function () {
  15324. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  15325. return false;
  15326. }
  15327. return _super.prototype.isReady.call(this);
  15328. };
  15329. Mesh.prototype.isDisposed = function () {
  15330. return this._isDisposed;
  15331. };
  15332. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  15333. get: function () {
  15334. return this._sideOrientation;
  15335. },
  15336. set: function (sideO) {
  15337. this._sideOrientation = sideO;
  15338. },
  15339. enumerable: true,
  15340. configurable: true
  15341. });
  15342. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  15343. get: function () {
  15344. return this._areNormalsFrozen;
  15345. },
  15346. enumerable: true,
  15347. configurable: true
  15348. });
  15349. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  15350. Mesh.prototype.freezeNormals = function () {
  15351. this._areNormalsFrozen = true;
  15352. };
  15353. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  15354. Mesh.prototype.unfreezeNormals = function () {
  15355. this._areNormalsFrozen = false;
  15356. };
  15357. // Methods
  15358. Mesh.prototype._preActivate = function () {
  15359. var sceneRenderId = this.getScene().getRenderId();
  15360. if (this._preActivateId === sceneRenderId) {
  15361. return;
  15362. }
  15363. this._preActivateId = sceneRenderId;
  15364. this._visibleInstances = null;
  15365. };
  15366. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  15367. if (!this._visibleInstances) {
  15368. this._visibleInstances = {};
  15369. this._visibleInstances.defaultRenderId = renderId;
  15370. this._visibleInstances.selfDefaultRenderId = this._renderId;
  15371. }
  15372. if (!this._visibleInstances[renderId]) {
  15373. this._visibleInstances[renderId] = new Array();
  15374. }
  15375. this._visibleInstances[renderId].push(instance);
  15376. };
  15377. Mesh.prototype.refreshBoundingInfo = function () {
  15378. if (this._boundingInfo.isLocked) {
  15379. return;
  15380. }
  15381. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15382. if (data) {
  15383. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  15384. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  15385. }
  15386. if (this.subMeshes) {
  15387. for (var index = 0; index < this.subMeshes.length; index++) {
  15388. this.subMeshes[index].refreshBoundingInfo();
  15389. }
  15390. }
  15391. this._updateBoundingInfo();
  15392. };
  15393. Mesh.prototype._createGlobalSubMesh = function () {
  15394. var totalVertices = this.getTotalVertices();
  15395. if (!totalVertices || !this.getIndices()) {
  15396. return null;
  15397. }
  15398. this.releaseSubMeshes();
  15399. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  15400. };
  15401. Mesh.prototype.subdivide = function (count) {
  15402. if (count < 1) {
  15403. return;
  15404. }
  15405. var totalIndices = this.getTotalIndices();
  15406. var subdivisionSize = (totalIndices / count) | 0;
  15407. var offset = 0;
  15408. // Ensure that subdivisionSize is a multiple of 3
  15409. while (subdivisionSize % 3 !== 0) {
  15410. subdivisionSize++;
  15411. }
  15412. this.releaseSubMeshes();
  15413. for (var index = 0; index < count; index++) {
  15414. if (offset >= totalIndices) {
  15415. break;
  15416. }
  15417. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  15418. offset += subdivisionSize;
  15419. }
  15420. this.synchronizeInstances();
  15421. };
  15422. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  15423. if (!this._geometry) {
  15424. var vertexData = new BABYLON.VertexData();
  15425. vertexData.set(data, kind);
  15426. var scene = this.getScene();
  15427. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  15428. }
  15429. else {
  15430. this._geometry.setVerticesData(kind, data, updatable, stride);
  15431. }
  15432. };
  15433. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  15434. if (!this._geometry) {
  15435. return;
  15436. }
  15437. if (!makeItUnique) {
  15438. this._geometry.updateVerticesData(kind, data, updateExtends);
  15439. }
  15440. else {
  15441. this.makeGeometryUnique();
  15442. this.updateVerticesData(kind, data, updateExtends, false);
  15443. }
  15444. };
  15445. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  15446. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  15447. if (!this._geometry) {
  15448. return;
  15449. }
  15450. if (!makeItUnique) {
  15451. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  15452. }
  15453. else {
  15454. this.makeGeometryUnique();
  15455. this.updateVerticesDataDirectly(kind, data, offset, false);
  15456. }
  15457. };
  15458. // Mesh positions update function :
  15459. // updates the mesh positions according to the positionFunction returned values.
  15460. // The positionFunction argument must be a javascript function accepting the mesh "positions" array as parameter.
  15461. // This dedicated positionFunction computes new mesh positions according to the given mesh type.
  15462. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  15463. if (computeNormals === void 0) { computeNormals = true; }
  15464. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15465. positionFunction(positions);
  15466. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  15467. if (computeNormals) {
  15468. var indices = this.getIndices();
  15469. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15470. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  15471. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  15472. }
  15473. };
  15474. Mesh.prototype.makeGeometryUnique = function () {
  15475. if (!this._geometry) {
  15476. return;
  15477. }
  15478. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  15479. geometry.applyToMesh(this);
  15480. };
  15481. Mesh.prototype.setIndices = function (indices, totalVertices) {
  15482. if (!this._geometry) {
  15483. var vertexData = new BABYLON.VertexData();
  15484. vertexData.indices = indices;
  15485. var scene = this.getScene();
  15486. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  15487. }
  15488. else {
  15489. this._geometry.setIndices(indices, totalVertices);
  15490. }
  15491. };
  15492. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  15493. var engine = this.getScene().getEngine();
  15494. // Wireframe
  15495. var indexToBind;
  15496. if (this._unIndexed) {
  15497. indexToBind = null;
  15498. }
  15499. else {
  15500. switch (fillMode) {
  15501. case BABYLON.Material.PointFillMode:
  15502. indexToBind = null;
  15503. break;
  15504. case BABYLON.Material.WireFrameFillMode:
  15505. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  15506. break;
  15507. default:
  15508. case BABYLON.Material.TriangleFillMode:
  15509. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  15510. break;
  15511. }
  15512. }
  15513. // VBOs
  15514. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  15515. };
  15516. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  15517. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  15518. return;
  15519. }
  15520. if (this.onBeforeDraw) {
  15521. this.onBeforeDraw();
  15522. }
  15523. var engine = this.getScene().getEngine();
  15524. // Draw order
  15525. switch (fillMode) {
  15526. case BABYLON.Material.PointFillMode:
  15527. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  15528. break;
  15529. case BABYLON.Material.WireFrameFillMode:
  15530. if (this._unIndexed) {
  15531. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  15532. }
  15533. else {
  15534. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  15535. }
  15536. break;
  15537. default:
  15538. if (this._unIndexed) {
  15539. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  15540. }
  15541. else {
  15542. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  15543. }
  15544. }
  15545. };
  15546. Mesh.prototype.registerBeforeRender = function (func) {
  15547. this._onBeforeRenderCallbacks.push(func);
  15548. };
  15549. Mesh.prototype.unregisterBeforeRender = function (func) {
  15550. var index = this._onBeforeRenderCallbacks.indexOf(func);
  15551. if (index > -1) {
  15552. this._onBeforeRenderCallbacks.splice(index, 1);
  15553. }
  15554. };
  15555. Mesh.prototype.registerAfterRender = function (func) {
  15556. this._onAfterRenderCallbacks.push(func);
  15557. };
  15558. Mesh.prototype.unregisterAfterRender = function (func) {
  15559. var index = this._onAfterRenderCallbacks.indexOf(func);
  15560. if (index > -1) {
  15561. this._onAfterRenderCallbacks.splice(index, 1);
  15562. }
  15563. };
  15564. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  15565. var scene = this.getScene();
  15566. this._batchCache.mustReturn = false;
  15567. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  15568. this._batchCache.visibleInstances[subMeshId] = null;
  15569. if (this._visibleInstances) {
  15570. var currentRenderId = scene.getRenderId();
  15571. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  15572. var selfRenderId = this._renderId;
  15573. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  15574. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  15575. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  15576. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  15577. }
  15578. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  15579. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  15580. this._batchCache.mustReturn = true;
  15581. return this._batchCache;
  15582. }
  15583. if (currentRenderId !== selfRenderId) {
  15584. this._batchCache.renderSelf[subMeshId] = false;
  15585. }
  15586. }
  15587. this._renderIdForInstances[subMeshId] = currentRenderId;
  15588. }
  15589. return this._batchCache;
  15590. };
  15591. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  15592. var visibleInstances = batch.visibleInstances[subMesh._id];
  15593. var matricesCount = visibleInstances.length + 1;
  15594. var bufferSize = matricesCount * 16 * 4;
  15595. while (this._instancesBufferSize < bufferSize) {
  15596. this._instancesBufferSize *= 2;
  15597. }
  15598. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  15599. if (this._worldMatricesInstancesBuffer) {
  15600. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  15601. }
  15602. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  15603. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  15604. }
  15605. var offset = 0;
  15606. var instancesCount = 0;
  15607. var world = this.getWorldMatrix();
  15608. if (batch.renderSelf[subMesh._id]) {
  15609. world.copyToArray(this._worldMatricesInstancesArray, offset);
  15610. offset += 16;
  15611. instancesCount++;
  15612. }
  15613. if (visibleInstances) {
  15614. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  15615. var instance = visibleInstances[instanceIndex];
  15616. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  15617. offset += 16;
  15618. instancesCount++;
  15619. }
  15620. }
  15621. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  15622. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  15623. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  15624. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  15625. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  15626. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  15627. this._draw(subMesh, fillMode, instancesCount);
  15628. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  15629. };
  15630. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  15631. var scene = this.getScene();
  15632. var engine = scene.getEngine();
  15633. if (hardwareInstancedRendering) {
  15634. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  15635. }
  15636. else {
  15637. if (batch.renderSelf[subMesh._id]) {
  15638. // Draw
  15639. if (onBeforeDraw) {
  15640. onBeforeDraw(false, this.getWorldMatrix());
  15641. }
  15642. this._draw(subMesh, fillMode);
  15643. }
  15644. if (batch.visibleInstances[subMesh._id]) {
  15645. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  15646. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  15647. // World
  15648. var world = instance.getWorldMatrix();
  15649. if (onBeforeDraw) {
  15650. onBeforeDraw(true, world);
  15651. }
  15652. // Draw
  15653. this._draw(subMesh, fillMode);
  15654. }
  15655. }
  15656. }
  15657. };
  15658. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  15659. var scene = this.getScene();
  15660. // Managing instances
  15661. var batch = this._getInstancesRenderList(subMesh._id);
  15662. if (batch.mustReturn) {
  15663. return;
  15664. }
  15665. // Checking geometry state
  15666. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  15667. return;
  15668. }
  15669. var callbackIndex;
  15670. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  15671. this._onBeforeRenderCallbacks[callbackIndex](this);
  15672. }
  15673. var engine = scene.getEngine();
  15674. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  15675. // Material
  15676. var effectiveMaterial = subMesh.getMaterial();
  15677. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  15678. return;
  15679. }
  15680. // Outline - step 1
  15681. var savedDepthWrite = engine.getDepthWrite();
  15682. if (this.renderOutline) {
  15683. engine.setDepthWrite(false);
  15684. scene.getOutlineRenderer().render(subMesh, batch);
  15685. engine.setDepthWrite(savedDepthWrite);
  15686. }
  15687. effectiveMaterial._preBind();
  15688. var effect = effectiveMaterial.getEffect();
  15689. // Bind
  15690. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  15691. this._bind(subMesh, effect, fillMode);
  15692. var world = this.getWorldMatrix();
  15693. effectiveMaterial.bind(world, this);
  15694. // Alpha mode
  15695. if (enableAlphaMode) {
  15696. engine.setAlphaMode(effectiveMaterial.alphaMode);
  15697. }
  15698. // Draw
  15699. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  15700. if (isInstance) {
  15701. effectiveMaterial.bindOnlyWorldMatrix(world);
  15702. }
  15703. });
  15704. // Unbind
  15705. effectiveMaterial.unbind();
  15706. // Outline - step 2
  15707. if (this.renderOutline && savedDepthWrite) {
  15708. engine.setDepthWrite(true);
  15709. engine.setColorWrite(false);
  15710. scene.getOutlineRenderer().render(subMesh, batch);
  15711. engine.setColorWrite(true);
  15712. }
  15713. // Overlay
  15714. if (this.renderOverlay) {
  15715. var currentMode = engine.getAlphaMode();
  15716. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  15717. scene.getOutlineRenderer().render(subMesh, batch, true);
  15718. engine.setAlphaMode(currentMode);
  15719. }
  15720. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  15721. this._onAfterRenderCallbacks[callbackIndex](this);
  15722. }
  15723. };
  15724. Mesh.prototype.getEmittedParticleSystems = function () {
  15725. var results = new Array();
  15726. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  15727. var particleSystem = this.getScene().particleSystems[index];
  15728. if (particleSystem.emitter === this) {
  15729. results.push(particleSystem);
  15730. }
  15731. }
  15732. return results;
  15733. };
  15734. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  15735. var results = new Array();
  15736. var descendants = this.getDescendants();
  15737. descendants.push(this);
  15738. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  15739. var particleSystem = this.getScene().particleSystems[index];
  15740. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  15741. results.push(particleSystem);
  15742. }
  15743. }
  15744. return results;
  15745. };
  15746. Mesh.prototype._checkDelayState = function () {
  15747. var _this = this;
  15748. var that = this;
  15749. var scene = this.getScene();
  15750. if (this._geometry) {
  15751. this._geometry.load(scene);
  15752. }
  15753. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  15754. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  15755. scene._addPendingData(that);
  15756. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  15757. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  15758. if (data instanceof ArrayBuffer) {
  15759. _this._delayLoadingFunction(data, _this);
  15760. }
  15761. else {
  15762. _this._delayLoadingFunction(JSON.parse(data), _this);
  15763. }
  15764. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  15765. scene._removePendingData(_this);
  15766. }, function () { }, scene.database, getBinaryData);
  15767. }
  15768. };
  15769. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  15770. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  15771. return false;
  15772. }
  15773. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  15774. return false;
  15775. }
  15776. this._checkDelayState();
  15777. return true;
  15778. };
  15779. Mesh.prototype.setMaterialByID = function (id) {
  15780. var materials = this.getScene().materials;
  15781. var index;
  15782. for (index = 0; index < materials.length; index++) {
  15783. if (materials[index].id === id) {
  15784. this.material = materials[index];
  15785. return;
  15786. }
  15787. }
  15788. // Multi
  15789. var multiMaterials = this.getScene().multiMaterials;
  15790. for (index = 0; index < multiMaterials.length; index++) {
  15791. if (multiMaterials[index].id === id) {
  15792. this.material = multiMaterials[index];
  15793. return;
  15794. }
  15795. }
  15796. };
  15797. Mesh.prototype.getAnimatables = function () {
  15798. var results = [];
  15799. if (this.material) {
  15800. results.push(this.material);
  15801. }
  15802. if (this.skeleton) {
  15803. results.push(this.skeleton);
  15804. }
  15805. return results;
  15806. };
  15807. // Geometry
  15808. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  15809. // Position
  15810. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  15811. return;
  15812. }
  15813. this._resetPointsArrayCache();
  15814. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15815. var temp = [];
  15816. var index;
  15817. for (index = 0; index < data.length; index += 3) {
  15818. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  15819. }
  15820. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  15821. // Normals
  15822. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15823. return;
  15824. }
  15825. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15826. temp = [];
  15827. for (index = 0; index < data.length; index += 3) {
  15828. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  15829. }
  15830. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  15831. // flip faces?
  15832. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  15833. this.flipFaces();
  15834. }
  15835. };
  15836. // Will apply current transform to mesh and reset world matrix
  15837. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  15838. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  15839. this.scaling.copyFromFloats(1, 1, 1);
  15840. this.position.copyFromFloats(0, 0, 0);
  15841. this.rotation.copyFromFloats(0, 0, 0);
  15842. //only if quaternion is already set
  15843. if (this.rotationQuaternion) {
  15844. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  15845. }
  15846. this._worldMatrix = BABYLON.Matrix.Identity();
  15847. };
  15848. // Cache
  15849. Mesh.prototype._resetPointsArrayCache = function () {
  15850. this._positions = null;
  15851. };
  15852. Mesh.prototype._generatePointsArray = function () {
  15853. if (this._positions)
  15854. return true;
  15855. this._positions = [];
  15856. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15857. if (!data) {
  15858. return false;
  15859. }
  15860. for (var index = 0; index < data.length; index += 3) {
  15861. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  15862. }
  15863. return true;
  15864. };
  15865. // Clone
  15866. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  15867. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  15868. };
  15869. // Dispose
  15870. Mesh.prototype.dispose = function (doNotRecurse) {
  15871. if (this._geometry) {
  15872. this._geometry.releaseForMesh(this, true);
  15873. }
  15874. // Instances
  15875. if (this._worldMatricesInstancesBuffer) {
  15876. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  15877. this._worldMatricesInstancesBuffer = null;
  15878. }
  15879. while (this.instances.length) {
  15880. this.instances[0].dispose();
  15881. }
  15882. _super.prototype.dispose.call(this, doNotRecurse);
  15883. };
  15884. // Geometric tools
  15885. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  15886. var _this = this;
  15887. var scene = this.getScene();
  15888. var onload = function (img) {
  15889. // Getting height map data
  15890. var canvas = document.createElement("canvas");
  15891. var context = canvas.getContext("2d");
  15892. var heightMapWidth = img.width;
  15893. var heightMapHeight = img.height;
  15894. canvas.width = heightMapWidth;
  15895. canvas.height = heightMapHeight;
  15896. context.drawImage(img, 0, 0);
  15897. // Create VertexData from map data
  15898. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  15899. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  15900. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  15901. //execute success callback, if set
  15902. if (onSuccess) {
  15903. onSuccess(_this);
  15904. }
  15905. };
  15906. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  15907. };
  15908. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  15909. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  15910. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  15911. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  15912. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  15913. return;
  15914. }
  15915. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15916. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15917. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  15918. var position = BABYLON.Vector3.Zero();
  15919. var normal = BABYLON.Vector3.Zero();
  15920. var uv = BABYLON.Vector2.Zero();
  15921. for (var index = 0; index < positions.length; index += 3) {
  15922. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  15923. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  15924. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  15925. // Compute height
  15926. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  15927. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  15928. var pos = (u + v * heightMapWidth) * 4;
  15929. var r = buffer[pos] / 255.0;
  15930. var g = buffer[pos + 1] / 255.0;
  15931. var b = buffer[pos + 2] / 255.0;
  15932. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  15933. normal.normalize();
  15934. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  15935. position = position.add(normal);
  15936. position.toArray(positions, index);
  15937. }
  15938. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  15939. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  15940. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  15941. };
  15942. Mesh.prototype.convertToFlatShadedMesh = function () {
  15943. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  15944. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  15945. var kinds = this.getVerticesDataKinds();
  15946. var vbs = [];
  15947. var data = [];
  15948. var newdata = [];
  15949. var updatableNormals = false;
  15950. var kindIndex;
  15951. var kind;
  15952. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15953. kind = kinds[kindIndex];
  15954. var vertexBuffer = this.getVertexBuffer(kind);
  15955. if (kind === BABYLON.VertexBuffer.NormalKind) {
  15956. updatableNormals = vertexBuffer.isUpdatable();
  15957. kinds.splice(kindIndex, 1);
  15958. kindIndex--;
  15959. continue;
  15960. }
  15961. vbs[kind] = vertexBuffer;
  15962. data[kind] = vbs[kind].getData();
  15963. newdata[kind] = [];
  15964. }
  15965. // Save previous submeshes
  15966. var previousSubmeshes = this.subMeshes.slice(0);
  15967. var indices = this.getIndices();
  15968. var totalIndices = this.getTotalIndices();
  15969. // Generating unique vertices per face
  15970. var index;
  15971. for (index = 0; index < totalIndices; index++) {
  15972. var vertexIndex = indices[index];
  15973. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15974. kind = kinds[kindIndex];
  15975. var stride = vbs[kind].getStrideSize();
  15976. for (var offset = 0; offset < stride; offset++) {
  15977. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  15978. }
  15979. }
  15980. }
  15981. // Updating faces & normal
  15982. var normals = [];
  15983. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  15984. for (index = 0; index < totalIndices; index += 3) {
  15985. indices[index] = index;
  15986. indices[index + 1] = index + 1;
  15987. indices[index + 2] = index + 2;
  15988. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  15989. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  15990. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  15991. var p1p2 = p1.subtract(p2);
  15992. var p3p2 = p3.subtract(p2);
  15993. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  15994. // Store same normals for every vertex
  15995. for (var localIndex = 0; localIndex < 3; localIndex++) {
  15996. normals.push(normal.x);
  15997. normals.push(normal.y);
  15998. normals.push(normal.z);
  15999. }
  16000. }
  16001. this.setIndices(indices);
  16002. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  16003. // Updating vertex buffers
  16004. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  16005. kind = kinds[kindIndex];
  16006. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  16007. }
  16008. // Updating submeshes
  16009. this.releaseSubMeshes();
  16010. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  16011. var previousOne = previousSubmeshes[submeshIndex];
  16012. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  16013. }
  16014. this.synchronizeInstances();
  16015. };
  16016. Mesh.prototype.convertToUnIndexedMesh = function () {
  16017. /// <summary>Remove indices by unfolding faces into buffers</summary>
  16018. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  16019. var kinds = this.getVerticesDataKinds();
  16020. var vbs = [];
  16021. var data = [];
  16022. var newdata = [];
  16023. var updatableNormals = false;
  16024. var kindIndex;
  16025. var kind;
  16026. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  16027. kind = kinds[kindIndex];
  16028. var vertexBuffer = this.getVertexBuffer(kind);
  16029. vbs[kind] = vertexBuffer;
  16030. data[kind] = vbs[kind].getData();
  16031. newdata[kind] = [];
  16032. }
  16033. // Save previous submeshes
  16034. var previousSubmeshes = this.subMeshes.slice(0);
  16035. var indices = this.getIndices();
  16036. var totalIndices = this.getTotalIndices();
  16037. // Generating unique vertices per face
  16038. var index;
  16039. for (index = 0; index < totalIndices; index++) {
  16040. var vertexIndex = indices[index];
  16041. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  16042. kind = kinds[kindIndex];
  16043. var stride = vbs[kind].getStrideSize();
  16044. for (var offset = 0; offset < stride; offset++) {
  16045. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  16046. }
  16047. }
  16048. }
  16049. // Updating indices
  16050. for (index = 0; index < totalIndices; index += 3) {
  16051. indices[index] = index;
  16052. indices[index + 1] = index + 1;
  16053. indices[index + 2] = index + 2;
  16054. }
  16055. this.setIndices(indices);
  16056. // Updating vertex buffers
  16057. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  16058. kind = kinds[kindIndex];
  16059. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  16060. }
  16061. // Updating submeshes
  16062. this.releaseSubMeshes();
  16063. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  16064. var previousOne = previousSubmeshes[submeshIndex];
  16065. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  16066. }
  16067. this._unIndexed = true;
  16068. this.synchronizeInstances();
  16069. };
  16070. // will inverse faces orientations, and invert normals too if specified
  16071. Mesh.prototype.flipFaces = function (flipNormals) {
  16072. if (flipNormals === void 0) { flipNormals = false; }
  16073. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  16074. var i;
  16075. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16076. for (i = 0; i < vertex_data.normals.length; i++) {
  16077. vertex_data.normals[i] *= -1;
  16078. }
  16079. }
  16080. var temp;
  16081. for (i = 0; i < vertex_data.indices.length; i += 3) {
  16082. // reassign indices
  16083. temp = vertex_data.indices[i + 1];
  16084. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  16085. vertex_data.indices[i + 2] = temp;
  16086. }
  16087. vertex_data.applyToMesh(this);
  16088. };
  16089. // Instances
  16090. Mesh.prototype.createInstance = function (name) {
  16091. return new BABYLON.InstancedMesh(name, this);
  16092. };
  16093. Mesh.prototype.synchronizeInstances = function () {
  16094. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  16095. var instance = this.instances[instanceIndex];
  16096. instance._syncSubMeshes();
  16097. }
  16098. };
  16099. /**
  16100. * Simplify the mesh according to the given array of settings.
  16101. * Function will return immediately and will simplify async.
  16102. * @param settings a collection of simplification settings.
  16103. * @param parallelProcessing should all levels calculate parallel or one after the other.
  16104. * @param type the type of simplification to run.
  16105. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  16106. */
  16107. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  16108. if (parallelProcessing === void 0) { parallelProcessing = true; }
  16109. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  16110. this.getScene().simplificationQueue.addTask({
  16111. settings: settings,
  16112. parallelProcessing: parallelProcessing,
  16113. mesh: this,
  16114. simplificationType: simplificationType,
  16115. successCallback: successCallback
  16116. });
  16117. };
  16118. /**
  16119. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  16120. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  16121. * This should be used together with the simplification to avoid disappearing triangles.
  16122. * @param successCallback an optional success callback to be called after the optimization finished.
  16123. */
  16124. Mesh.prototype.optimizeIndices = function (successCallback) {
  16125. var _this = this;
  16126. var indices = this.getIndices();
  16127. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16128. var vectorPositions = [];
  16129. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  16130. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  16131. }
  16132. var dupes = [];
  16133. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  16134. var realPos = vectorPositions.length - 1 - iteration;
  16135. var testedPosition = vectorPositions[realPos];
  16136. for (var j = 0; j < realPos; ++j) {
  16137. var againstPosition = vectorPositions[j];
  16138. if (testedPosition.equals(againstPosition)) {
  16139. dupes[realPos] = j;
  16140. break;
  16141. }
  16142. }
  16143. }, function () {
  16144. for (var i = 0; i < indices.length; ++i) {
  16145. indices[i] = dupes[indices[i]] || indices[i];
  16146. }
  16147. //indices are now reordered
  16148. var originalSubMeshes = _this.subMeshes.slice(0);
  16149. _this.setIndices(indices);
  16150. _this.subMeshes = originalSubMeshes;
  16151. if (successCallback) {
  16152. successCallback(_this);
  16153. }
  16154. });
  16155. };
  16156. // Statics
  16157. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  16158. var mesh = new Mesh(parsedMesh.name, scene);
  16159. mesh.id = parsedMesh.id;
  16160. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  16161. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  16162. if (parsedMesh.rotationQuaternion) {
  16163. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  16164. }
  16165. else if (parsedMesh.rotation) {
  16166. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  16167. }
  16168. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  16169. if (parsedMesh.localMatrix) {
  16170. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  16171. }
  16172. else if (parsedMesh.pivotMatrix) {
  16173. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  16174. }
  16175. mesh.setEnabled(parsedMesh.isEnabled);
  16176. mesh.isVisible = parsedMesh.isVisible;
  16177. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  16178. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  16179. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  16180. if (parsedMesh.applyFog !== undefined) {
  16181. mesh.applyFog = parsedMesh.applyFog;
  16182. }
  16183. if (parsedMesh.pickable !== undefined) {
  16184. mesh.isPickable = parsedMesh.pickable;
  16185. }
  16186. if (parsedMesh.alphaIndex !== undefined) {
  16187. mesh.alphaIndex = parsedMesh.alphaIndex;
  16188. }
  16189. mesh.receiveShadows = parsedMesh.receiveShadows;
  16190. mesh.billboardMode = parsedMesh.billboardMode;
  16191. if (parsedMesh.visibility !== undefined) {
  16192. mesh.visibility = parsedMesh.visibility;
  16193. }
  16194. mesh.checkCollisions = parsedMesh.checkCollisions;
  16195. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  16196. // freezeWorldMatrix
  16197. if (parsedMesh.freezeWorldMatrix) {
  16198. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  16199. }
  16200. // Parent
  16201. if (parsedMesh.parentId) {
  16202. mesh._waitingParentId = parsedMesh.parentId;
  16203. }
  16204. // Actions
  16205. if (parsedMesh.actions !== undefined) {
  16206. mesh._waitingActions = parsedMesh.actions;
  16207. }
  16208. // Geometry
  16209. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  16210. if (parsedMesh.delayLoadingFile) {
  16211. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  16212. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  16213. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  16214. if (parsedMesh._binaryInfo) {
  16215. mesh._binaryInfo = parsedMesh._binaryInfo;
  16216. }
  16217. mesh._delayInfo = [];
  16218. if (parsedMesh.hasUVs) {
  16219. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  16220. }
  16221. if (parsedMesh.hasUVs2) {
  16222. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  16223. }
  16224. if (parsedMesh.hasUVs3) {
  16225. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  16226. }
  16227. if (parsedMesh.hasUVs4) {
  16228. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  16229. }
  16230. if (parsedMesh.hasUVs5) {
  16231. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  16232. }
  16233. if (parsedMesh.hasUVs6) {
  16234. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  16235. }
  16236. if (parsedMesh.hasColors) {
  16237. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  16238. }
  16239. if (parsedMesh.hasMatricesIndices) {
  16240. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  16241. }
  16242. if (parsedMesh.hasMatricesWeights) {
  16243. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  16244. }
  16245. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  16246. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  16247. mesh._checkDelayState();
  16248. }
  16249. }
  16250. else {
  16251. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  16252. }
  16253. // Material
  16254. if (parsedMesh.materialId) {
  16255. mesh.setMaterialByID(parsedMesh.materialId);
  16256. }
  16257. else {
  16258. mesh.material = null;
  16259. }
  16260. // Skeleton
  16261. if (parsedMesh.skeletonId > -1) {
  16262. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  16263. if (parsedMesh.numBoneInfluencers) {
  16264. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  16265. }
  16266. }
  16267. // Animations
  16268. if (parsedMesh.animations) {
  16269. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  16270. var parsedAnimation = parsedMesh.animations[animationIndex];
  16271. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  16272. }
  16273. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  16274. }
  16275. if (parsedMesh.autoAnimate) {
  16276. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  16277. }
  16278. // Layer Mask
  16279. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  16280. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  16281. }
  16282. else {
  16283. mesh.layerMask = 0x0FFFFFFF;
  16284. }
  16285. // Instances
  16286. if (parsedMesh.instances) {
  16287. for (var index = 0; index < parsedMesh.instances.length; index++) {
  16288. var parsedInstance = parsedMesh.instances[index];
  16289. var instance = mesh.createInstance(parsedInstance.name);
  16290. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  16291. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  16292. if (parsedInstance.rotationQuaternion) {
  16293. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  16294. }
  16295. else if (parsedInstance.rotation) {
  16296. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  16297. }
  16298. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  16299. instance.checkCollisions = mesh.checkCollisions;
  16300. if (parsedMesh.animations) {
  16301. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  16302. parsedAnimation = parsedMesh.animations[animationIndex];
  16303. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  16304. }
  16305. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  16306. }
  16307. }
  16308. }
  16309. return mesh;
  16310. };
  16311. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  16312. return BABYLON.MeshBuilder.CreateRibbon(name, {
  16313. pathArray: pathArray,
  16314. closeArray: closeArray,
  16315. closePath: closePath,
  16316. offset: offset,
  16317. updatable: updatable,
  16318. sideOrientation: sideOrientation,
  16319. instance: instance
  16320. }, scene);
  16321. };
  16322. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  16323. var options = {
  16324. radius: radius,
  16325. tessellation: tessellation,
  16326. sideOrientation: sideOrientation,
  16327. updatable: updatable
  16328. };
  16329. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  16330. };
  16331. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  16332. var options = {
  16333. size: size,
  16334. sideOrientation: sideOrientation,
  16335. updatable: updatable
  16336. };
  16337. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  16338. };
  16339. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  16340. var options = {
  16341. segments: segments,
  16342. diameterX: diameter,
  16343. diameterY: diameter,
  16344. diameterZ: diameter,
  16345. sideOrientation: sideOrientation,
  16346. updatable: updatable
  16347. };
  16348. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  16349. };
  16350. // Cylinder and cone
  16351. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  16352. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  16353. if (scene !== undefined) {
  16354. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  16355. updatable = scene;
  16356. }
  16357. scene = subdivisions;
  16358. subdivisions = 1;
  16359. }
  16360. var options = {
  16361. height: height,
  16362. diameterTop: diameterTop,
  16363. diameterBottom: diameterBottom,
  16364. tessellation: tessellation,
  16365. subdivisions: subdivisions,
  16366. sideOrientation: sideOrientation,
  16367. updatable: updatable
  16368. };
  16369. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  16370. };
  16371. // Torus (Code from SharpDX.org)
  16372. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  16373. var options = {
  16374. diameter: diameter,
  16375. thickness: thickness,
  16376. tessellation: tessellation,
  16377. sideOrientation: sideOrientation,
  16378. updatable: updatable
  16379. };
  16380. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  16381. };
  16382. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  16383. var options = {
  16384. radius: radius,
  16385. tube: tube,
  16386. radialSegments: radialSegments,
  16387. tubularSegments: tubularSegments,
  16388. p: p,
  16389. q: q,
  16390. sideOrientation: sideOrientation,
  16391. updatable: updatable
  16392. };
  16393. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  16394. };
  16395. // Lines
  16396. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  16397. var options = {
  16398. points: points,
  16399. updatable: updatable,
  16400. instance: instance
  16401. };
  16402. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  16403. };
  16404. // Dashed Lines
  16405. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  16406. var options = {
  16407. points: points,
  16408. dashSize: dashSize,
  16409. gapSize: gapSize,
  16410. dashNb: dashNb,
  16411. updatable: updatable
  16412. };
  16413. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  16414. };
  16415. // Extrusion
  16416. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  16417. var options = {
  16418. shape: shape,
  16419. path: path,
  16420. scale: scale,
  16421. rotation: rotation,
  16422. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  16423. sideOrientation: sideOrientation,
  16424. instance: instance,
  16425. updatable: updatable
  16426. };
  16427. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  16428. };
  16429. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  16430. var options = {
  16431. shape: shape,
  16432. path: path,
  16433. scaleFunction: scaleFunction,
  16434. rotationFunction: rotationFunction,
  16435. ribbonCloseArray: ribbonCloseArray,
  16436. ribbonClosePath: ribbonClosePath,
  16437. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  16438. sideOrientation: sideOrientation,
  16439. instance: instance,
  16440. updatable: updatable
  16441. };
  16442. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  16443. };
  16444. // Lathe
  16445. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  16446. var options = {
  16447. shape: shape,
  16448. radius: radius,
  16449. tessellation: tessellation,
  16450. sideOrientation: sideOrientation,
  16451. updatable: updatable
  16452. };
  16453. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  16454. };
  16455. // Plane & ground
  16456. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  16457. var options = {
  16458. size: size,
  16459. width: size,
  16460. height: size,
  16461. sideOrientation: sideOrientation,
  16462. updatable: updatable
  16463. };
  16464. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  16465. };
  16466. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  16467. var options = {
  16468. width: width,
  16469. height: height,
  16470. subdivisions: subdivisions,
  16471. updatable: updatable
  16472. };
  16473. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  16474. };
  16475. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  16476. var options = {
  16477. xmin: xmin,
  16478. zmin: zmin,
  16479. xmax: xmax,
  16480. zmax: zmax,
  16481. subdivisions: subdivisions,
  16482. precision: precision,
  16483. updatable: updatable
  16484. };
  16485. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  16486. };
  16487. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  16488. var options = {
  16489. width: width,
  16490. height: height,
  16491. subdivisions: subdivisions,
  16492. minHeight: minHeight,
  16493. maxHeight: maxHeight,
  16494. updatable: updatable,
  16495. onReady: onReady
  16496. };
  16497. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  16498. };
  16499. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  16500. var options = {
  16501. path: path,
  16502. radius: radius,
  16503. tessellation: tessellation,
  16504. radiusFunction: radiusFunction,
  16505. arc: 1,
  16506. cap: cap,
  16507. updatable: updatable,
  16508. sideOrientation: sideOrientation,
  16509. instance: instance
  16510. };
  16511. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  16512. };
  16513. Mesh.CreatePolyhedron = function (name, options, scene) {
  16514. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  16515. };
  16516. Mesh.CreateIcoSphere = function (name, options, scene) {
  16517. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  16518. };
  16519. // Decals
  16520. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  16521. var options = {
  16522. position: position,
  16523. normal: normal,
  16524. size: size,
  16525. angle: angle
  16526. };
  16527. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  16528. };
  16529. // Skeletons
  16530. /**
  16531. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  16532. */
  16533. Mesh.prototype.setPositionsForCPUSkinning = function () {
  16534. var source;
  16535. if (!this._sourcePositions) {
  16536. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16537. this._sourcePositions = new Float32Array(source);
  16538. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  16539. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  16540. }
  16541. }
  16542. return this._sourcePositions;
  16543. };
  16544. /**
  16545. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  16546. */
  16547. Mesh.prototype.setNormalsForCPUSkinning = function () {
  16548. var source;
  16549. if (!this._sourceNormals) {
  16550. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16551. this._sourceNormals = new Float32Array(source);
  16552. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  16553. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  16554. }
  16555. }
  16556. return this._sourceNormals;
  16557. };
  16558. /**
  16559. * Update the vertex buffers by applying transformation from the bones
  16560. * @param {skeleton} skeleton to apply
  16561. */
  16562. Mesh.prototype.applySkeleton = function (skeleton) {
  16563. if (!this.geometry) {
  16564. return;
  16565. }
  16566. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  16567. return;
  16568. }
  16569. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  16570. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  16571. return this;
  16572. }
  16573. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16574. return this;
  16575. }
  16576. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  16577. return this;
  16578. }
  16579. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  16580. return this;
  16581. }
  16582. if (!this._sourcePositions) {
  16583. this.setPositionsForCPUSkinning();
  16584. }
  16585. if (!this._sourceNormals) {
  16586. this.setNormalsForCPUSkinning();
  16587. }
  16588. // positionsData checks for not being Float32Array will only pass at most once
  16589. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16590. if (!(positionsData instanceof Float32Array)) {
  16591. positionsData = new Float32Array(positionsData);
  16592. }
  16593. // normalsData checks for not being Float32Array will only pass at most once
  16594. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16595. if (!(normalsData instanceof Float32Array)) {
  16596. normalsData = new Float32Array(normalsData);
  16597. }
  16598. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  16599. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  16600. var needExtras = this.numBoneInfluencers > 4;
  16601. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  16602. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  16603. var skeletonMatrices = skeleton.getTransformMatrices(this);
  16604. var tempVector3 = BABYLON.Vector3.Zero();
  16605. var finalMatrix = new BABYLON.Matrix();
  16606. var tempMatrix = new BABYLON.Matrix();
  16607. var matWeightIdx = 0;
  16608. var inf;
  16609. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  16610. var weight;
  16611. for (inf = 0; inf < 4; inf++) {
  16612. weight = matricesWeightsData[matWeightIdx + inf];
  16613. if (weight > 0) {
  16614. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  16615. finalMatrix.addToSelf(tempMatrix);
  16616. }
  16617. else
  16618. break;
  16619. }
  16620. if (needExtras) {
  16621. for (inf = 0; inf < 4; inf++) {
  16622. weight = matricesWeightsExtraData[matWeightIdx + inf];
  16623. if (weight > 0) {
  16624. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  16625. finalMatrix.addToSelf(tempMatrix);
  16626. }
  16627. else
  16628. break;
  16629. }
  16630. }
  16631. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  16632. tempVector3.toArray(positionsData, index);
  16633. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  16634. tempVector3.toArray(normalsData, index);
  16635. finalMatrix.reset();
  16636. }
  16637. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  16638. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  16639. return this;
  16640. };
  16641. // Tools
  16642. Mesh.MinMax = function (meshes) {
  16643. var minVector = null;
  16644. var maxVector = null;
  16645. for (var i in meshes) {
  16646. var mesh = meshes[i];
  16647. var boundingBox = mesh.getBoundingInfo().boundingBox;
  16648. if (!minVector) {
  16649. minVector = boundingBox.minimumWorld;
  16650. maxVector = boundingBox.maximumWorld;
  16651. continue;
  16652. }
  16653. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  16654. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  16655. }
  16656. return {
  16657. min: minVector,
  16658. max: maxVector
  16659. };
  16660. };
  16661. Mesh.Center = function (meshesOrMinMaxVector) {
  16662. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  16663. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  16664. };
  16665. /**
  16666. * Merge the array of meshes into a single mesh for performance reasons.
  16667. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  16668. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  16669. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  16670. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  16671. */
  16672. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  16673. if (disposeSource === void 0) { disposeSource = true; }
  16674. var index;
  16675. if (!allow32BitsIndices) {
  16676. var totalVertices = 0;
  16677. // Counting vertices
  16678. for (index = 0; index < meshes.length; index++) {
  16679. if (meshes[index]) {
  16680. totalVertices += meshes[index].getTotalVertices();
  16681. if (totalVertices > 65536) {
  16682. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  16683. return null;
  16684. }
  16685. }
  16686. }
  16687. }
  16688. // Merge
  16689. var vertexData;
  16690. var otherVertexData;
  16691. var source;
  16692. for (index = 0; index < meshes.length; index++) {
  16693. if (meshes[index]) {
  16694. meshes[index].computeWorldMatrix(true);
  16695. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  16696. otherVertexData.transform(meshes[index].getWorldMatrix());
  16697. if (vertexData) {
  16698. vertexData.merge(otherVertexData);
  16699. }
  16700. else {
  16701. vertexData = otherVertexData;
  16702. source = meshes[index];
  16703. }
  16704. }
  16705. }
  16706. if (!meshSubclass) {
  16707. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  16708. }
  16709. vertexData.applyToMesh(meshSubclass);
  16710. // Setting properties
  16711. meshSubclass.material = source.material;
  16712. meshSubclass.checkCollisions = source.checkCollisions;
  16713. // Cleaning
  16714. if (disposeSource) {
  16715. for (index = 0; index < meshes.length; index++) {
  16716. if (meshes[index]) {
  16717. meshes[index].dispose();
  16718. }
  16719. }
  16720. }
  16721. return meshSubclass;
  16722. };
  16723. // Consts
  16724. Mesh._FRONTSIDE = 0;
  16725. Mesh._BACKSIDE = 1;
  16726. Mesh._DOUBLESIDE = 2;
  16727. Mesh._DEFAULTSIDE = 0;
  16728. Mesh._NO_CAP = 0;
  16729. Mesh._CAP_START = 1;
  16730. Mesh._CAP_END = 2;
  16731. Mesh._CAP_ALL = 3;
  16732. return Mesh;
  16733. })(BABYLON.AbstractMesh);
  16734. BABYLON.Mesh = Mesh;
  16735. })(BABYLON || (BABYLON = {}));
  16736. var BABYLON;
  16737. (function (BABYLON) {
  16738. var SubMesh = (function () {
  16739. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  16740. if (createBoundingBox === void 0) { createBoundingBox = true; }
  16741. this.materialIndex = materialIndex;
  16742. this.verticesStart = verticesStart;
  16743. this.verticesCount = verticesCount;
  16744. this.indexStart = indexStart;
  16745. this.indexCount = indexCount;
  16746. this._renderId = 0;
  16747. this._mesh = mesh;
  16748. this._renderingMesh = renderingMesh || mesh;
  16749. mesh.subMeshes.push(this);
  16750. this._trianglePlanes = [];
  16751. this._id = mesh.subMeshes.length - 1;
  16752. if (createBoundingBox) {
  16753. this.refreshBoundingInfo();
  16754. mesh.computeWorldMatrix(true);
  16755. }
  16756. }
  16757. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  16758. get: function () {
  16759. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  16760. },
  16761. enumerable: true,
  16762. configurable: true
  16763. });
  16764. SubMesh.prototype.getBoundingInfo = function () {
  16765. if (this.IsGlobal) {
  16766. return this._mesh.getBoundingInfo();
  16767. }
  16768. return this._boundingInfo;
  16769. };
  16770. SubMesh.prototype.getMesh = function () {
  16771. return this._mesh;
  16772. };
  16773. SubMesh.prototype.getRenderingMesh = function () {
  16774. return this._renderingMesh;
  16775. };
  16776. SubMesh.prototype.getMaterial = function () {
  16777. var rootMaterial = this._renderingMesh.material;
  16778. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  16779. var multiMaterial = rootMaterial;
  16780. return multiMaterial.getSubMaterial(this.materialIndex);
  16781. }
  16782. if (!rootMaterial) {
  16783. return this._mesh.getScene().defaultMaterial;
  16784. }
  16785. return rootMaterial;
  16786. };
  16787. // Methods
  16788. SubMesh.prototype.refreshBoundingInfo = function () {
  16789. this._lastColliderWorldVertices = null;
  16790. if (this.IsGlobal) {
  16791. return;
  16792. }
  16793. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16794. if (!data) {
  16795. this._boundingInfo = this._mesh._boundingInfo;
  16796. return;
  16797. }
  16798. var indices = this._renderingMesh.getIndices();
  16799. var extend;
  16800. //is this the only submesh?
  16801. if (this.indexStart === 0 && this.indexCount === indices.length) {
  16802. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  16803. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  16804. }
  16805. else {
  16806. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  16807. }
  16808. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  16809. };
  16810. SubMesh.prototype._checkCollision = function (collider) {
  16811. return this.getBoundingInfo()._checkCollision(collider);
  16812. };
  16813. SubMesh.prototype.updateBoundingInfo = function (world) {
  16814. if (!this.getBoundingInfo()) {
  16815. this.refreshBoundingInfo();
  16816. }
  16817. this.getBoundingInfo().update(world);
  16818. };
  16819. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  16820. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  16821. };
  16822. SubMesh.prototype.render = function (enableAlphaMode) {
  16823. this._renderingMesh.render(this, enableAlphaMode);
  16824. };
  16825. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  16826. if (!this._linesIndexBuffer) {
  16827. var linesIndices = [];
  16828. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  16829. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  16830. }
  16831. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  16832. this.linesIndexCount = linesIndices.length;
  16833. }
  16834. return this._linesIndexBuffer;
  16835. };
  16836. SubMesh.prototype.canIntersects = function (ray) {
  16837. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  16838. };
  16839. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  16840. var intersectInfo = null;
  16841. // Triangles test
  16842. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  16843. var p0 = positions[indices[index]];
  16844. var p1 = positions[indices[index + 1]];
  16845. var p2 = positions[indices[index + 2]];
  16846. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  16847. if (currentIntersectInfo) {
  16848. if (currentIntersectInfo.distance < 0) {
  16849. continue;
  16850. }
  16851. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  16852. intersectInfo = currentIntersectInfo;
  16853. intersectInfo.faceId = index / 3;
  16854. if (fastCheck) {
  16855. break;
  16856. }
  16857. }
  16858. }
  16859. }
  16860. return intersectInfo;
  16861. };
  16862. // Clone
  16863. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  16864. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  16865. if (!this.IsGlobal) {
  16866. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  16867. }
  16868. return result;
  16869. };
  16870. // Dispose
  16871. SubMesh.prototype.dispose = function () {
  16872. if (this._linesIndexBuffer) {
  16873. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  16874. this._linesIndexBuffer = null;
  16875. }
  16876. // Remove from mesh
  16877. var index = this._mesh.subMeshes.indexOf(this);
  16878. this._mesh.subMeshes.splice(index, 1);
  16879. };
  16880. // Statics
  16881. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  16882. var minVertexIndex = Number.MAX_VALUE;
  16883. var maxVertexIndex = -Number.MAX_VALUE;
  16884. renderingMesh = renderingMesh || mesh;
  16885. var indices = renderingMesh.getIndices();
  16886. for (var index = startIndex; index < startIndex + indexCount; index++) {
  16887. var vertexIndex = indices[index];
  16888. if (vertexIndex < minVertexIndex)
  16889. minVertexIndex = vertexIndex;
  16890. if (vertexIndex > maxVertexIndex)
  16891. maxVertexIndex = vertexIndex;
  16892. }
  16893. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  16894. };
  16895. return SubMesh;
  16896. })();
  16897. BABYLON.SubMesh = SubMesh;
  16898. })(BABYLON || (BABYLON = {}));
  16899. var BABYLON;
  16900. (function (BABYLON) {
  16901. var MeshBuilder = (function () {
  16902. function MeshBuilder() {
  16903. }
  16904. MeshBuilder.CreateBox = function (name, options, scene) {
  16905. var box = new BABYLON.Mesh(name, scene);
  16906. var vertexData = BABYLON.VertexData.CreateBox(options);
  16907. vertexData.applyToMesh(box, options.updatable);
  16908. return box;
  16909. };
  16910. MeshBuilder.CreateSphere = function (name, options, scene) {
  16911. var sphere = new BABYLON.Mesh(name, scene);
  16912. var vertexData = BABYLON.VertexData.CreateSphere(options);
  16913. vertexData.applyToMesh(sphere, options.updatable);
  16914. return sphere;
  16915. };
  16916. MeshBuilder.CreateDisc = function (name, options, scene) {
  16917. var disc = new BABYLON.Mesh(name, scene);
  16918. var vertexData = BABYLON.VertexData.CreateDisc(options);
  16919. vertexData.applyToMesh(disc, options.updatable);
  16920. return disc;
  16921. };
  16922. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  16923. var sphere = new BABYLON.Mesh(name, scene);
  16924. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  16925. vertexData.applyToMesh(sphere, options.updatable);
  16926. return sphere;
  16927. };
  16928. ;
  16929. MeshBuilder.CreateRibbon = function (name, options, scene) {
  16930. var pathArray = options.pathArray;
  16931. var closeArray = options.closeArray;
  16932. var closePath = options.closePath;
  16933. var offset = options.offset;
  16934. var sideOrientation = options.sideOrientation;
  16935. var instance = options.instance;
  16936. var updatable = options.updatable;
  16937. if (instance) {
  16938. // positionFunction : ribbon case
  16939. // only pathArray and sideOrientation parameters are taken into account for positions update
  16940. var positionFunction = function (positions) {
  16941. var minlg = pathArray[0].length;
  16942. var i = 0;
  16943. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  16944. for (var si = 1; si <= ns; si++) {
  16945. for (var p = 0; p < pathArray.length; p++) {
  16946. var path = pathArray[p];
  16947. var l = path.length;
  16948. minlg = (minlg < l) ? minlg : l;
  16949. var j = 0;
  16950. while (j < minlg) {
  16951. positions[i] = path[j].x;
  16952. positions[i + 1] = path[j].y;
  16953. positions[i + 2] = path[j].z;
  16954. j++;
  16955. i += 3;
  16956. }
  16957. if (instance._closePath) {
  16958. positions[i] = path[0].x;
  16959. positions[i + 1] = path[0].y;
  16960. positions[i + 2] = path[0].z;
  16961. i += 3;
  16962. }
  16963. }
  16964. }
  16965. };
  16966. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16967. positionFunction(positions);
  16968. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  16969. if (!(instance.areNormalsFrozen)) {
  16970. var indices = instance.getIndices();
  16971. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16972. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  16973. if (instance._closePath) {
  16974. var indexFirst = 0;
  16975. var indexLast = 0;
  16976. for (var p = 0; p < pathArray.length; p++) {
  16977. indexFirst = instance._idx[p] * 3;
  16978. if (p + 1 < pathArray.length) {
  16979. indexLast = (instance._idx[p + 1] - 1) * 3;
  16980. }
  16981. else {
  16982. indexLast = normals.length - 3;
  16983. }
  16984. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  16985. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  16986. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  16987. normals[indexLast] = normals[indexFirst];
  16988. normals[indexLast + 1] = normals[indexFirst + 1];
  16989. normals[indexLast + 2] = normals[indexFirst + 2];
  16990. }
  16991. }
  16992. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  16993. }
  16994. return instance;
  16995. }
  16996. else {
  16997. var ribbon = new BABYLON.Mesh(name, scene);
  16998. ribbon.sideOrientation = sideOrientation;
  16999. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  17000. if (closePath) {
  17001. ribbon._idx = vertexData._idx;
  17002. }
  17003. ribbon._closePath = closePath;
  17004. ribbon._closeArray = closeArray;
  17005. vertexData.applyToMesh(ribbon, updatable);
  17006. return ribbon;
  17007. }
  17008. };
  17009. MeshBuilder.CreateCylinder = function (name, options, scene) {
  17010. var cylinder = new BABYLON.Mesh(name, scene);
  17011. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  17012. vertexData.applyToMesh(cylinder, options.updatable);
  17013. return cylinder;
  17014. };
  17015. MeshBuilder.CreateTorus = function (name, options, scene) {
  17016. var torus = new BABYLON.Mesh(name, scene);
  17017. var vertexData = BABYLON.VertexData.CreateTorus(options);
  17018. vertexData.applyToMesh(torus, options.updatable);
  17019. return torus;
  17020. };
  17021. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  17022. var torusKnot = new BABYLON.Mesh(name, scene);
  17023. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  17024. vertexData.applyToMesh(torusKnot, options.updatable);
  17025. return torusKnot;
  17026. };
  17027. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  17028. var instance = options.instance;
  17029. var lines = options.lines;
  17030. if (instance) {
  17031. var positionFunction = function (positions) {
  17032. var i = 0;
  17033. for (var l = 0; l < lines.length; l++) {
  17034. var points = lines[l];
  17035. for (var p = 0; p < points.length; p++) {
  17036. positions[i] = points[p].x;
  17037. positions[i + 1] = points[p].y;
  17038. positions[i + 2] = points[p].z;
  17039. i += 3;
  17040. }
  17041. }
  17042. };
  17043. instance.updateMeshPositions(positionFunction, false);
  17044. return instance;
  17045. }
  17046. // line system creation
  17047. var lineSystem = new BABYLON.LinesMesh(name, scene);
  17048. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  17049. vertexData.applyToMesh(lineSystem, options.updatable);
  17050. return lineSystem;
  17051. };
  17052. MeshBuilder.CreateLines = function (name, options, scene) {
  17053. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  17054. return lines;
  17055. };
  17056. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  17057. var points = options.points;
  17058. var instance = options.instance;
  17059. var gapSize = options.gapSize;
  17060. var dashNb = options.dashNb;
  17061. var dashSize = options.dashSize;
  17062. if (instance) {
  17063. var positionFunction = function (positions) {
  17064. var curvect = BABYLON.Vector3.Zero();
  17065. var nbSeg = positions.length / 6;
  17066. var lg = 0;
  17067. var nb = 0;
  17068. var shft = 0;
  17069. var dashshft = 0;
  17070. var curshft = 0;
  17071. var p = 0;
  17072. var i = 0;
  17073. var j = 0;
  17074. for (i = 0; i < points.length - 1; i++) {
  17075. points[i + 1].subtractToRef(points[i], curvect);
  17076. lg += curvect.length();
  17077. }
  17078. shft = lg / nbSeg;
  17079. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  17080. for (i = 0; i < points.length - 1; i++) {
  17081. points[i + 1].subtractToRef(points[i], curvect);
  17082. nb = Math.floor(curvect.length() / shft);
  17083. curvect.normalize();
  17084. j = 0;
  17085. while (j < nb && p < positions.length) {
  17086. curshft = shft * j;
  17087. positions[p] = points[i].x + curshft * curvect.x;
  17088. positions[p + 1] = points[i].y + curshft * curvect.y;
  17089. positions[p + 2] = points[i].z + curshft * curvect.z;
  17090. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  17091. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  17092. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  17093. p += 6;
  17094. j++;
  17095. }
  17096. }
  17097. while (p < positions.length) {
  17098. positions[p] = points[i].x;
  17099. positions[p + 1] = points[i].y;
  17100. positions[p + 2] = points[i].z;
  17101. p += 3;
  17102. }
  17103. };
  17104. instance.updateMeshPositions(positionFunction, false);
  17105. return instance;
  17106. }
  17107. // dashed lines creation
  17108. var dashedLines = new BABYLON.LinesMesh(name, scene);
  17109. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  17110. vertexData.applyToMesh(dashedLines, options.updatable);
  17111. dashedLines.dashSize = dashSize;
  17112. dashedLines.gapSize = gapSize;
  17113. return dashedLines;
  17114. };
  17115. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  17116. var path = options.path;
  17117. var shape = options.shape;
  17118. var scale = options.scale || 1;
  17119. var rotation = options.rotation || 0;
  17120. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  17121. var updatable = options.updatable;
  17122. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  17123. var instance = options.instance;
  17124. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance);
  17125. };
  17126. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  17127. var path = options.path;
  17128. var shape = options.shape;
  17129. var scaleFunction = options.scaleFunction || (function () { return 1; });
  17130. var rotationFunction = options.rotationFunction || (function () { return 0; });
  17131. var ribbonCloseArray = options.ribbonCloseArray || false;
  17132. var ribbonClosePath = options.ribbonClosePath || false;
  17133. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  17134. var updatable = options.updatable;
  17135. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  17136. var instance = options.instance;
  17137. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance);
  17138. };
  17139. MeshBuilder.CreateLathe = function (name, options, scene) {
  17140. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  17141. var closed = (options.closed === undefined) ? true : options.closed;
  17142. var shape = options.shape;
  17143. var radius = options.radius || 1;
  17144. var tessellation = options.tessellation || 64;
  17145. var updatable = options.updatable;
  17146. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  17147. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  17148. var pi2 = Math.PI * 2;
  17149. var paths = new Array();
  17150. var i = 0;
  17151. var p = 0;
  17152. var step = pi2 / tessellation * arc;
  17153. var rotated;
  17154. var path = new Array();
  17155. ;
  17156. for (i = 0; i <= tessellation; i++) {
  17157. var path = [];
  17158. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  17159. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  17160. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  17161. }
  17162. for (p = 0; p < shape.length; p++) {
  17163. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  17164. path.push(rotated);
  17165. }
  17166. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  17167. 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));
  17168. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  17169. }
  17170. paths.push(path);
  17171. }
  17172. // lathe ribbon
  17173. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable }, scene);
  17174. return lathe;
  17175. };
  17176. MeshBuilder.CreatePlane = function (name, options, scene) {
  17177. var plane = new BABYLON.Mesh(name, scene);
  17178. var vertexData = BABYLON.VertexData.CreatePlane(options);
  17179. vertexData.applyToMesh(plane, options.updatable);
  17180. if (options.sourcePlane) {
  17181. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  17182. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  17183. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  17184. plane.rotate(vectorProduct, product);
  17185. }
  17186. return plane;
  17187. };
  17188. MeshBuilder.CreateGround = function (name, options, scene) {
  17189. var ground = new BABYLON.GroundMesh(name, scene);
  17190. ground._setReady(false);
  17191. ground._subdivisions = options.subdivisions || 1;
  17192. ground._width = options.width || 1;
  17193. ground._height = options.height || 1;
  17194. ground._maxX = ground._width / 2;
  17195. ground._maxZ = ground._height / 2;
  17196. ground._minX = -ground._maxX;
  17197. ground._minZ = -ground._maxZ;
  17198. var vertexData = BABYLON.VertexData.CreateGround(options);
  17199. vertexData.applyToMesh(ground, options.updatable);
  17200. ground._setReady(true);
  17201. return ground;
  17202. };
  17203. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  17204. var tiledGround = new BABYLON.Mesh(name, scene);
  17205. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  17206. vertexData.applyToMesh(tiledGround, options.updatable);
  17207. return tiledGround;
  17208. };
  17209. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  17210. var width = options.width || 10;
  17211. var height = options.height || 10;
  17212. var subdivisions = options.subdivisions || 1;
  17213. var minHeight = options.minHeight;
  17214. var maxHeight = options.maxHeight || 10;
  17215. var updatable = options.updatable;
  17216. var onReady = options.onReady;
  17217. var ground = new BABYLON.GroundMesh(name, scene);
  17218. ground._subdivisions = subdivisions;
  17219. ground._width = width;
  17220. ground._height = height;
  17221. ground._maxX = ground._width / 2;
  17222. ground._maxZ = ground._height / 2;
  17223. ground._minX = -ground._maxX;
  17224. ground._minZ = -ground._maxZ;
  17225. ground._setReady(false);
  17226. var onload = function (img) {
  17227. // Getting height map data
  17228. var canvas = document.createElement("canvas");
  17229. var context = canvas.getContext("2d");
  17230. var bufferWidth = img.width;
  17231. var bufferHeight = img.height;
  17232. canvas.width = bufferWidth;
  17233. canvas.height = bufferHeight;
  17234. context.drawImage(img, 0, 0);
  17235. // Create VertexData from map data
  17236. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  17237. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  17238. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  17239. width: width, height: height,
  17240. subdivisions: subdivisions,
  17241. minHeight: minHeight, maxHeight: maxHeight,
  17242. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  17243. });
  17244. vertexData.applyToMesh(ground, updatable);
  17245. ground._setReady(true);
  17246. //execute ready callback, if set
  17247. if (onReady) {
  17248. onReady(ground);
  17249. }
  17250. };
  17251. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  17252. return ground;
  17253. };
  17254. MeshBuilder.CreateTube = function (name, options, scene) {
  17255. var path = options.path;
  17256. var radius = options.radius || 1;
  17257. var tessellation = options.tessellation || 64;
  17258. var radiusFunction = options.radiusFunction;
  17259. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  17260. var updatable = options.updatable;
  17261. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  17262. var instance = options.instance;
  17263. options.arc = (options.arc <= 0 || options.arc > 1) ? 1 : options.arc || 1;
  17264. // tube geometry
  17265. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  17266. var tangents = path3D.getTangents();
  17267. var normals = path3D.getNormals();
  17268. var distances = path3D.getDistances();
  17269. var pi2 = Math.PI * 2;
  17270. var step = pi2 / tessellation * arc;
  17271. var returnRadius = function () { return radius; };
  17272. var radiusFunctionFinal = radiusFunction || returnRadius;
  17273. var circlePath;
  17274. var rad;
  17275. var normal;
  17276. var rotated;
  17277. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  17278. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  17279. for (var i = 0; i < path.length; i++) {
  17280. rad = radiusFunctionFinal(i, distances[i]); // current radius
  17281. circlePath = Array(); // current circle array
  17282. normal = normals[i]; // current normal
  17283. for (var t = 0; t < tessellation; t++) {
  17284. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  17285. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  17286. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  17287. rotated.scaleInPlace(rad).addInPlace(path[i]);
  17288. circlePath[t] = rotated;
  17289. }
  17290. circlePaths[index] = circlePath;
  17291. index++;
  17292. }
  17293. // cap
  17294. var capPath = function (nbPoints, pathIndex) {
  17295. var pointCap = Array();
  17296. for (var i = 0; i < nbPoints; i++) {
  17297. pointCap.push(path[pathIndex]);
  17298. }
  17299. return pointCap;
  17300. };
  17301. switch (cap) {
  17302. case BABYLON.Mesh.NO_CAP:
  17303. break;
  17304. case BABYLON.Mesh.CAP_START:
  17305. circlePaths[0] = capPath(tessellation, 0);
  17306. circlePaths[1] = circlePaths[2].slice(0);
  17307. break;
  17308. case BABYLON.Mesh.CAP_END:
  17309. circlePaths[index] = circlePaths[index - 1].slice(0);
  17310. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  17311. break;
  17312. case BABYLON.Mesh.CAP_ALL:
  17313. circlePaths[0] = capPath(tessellation, 0);
  17314. circlePaths[1] = circlePaths[2].slice(0);
  17315. circlePaths[index] = circlePaths[index - 1].slice(0);
  17316. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  17317. break;
  17318. default:
  17319. break;
  17320. }
  17321. return circlePaths;
  17322. };
  17323. var path3D;
  17324. var pathArray;
  17325. if (instance) {
  17326. var arc = options.arc || instance.arc;
  17327. path3D = (instance.path3D).update(path);
  17328. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  17329. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  17330. instance.path3D = path3D;
  17331. instance.pathArray = pathArray;
  17332. instance.arc = arc;
  17333. return instance;
  17334. }
  17335. // tube creation
  17336. path3D = new BABYLON.Path3D(path);
  17337. var newPathArray = new Array();
  17338. cap = (cap < 0 || cap > 3) ? 0 : cap;
  17339. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  17340. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation }, scene);
  17341. tube.pathArray = pathArray;
  17342. tube.path3D = path3D;
  17343. tube.tessellation = tessellation;
  17344. tube.cap = cap;
  17345. tube.arc = options.arc;
  17346. return tube;
  17347. };
  17348. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  17349. var polyhedron = new BABYLON.Mesh(name, scene);
  17350. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  17351. vertexData.applyToMesh(polyhedron, options.updatable);
  17352. return polyhedron;
  17353. };
  17354. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  17355. var indices = sourceMesh.getIndices();
  17356. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17357. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17358. var position = options.position || BABYLON.Vector3.Zero();
  17359. var normal = options.normal || BABYLON.Vector3.Up();
  17360. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  17361. var angle = options.angle || 0;
  17362. // Getting correct rotation
  17363. if (!normal) {
  17364. var target = new BABYLON.Vector3(0, 0, 1);
  17365. var camera = sourceMesh.getScene().activeCamera;
  17366. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  17367. normal = camera.globalPosition.subtract(cameraWorldTarget);
  17368. }
  17369. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  17370. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  17371. var pitch = Math.atan2(normal.y, len);
  17372. // Matrix
  17373. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  17374. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  17375. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  17376. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  17377. var vertexData = new BABYLON.VertexData();
  17378. vertexData.indices = [];
  17379. vertexData.positions = [];
  17380. vertexData.normals = [];
  17381. vertexData.uvs = [];
  17382. var currentVertexDataIndex = 0;
  17383. var extractDecalVector3 = function (indexId) {
  17384. var vertexId = indices[indexId];
  17385. var result = new BABYLON.PositionNormalVertex();
  17386. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  17387. // Send vector to decal local world
  17388. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  17389. // Get normal
  17390. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  17391. return result;
  17392. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  17393. var clip = function (vertices, axis) {
  17394. if (vertices.length === 0) {
  17395. return vertices;
  17396. }
  17397. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  17398. var clipVertices = function (v0, v1) {
  17399. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  17400. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  17401. };
  17402. var result = new Array();
  17403. for (var index = 0; index < vertices.length; index += 3) {
  17404. var v1Out;
  17405. var v2Out;
  17406. var v3Out;
  17407. var total = 0;
  17408. var nV1, nV2, nV3, nV4;
  17409. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  17410. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  17411. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  17412. v1Out = d1 > 0;
  17413. v2Out = d2 > 0;
  17414. v3Out = d3 > 0;
  17415. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  17416. switch (total) {
  17417. case 0:
  17418. result.push(vertices[index]);
  17419. result.push(vertices[index + 1]);
  17420. result.push(vertices[index + 2]);
  17421. break;
  17422. case 1:
  17423. if (v1Out) {
  17424. nV1 = vertices[index + 1];
  17425. nV2 = vertices[index + 2];
  17426. nV3 = clipVertices(vertices[index], nV1);
  17427. nV4 = clipVertices(vertices[index], nV2);
  17428. }
  17429. if (v2Out) {
  17430. nV1 = vertices[index];
  17431. nV2 = vertices[index + 2];
  17432. nV3 = clipVertices(vertices[index + 1], nV1);
  17433. nV4 = clipVertices(vertices[index + 1], nV2);
  17434. result.push(nV3);
  17435. result.push(nV2.clone());
  17436. result.push(nV1.clone());
  17437. result.push(nV2.clone());
  17438. result.push(nV3.clone());
  17439. result.push(nV4);
  17440. break;
  17441. }
  17442. if (v3Out) {
  17443. nV1 = vertices[index];
  17444. nV2 = vertices[index + 1];
  17445. nV3 = clipVertices(vertices[index + 2], nV1);
  17446. nV4 = clipVertices(vertices[index + 2], nV2);
  17447. }
  17448. result.push(nV1.clone());
  17449. result.push(nV2.clone());
  17450. result.push(nV3);
  17451. result.push(nV4);
  17452. result.push(nV3.clone());
  17453. result.push(nV2.clone());
  17454. break;
  17455. case 2:
  17456. if (!v1Out) {
  17457. nV1 = vertices[index].clone();
  17458. nV2 = clipVertices(nV1, vertices[index + 1]);
  17459. nV3 = clipVertices(nV1, vertices[index + 2]);
  17460. result.push(nV1);
  17461. result.push(nV2);
  17462. result.push(nV3);
  17463. }
  17464. if (!v2Out) {
  17465. nV1 = vertices[index + 1].clone();
  17466. nV2 = clipVertices(nV1, vertices[index + 2]);
  17467. nV3 = clipVertices(nV1, vertices[index]);
  17468. result.push(nV1);
  17469. result.push(nV2);
  17470. result.push(nV3);
  17471. }
  17472. if (!v3Out) {
  17473. nV1 = vertices[index + 2].clone();
  17474. nV2 = clipVertices(nV1, vertices[index]);
  17475. nV3 = clipVertices(nV1, vertices[index + 1]);
  17476. result.push(nV1);
  17477. result.push(nV2);
  17478. result.push(nV3);
  17479. }
  17480. break;
  17481. case 3:
  17482. break;
  17483. }
  17484. }
  17485. return result;
  17486. };
  17487. for (var index = 0; index < indices.length; index += 3) {
  17488. var faceVertices = new Array();
  17489. faceVertices.push(extractDecalVector3(index));
  17490. faceVertices.push(extractDecalVector3(index + 1));
  17491. faceVertices.push(extractDecalVector3(index + 2));
  17492. // Clip
  17493. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  17494. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  17495. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  17496. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  17497. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  17498. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  17499. if (faceVertices.length === 0) {
  17500. continue;
  17501. }
  17502. // Add UVs and get back to world
  17503. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  17504. var vertex = faceVertices[vIndex];
  17505. //TODO check for Int32Array
  17506. vertexData.indices.push(currentVertexDataIndex);
  17507. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  17508. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  17509. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  17510. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  17511. currentVertexDataIndex++;
  17512. }
  17513. }
  17514. // Return mesh
  17515. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  17516. vertexData.applyToMesh(decal);
  17517. decal.position = position.clone();
  17518. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  17519. return decal;
  17520. };
  17521. // Privates
  17522. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance) {
  17523. // extrusion geometry
  17524. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  17525. var tangents = path3D.getTangents();
  17526. var normals = path3D.getNormals();
  17527. var binormals = path3D.getBinormals();
  17528. var distances = path3D.getDistances();
  17529. var angle = 0;
  17530. var returnScale = function () { return scale; };
  17531. var returnRotation = function () { return rotation; };
  17532. var rotate = custom ? rotateFunction : returnRotation;
  17533. var scl = custom ? scaleFunction : returnScale;
  17534. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  17535. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  17536. for (var i = 0; i < curve.length; i++) {
  17537. var shapePath = new Array();
  17538. var angleStep = rotate(i, distances[i]);
  17539. var scaleRatio = scl(i, distances[i]);
  17540. for (var p = 0; p < shape.length; p++) {
  17541. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  17542. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  17543. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  17544. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  17545. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  17546. shapePath[p] = rotated;
  17547. }
  17548. shapePaths[index] = shapePath;
  17549. angle += angleStep;
  17550. index++;
  17551. }
  17552. // cap
  17553. var capPath = function (shapePath) {
  17554. var pointCap = Array();
  17555. var barycenter = BABYLON.Vector3.Zero();
  17556. var i;
  17557. for (i = 0; i < shapePath.length; i++) {
  17558. barycenter.addInPlace(shapePath[i]);
  17559. }
  17560. barycenter.scaleInPlace(1 / shapePath.length);
  17561. for (i = 0; i < shapePath.length; i++) {
  17562. pointCap.push(barycenter);
  17563. }
  17564. return pointCap;
  17565. };
  17566. switch (cap) {
  17567. case BABYLON.Mesh.NO_CAP:
  17568. break;
  17569. case BABYLON.Mesh.CAP_START:
  17570. shapePaths[0] = capPath(shapePaths[2]);
  17571. shapePaths[1] = shapePaths[2].slice(0);
  17572. break;
  17573. case BABYLON.Mesh.CAP_END:
  17574. shapePaths[index] = shapePaths[index - 1];
  17575. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  17576. break;
  17577. case BABYLON.Mesh.CAP_ALL:
  17578. shapePaths[0] = capPath(shapePaths[2]);
  17579. shapePaths[1] = shapePaths[2].slice(0);
  17580. shapePaths[index] = shapePaths[index - 1];
  17581. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  17582. break;
  17583. default:
  17584. break;
  17585. }
  17586. return shapePaths;
  17587. };
  17588. var path3D;
  17589. var pathArray;
  17590. if (instance) {
  17591. path3D = (instance.path3D).update(curve);
  17592. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  17593. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  17594. return instance;
  17595. }
  17596. // extruded shape creation
  17597. path3D = new BABYLON.Path3D(curve);
  17598. var newShapePaths = new Array();
  17599. cap = (cap < 0 || cap > 3) ? 0 : cap;
  17600. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  17601. var extrudedGeneric = BABYLON.Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  17602. extrudedGeneric.pathArray = pathArray;
  17603. extrudedGeneric.path3D = path3D;
  17604. extrudedGeneric.cap = cap;
  17605. return extrudedGeneric;
  17606. };
  17607. return MeshBuilder;
  17608. })();
  17609. BABYLON.MeshBuilder = MeshBuilder;
  17610. })(BABYLON || (BABYLON = {}));
  17611. var BABYLON;
  17612. (function (BABYLON) {
  17613. var BaseTexture = (function () {
  17614. function BaseTexture(scene) {
  17615. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  17616. this.hasAlpha = false;
  17617. this.getAlphaFromRGB = false;
  17618. this.level = 1;
  17619. this.isCube = false;
  17620. this.isRenderTarget = false;
  17621. this.animations = new Array();
  17622. this.coordinatesIndex = 0;
  17623. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  17624. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  17625. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  17626. this.anisotropicFilteringLevel = 4;
  17627. this._scene = scene;
  17628. this._scene.textures.push(this);
  17629. }
  17630. BaseTexture.prototype.getScene = function () {
  17631. return this._scene;
  17632. };
  17633. BaseTexture.prototype.getTextureMatrix = function () {
  17634. return null;
  17635. };
  17636. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  17637. return null;
  17638. };
  17639. BaseTexture.prototype.getInternalTexture = function () {
  17640. return this._texture;
  17641. };
  17642. BaseTexture.prototype.isReady = function () {
  17643. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  17644. return true;
  17645. }
  17646. if (this._texture) {
  17647. return this._texture.isReady;
  17648. }
  17649. return false;
  17650. };
  17651. BaseTexture.prototype.getSize = function () {
  17652. if (this._texture._width) {
  17653. return { width: this._texture._width, height: this._texture._height };
  17654. }
  17655. if (this._texture._size) {
  17656. return { width: this._texture._size, height: this._texture._size };
  17657. }
  17658. return { width: 0, height: 0 };
  17659. };
  17660. BaseTexture.prototype.getBaseSize = function () {
  17661. if (!this.isReady())
  17662. return { width: 0, height: 0 };
  17663. if (this._texture._size) {
  17664. return { width: this._texture._size, height: this._texture._size };
  17665. }
  17666. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  17667. };
  17668. BaseTexture.prototype.scale = function (ratio) {
  17669. };
  17670. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  17671. get: function () {
  17672. return false;
  17673. },
  17674. enumerable: true,
  17675. configurable: true
  17676. });
  17677. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  17678. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  17679. for (var index = 0; index < texturesCache.length; index++) {
  17680. var texturesCacheEntry = texturesCache[index];
  17681. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  17682. texturesCache.splice(index, 1);
  17683. return;
  17684. }
  17685. }
  17686. };
  17687. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  17688. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  17689. for (var index = 0; index < texturesCache.length; index++) {
  17690. var texturesCacheEntry = texturesCache[index];
  17691. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  17692. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  17693. texturesCacheEntry.references++;
  17694. return texturesCacheEntry;
  17695. }
  17696. }
  17697. }
  17698. return null;
  17699. };
  17700. BaseTexture.prototype.delayLoad = function () {
  17701. };
  17702. BaseTexture.prototype.clone = function () {
  17703. return null;
  17704. };
  17705. BaseTexture.prototype.releaseInternalTexture = function () {
  17706. if (this._texture) {
  17707. this._scene.getEngine().releaseInternalTexture(this._texture);
  17708. delete this._texture;
  17709. }
  17710. };
  17711. BaseTexture.prototype.dispose = function () {
  17712. // Animations
  17713. this.getScene().stopAnimation(this);
  17714. // Remove from scene
  17715. var index = this._scene.textures.indexOf(this);
  17716. if (index >= 0) {
  17717. this._scene.textures.splice(index, 1);
  17718. }
  17719. if (this._texture === undefined) {
  17720. return;
  17721. }
  17722. // Release
  17723. this.releaseInternalTexture();
  17724. // Callback
  17725. if (this.onDispose) {
  17726. this.onDispose();
  17727. }
  17728. };
  17729. BaseTexture.prototype.serialize = function () {
  17730. var serializationObject = {};
  17731. if (!this.name) {
  17732. return null;
  17733. }
  17734. serializationObject.name = this.name;
  17735. serializationObject.hasAlpha = this.hasAlpha;
  17736. serializationObject.level = this.level;
  17737. serializationObject.coordinatesIndex = this.coordinatesIndex;
  17738. serializationObject.coordinatesMode = this.coordinatesMode;
  17739. serializationObject.wrapU = this.wrapU;
  17740. serializationObject.wrapV = this.wrapV;
  17741. // Animations
  17742. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  17743. return serializationObject;
  17744. };
  17745. return BaseTexture;
  17746. })();
  17747. BABYLON.BaseTexture = BaseTexture;
  17748. })(BABYLON || (BABYLON = {}));
  17749. var BABYLON;
  17750. (function (BABYLON) {
  17751. var Texture = (function (_super) {
  17752. __extends(Texture, _super);
  17753. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  17754. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  17755. if (onLoad === void 0) { onLoad = null; }
  17756. if (onError === void 0) { onError = null; }
  17757. if (buffer === void 0) { buffer = null; }
  17758. if (deleteBuffer === void 0) { deleteBuffer = false; }
  17759. _super.call(this, scene);
  17760. this.uOffset = 0;
  17761. this.vOffset = 0;
  17762. this.uScale = 1.0;
  17763. this.vScale = 1.0;
  17764. this.uAng = 0;
  17765. this.vAng = 0;
  17766. this.wAng = 0;
  17767. this.name = url;
  17768. this.url = url;
  17769. this._noMipmap = noMipmap;
  17770. this._invertY = invertY;
  17771. this._samplingMode = samplingMode;
  17772. this._buffer = buffer;
  17773. this._deleteBuffer = deleteBuffer;
  17774. if (!url) {
  17775. return;
  17776. }
  17777. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  17778. if (!this._texture) {
  17779. if (!scene.useDelayedTextureLoading) {
  17780. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  17781. if (deleteBuffer) {
  17782. delete this._buffer;
  17783. }
  17784. }
  17785. else {
  17786. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  17787. this._delayedOnLoad = onLoad;
  17788. this._delayedOnError = onError;
  17789. }
  17790. }
  17791. else {
  17792. BABYLON.Tools.SetImmediate(function () {
  17793. if (onLoad) {
  17794. onLoad();
  17795. }
  17796. });
  17797. }
  17798. }
  17799. Texture.prototype.delayLoad = function () {
  17800. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  17801. return;
  17802. }
  17803. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  17804. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  17805. if (!this._texture) {
  17806. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer);
  17807. if (this._deleteBuffer) {
  17808. delete this._buffer;
  17809. }
  17810. }
  17811. };
  17812. Texture.prototype.updateSamplingMode = function (samplingMode) {
  17813. if (!this._texture) {
  17814. return;
  17815. }
  17816. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  17817. };
  17818. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  17819. x *= this.uScale;
  17820. y *= this.vScale;
  17821. x -= 0.5 * this.uScale;
  17822. y -= 0.5 * this.vScale;
  17823. z -= 0.5;
  17824. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  17825. t.x += 0.5 * this.uScale + this.uOffset;
  17826. t.y += 0.5 * this.vScale + this.vOffset;
  17827. t.z += 0.5;
  17828. };
  17829. Texture.prototype.getTextureMatrix = function () {
  17830. if (this.uOffset === this._cachedUOffset &&
  17831. this.vOffset === this._cachedVOffset &&
  17832. this.uScale === this._cachedUScale &&
  17833. this.vScale === this._cachedVScale &&
  17834. this.uAng === this._cachedUAng &&
  17835. this.vAng === this._cachedVAng &&
  17836. this.wAng === this._cachedWAng) {
  17837. return this._cachedTextureMatrix;
  17838. }
  17839. this._cachedUOffset = this.uOffset;
  17840. this._cachedVOffset = this.vOffset;
  17841. this._cachedUScale = this.uScale;
  17842. this._cachedVScale = this.vScale;
  17843. this._cachedUAng = this.uAng;
  17844. this._cachedVAng = this.vAng;
  17845. this._cachedWAng = this.wAng;
  17846. if (!this._cachedTextureMatrix) {
  17847. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  17848. this._rowGenerationMatrix = new BABYLON.Matrix();
  17849. this._t0 = BABYLON.Vector3.Zero();
  17850. this._t1 = BABYLON.Vector3.Zero();
  17851. this._t2 = BABYLON.Vector3.Zero();
  17852. }
  17853. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  17854. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  17855. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  17856. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  17857. this._t1.subtractInPlace(this._t0);
  17858. this._t2.subtractInPlace(this._t0);
  17859. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  17860. this._cachedTextureMatrix.m[0] = this._t1.x;
  17861. this._cachedTextureMatrix.m[1] = this._t1.y;
  17862. this._cachedTextureMatrix.m[2] = this._t1.z;
  17863. this._cachedTextureMatrix.m[4] = this._t2.x;
  17864. this._cachedTextureMatrix.m[5] = this._t2.y;
  17865. this._cachedTextureMatrix.m[6] = this._t2.z;
  17866. this._cachedTextureMatrix.m[8] = this._t0.x;
  17867. this._cachedTextureMatrix.m[9] = this._t0.y;
  17868. this._cachedTextureMatrix.m[10] = this._t0.z;
  17869. return this._cachedTextureMatrix;
  17870. };
  17871. Texture.prototype.getReflectionTextureMatrix = function () {
  17872. if (this.uOffset === this._cachedUOffset &&
  17873. this.vOffset === this._cachedVOffset &&
  17874. this.uScale === this._cachedUScale &&
  17875. this.vScale === this._cachedVScale &&
  17876. this.coordinatesMode === this._cachedCoordinatesMode) {
  17877. return this._cachedTextureMatrix;
  17878. }
  17879. if (!this._cachedTextureMatrix) {
  17880. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  17881. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  17882. }
  17883. this._cachedCoordinatesMode = this.coordinatesMode;
  17884. switch (this.coordinatesMode) {
  17885. case Texture.PLANAR_MODE:
  17886. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  17887. this._cachedTextureMatrix[0] = this.uScale;
  17888. this._cachedTextureMatrix[5] = this.vScale;
  17889. this._cachedTextureMatrix[12] = this.uOffset;
  17890. this._cachedTextureMatrix[13] = this.vOffset;
  17891. break;
  17892. case Texture.PROJECTION_MODE:
  17893. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  17894. this._projectionModeMatrix.m[0] = 0.5;
  17895. this._projectionModeMatrix.m[5] = -0.5;
  17896. this._projectionModeMatrix.m[10] = 0.0;
  17897. this._projectionModeMatrix.m[12] = 0.5;
  17898. this._projectionModeMatrix.m[13] = 0.5;
  17899. this._projectionModeMatrix.m[14] = 1.0;
  17900. this._projectionModeMatrix.m[15] = 1.0;
  17901. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  17902. break;
  17903. default:
  17904. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  17905. break;
  17906. }
  17907. return this._cachedTextureMatrix;
  17908. };
  17909. Texture.prototype.clone = function () {
  17910. var newTexture = new Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  17911. // Base texture
  17912. newTexture.hasAlpha = this.hasAlpha;
  17913. newTexture.level = this.level;
  17914. newTexture.wrapU = this.wrapU;
  17915. newTexture.wrapV = this.wrapV;
  17916. newTexture.coordinatesIndex = this.coordinatesIndex;
  17917. newTexture.coordinatesMode = this.coordinatesMode;
  17918. // Texture
  17919. newTexture.uOffset = this.uOffset;
  17920. newTexture.vOffset = this.vOffset;
  17921. newTexture.uScale = this.uScale;
  17922. newTexture.vScale = this.vScale;
  17923. newTexture.uAng = this.uAng;
  17924. newTexture.vAng = this.vAng;
  17925. newTexture.wAng = this.wAng;
  17926. return newTexture;
  17927. };
  17928. Texture.prototype.serialize = function () {
  17929. if (!this.name) {
  17930. return null;
  17931. }
  17932. var serializationObject = _super.prototype.serialize.call(this);
  17933. serializationObject.uOffset = this.uOffset;
  17934. serializationObject.vOffset = this.vOffset;
  17935. serializationObject.uScale = this.uScale;
  17936. serializationObject.vScale = this.vScale;
  17937. serializationObject.uAng = this.uAng;
  17938. serializationObject.vAng = this.vAng;
  17939. serializationObject.wAng = this.wAng;
  17940. return serializationObject;
  17941. };
  17942. // Statics
  17943. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  17944. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  17945. if (onLoad === void 0) { onLoad = null; }
  17946. if (onError === void 0) { onError = null; }
  17947. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  17948. };
  17949. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  17950. if (parsedTexture.isCube) {
  17951. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  17952. }
  17953. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  17954. return null;
  17955. }
  17956. var texture;
  17957. if (parsedTexture.mirrorPlane) {
  17958. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  17959. texture._waitingRenderList = parsedTexture.renderList;
  17960. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  17961. }
  17962. else if (parsedTexture.isRenderTarget) {
  17963. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  17964. texture._waitingRenderList = parsedTexture.renderList;
  17965. }
  17966. else {
  17967. if (parsedTexture.base64String) {
  17968. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  17969. }
  17970. else {
  17971. texture = new Texture(rootUrl + parsedTexture.name, scene);
  17972. }
  17973. }
  17974. texture.name = parsedTexture.name;
  17975. texture.hasAlpha = parsedTexture.hasAlpha;
  17976. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  17977. texture.level = parsedTexture.level;
  17978. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  17979. texture.coordinatesMode = parsedTexture.coordinatesMode;
  17980. texture.uOffset = parsedTexture.uOffset;
  17981. texture.vOffset = parsedTexture.vOffset;
  17982. texture.uScale = parsedTexture.uScale;
  17983. texture.vScale = parsedTexture.vScale;
  17984. texture.uAng = parsedTexture.uAng;
  17985. texture.vAng = parsedTexture.vAng;
  17986. texture.wAng = parsedTexture.wAng;
  17987. texture.wrapU = parsedTexture.wrapU;
  17988. texture.wrapV = parsedTexture.wrapV;
  17989. // Animations
  17990. if (parsedTexture.animations) {
  17991. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  17992. var parsedAnimation = parsedTexture.animations[animationIndex];
  17993. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  17994. }
  17995. }
  17996. return texture;
  17997. };
  17998. // Constants
  17999. Texture.NEAREST_SAMPLINGMODE = 1;
  18000. Texture.BILINEAR_SAMPLINGMODE = 2;
  18001. Texture.TRILINEAR_SAMPLINGMODE = 3;
  18002. Texture.EXPLICIT_MODE = 0;
  18003. Texture.SPHERICAL_MODE = 1;
  18004. Texture.PLANAR_MODE = 2;
  18005. Texture.CUBIC_MODE = 3;
  18006. Texture.PROJECTION_MODE = 4;
  18007. Texture.SKYBOX_MODE = 5;
  18008. Texture.INVCUBIC_MODE = 6;
  18009. Texture.EQUIRECTANGULAR_MODE = 7;
  18010. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  18011. Texture.CLAMP_ADDRESSMODE = 0;
  18012. Texture.WRAP_ADDRESSMODE = 1;
  18013. Texture.MIRROR_ADDRESSMODE = 2;
  18014. return Texture;
  18015. })(BABYLON.BaseTexture);
  18016. BABYLON.Texture = Texture;
  18017. })(BABYLON || (BABYLON = {}));
  18018. var BABYLON;
  18019. (function (BABYLON) {
  18020. var CubeTexture = (function (_super) {
  18021. __extends(CubeTexture, _super);
  18022. function CubeTexture(rootUrl, scene, extensions, noMipmap, files) {
  18023. _super.call(this, scene);
  18024. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  18025. this.name = rootUrl;
  18026. this.url = rootUrl;
  18027. this._noMipmap = noMipmap;
  18028. this.hasAlpha = false;
  18029. if (!rootUrl && !files) {
  18030. return;
  18031. }
  18032. this._texture = this._getFromCache(rootUrl, noMipmap);
  18033. if (!files) {
  18034. if (!extensions) {
  18035. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  18036. }
  18037. files = [];
  18038. for (var index = 0; index < extensions.length; index++) {
  18039. files.push(rootUrl + extensions[index]);
  18040. }
  18041. this._extensions = extensions;
  18042. }
  18043. this._files = files;
  18044. if (!this._texture) {
  18045. if (!scene.useDelayedTextureLoading) {
  18046. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap);
  18047. }
  18048. else {
  18049. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  18050. }
  18051. }
  18052. this.isCube = true;
  18053. this._textureMatrix = BABYLON.Matrix.Identity();
  18054. }
  18055. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  18056. return new CubeTexture("", scene, null, noMipmap, files);
  18057. };
  18058. CubeTexture.prototype.clone = function () {
  18059. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap, this._files);
  18060. // Base texture
  18061. newTexture.level = this.level;
  18062. newTexture.wrapU = this.wrapU;
  18063. newTexture.wrapV = this.wrapV;
  18064. newTexture.coordinatesIndex = this.coordinatesIndex;
  18065. newTexture.coordinatesMode = this.coordinatesMode;
  18066. return newTexture;
  18067. };
  18068. // Methods
  18069. CubeTexture.prototype.delayLoad = function () {
  18070. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  18071. return;
  18072. }
  18073. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  18074. this._texture = this._getFromCache(this.url, this._noMipmap);
  18075. if (!this._texture) {
  18076. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  18077. }
  18078. };
  18079. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  18080. return this._textureMatrix;
  18081. };
  18082. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  18083. var texture = null;
  18084. if ((parsedTexture.name || parsedTexture.extensions) && !parsedTexture.isRenderTarget) {
  18085. texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  18086. texture.name = parsedTexture.name;
  18087. texture.hasAlpha = parsedTexture.hasAlpha;
  18088. texture.level = parsedTexture.level;
  18089. texture.coordinatesMode = parsedTexture.coordinatesMode;
  18090. }
  18091. return texture;
  18092. };
  18093. CubeTexture.prototype.serialize = function () {
  18094. if (!this.name) {
  18095. return null;
  18096. }
  18097. var serializationObject = {};
  18098. serializationObject.name = this.name;
  18099. serializationObject.hasAlpha = this.hasAlpha;
  18100. serializationObject.isCube = true;
  18101. serializationObject.level = this.level;
  18102. serializationObject.coordinatesMode = this.coordinatesMode;
  18103. return serializationObject;
  18104. };
  18105. return CubeTexture;
  18106. })(BABYLON.BaseTexture);
  18107. BABYLON.CubeTexture = CubeTexture;
  18108. })(BABYLON || (BABYLON = {}));
  18109. var BABYLON;
  18110. (function (BABYLON) {
  18111. var RenderTargetTexture = (function (_super) {
  18112. __extends(RenderTargetTexture, _super);
  18113. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube) {
  18114. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  18115. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  18116. if (isCube === void 0) { isCube = false; }
  18117. _super.call(this, null, scene, !generateMipMaps);
  18118. this.isCube = isCube;
  18119. this.renderList = new Array();
  18120. this.renderParticles = true;
  18121. this.renderSprites = false;
  18122. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  18123. this._currentRefreshId = -1;
  18124. this._refreshRate = 1;
  18125. this.name = name;
  18126. this.isRenderTarget = true;
  18127. this._size = size;
  18128. this._generateMipMaps = generateMipMaps;
  18129. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  18130. if (isCube) {
  18131. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  18132. this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  18133. this._textureMatrix = BABYLON.Matrix.Identity();
  18134. }
  18135. else {
  18136. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  18137. }
  18138. // Rendering groups
  18139. this._renderingManager = new BABYLON.RenderingManager(scene);
  18140. }
  18141. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  18142. get: function () {
  18143. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  18144. },
  18145. enumerable: true,
  18146. configurable: true
  18147. });
  18148. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  18149. get: function () {
  18150. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  18151. },
  18152. enumerable: true,
  18153. configurable: true
  18154. });
  18155. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  18156. get: function () {
  18157. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  18158. },
  18159. enumerable: true,
  18160. configurable: true
  18161. });
  18162. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  18163. this._currentRefreshId = -1;
  18164. };
  18165. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  18166. get: function () {
  18167. return this._refreshRate;
  18168. },
  18169. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  18170. set: function (value) {
  18171. this._refreshRate = value;
  18172. this.resetRefreshCounter();
  18173. },
  18174. enumerable: true,
  18175. configurable: true
  18176. });
  18177. RenderTargetTexture.prototype._shouldRender = function () {
  18178. if (this._currentRefreshId === -1) {
  18179. this._currentRefreshId = 1;
  18180. return true;
  18181. }
  18182. if (this.refreshRate === this._currentRefreshId) {
  18183. this._currentRefreshId = 1;
  18184. return true;
  18185. }
  18186. this._currentRefreshId++;
  18187. return false;
  18188. };
  18189. RenderTargetTexture.prototype.isReady = function () {
  18190. if (!this.getScene().renderTargetsEnabled) {
  18191. return false;
  18192. }
  18193. return _super.prototype.isReady.call(this);
  18194. };
  18195. RenderTargetTexture.prototype.getRenderSize = function () {
  18196. return this._size;
  18197. };
  18198. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  18199. get: function () {
  18200. return true;
  18201. },
  18202. enumerable: true,
  18203. configurable: true
  18204. });
  18205. RenderTargetTexture.prototype.scale = function (ratio) {
  18206. var newSize = this._size * ratio;
  18207. this.resize(newSize, this._generateMipMaps);
  18208. };
  18209. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  18210. if (this.isCube) {
  18211. return this._textureMatrix;
  18212. }
  18213. return _super.prototype.getReflectionTextureMatrix.call(this);
  18214. };
  18215. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  18216. this.releaseInternalTexture();
  18217. if (this.isCube) {
  18218. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
  18219. }
  18220. else {
  18221. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  18222. }
  18223. };
  18224. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  18225. var scene = this.getScene();
  18226. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  18227. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  18228. }
  18229. if (this._waitingRenderList) {
  18230. this.renderList = [];
  18231. for (var index = 0; index < this._waitingRenderList.length; index++) {
  18232. var id = this._waitingRenderList[index];
  18233. this.renderList.push(scene.getMeshByID(id));
  18234. }
  18235. delete this._waitingRenderList;
  18236. }
  18237. if (this.renderList && this.renderList.length === 0) {
  18238. return;
  18239. }
  18240. // Prepare renderingManager
  18241. this._renderingManager.reset();
  18242. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  18243. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  18244. var mesh = currentRenderList[meshIndex];
  18245. if (mesh) {
  18246. if (!mesh.isReady()) {
  18247. // Reset _currentRefreshId
  18248. this.resetRefreshCounter();
  18249. continue;
  18250. }
  18251. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  18252. mesh._activate(scene.getRenderId());
  18253. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  18254. var subMesh = mesh.subMeshes[subIndex];
  18255. scene._activeIndices += subMesh.indexCount;
  18256. this._renderingManager.dispatch(subMesh);
  18257. }
  18258. }
  18259. }
  18260. }
  18261. if (this.isCube) {
  18262. for (var face = 0; face < 6; face++) {
  18263. this.renderToTarget(face, currentRenderList, useCameraPostProcess, dumpForDebug);
  18264. scene.incrementRenderId();
  18265. }
  18266. }
  18267. else {
  18268. this.renderToTarget(0, currentRenderList, useCameraPostProcess, dumpForDebug);
  18269. }
  18270. if (this.onAfterUnbind) {
  18271. this.onAfterUnbind();
  18272. }
  18273. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  18274. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  18275. }
  18276. scene.resetCachedMaterial();
  18277. };
  18278. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, useCameraPostProcess, dumpForDebug) {
  18279. var scene = this.getScene();
  18280. var engine = scene.getEngine();
  18281. // Bind
  18282. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  18283. if (this.isCube) {
  18284. engine.bindFramebuffer(this._texture, faceIndex);
  18285. }
  18286. else {
  18287. engine.bindFramebuffer(this._texture);
  18288. }
  18289. }
  18290. if (this.onBeforeRender) {
  18291. this.onBeforeRender(faceIndex);
  18292. }
  18293. // Clear
  18294. if (this.onClear) {
  18295. this.onClear(engine);
  18296. }
  18297. else {
  18298. engine.clear(scene.clearColor, true, true);
  18299. }
  18300. if (!this._doNotChangeAspectRatio) {
  18301. scene.updateTransformMatrix(true);
  18302. }
  18303. // Render
  18304. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  18305. if (useCameraPostProcess) {
  18306. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  18307. }
  18308. if (!this._doNotChangeAspectRatio) {
  18309. scene.updateTransformMatrix(true);
  18310. }
  18311. if (this.onAfterRender) {
  18312. this.onAfterRender(faceIndex);
  18313. }
  18314. // Dump ?
  18315. if (dumpForDebug) {
  18316. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  18317. }
  18318. // Unbind
  18319. if (!this.isCube || faceIndex === 5) {
  18320. if (this.isCube) {
  18321. if (faceIndex === 5) {
  18322. engine.generateMipMapsForCubemap(this._texture);
  18323. }
  18324. }
  18325. engine.unBindFramebuffer(this._texture, this.isCube);
  18326. }
  18327. };
  18328. RenderTargetTexture.prototype.clone = function () {
  18329. var textureSize = this.getSize();
  18330. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  18331. // Base texture
  18332. newTexture.hasAlpha = this.hasAlpha;
  18333. newTexture.level = this.level;
  18334. // RenderTarget Texture
  18335. newTexture.coordinatesMode = this.coordinatesMode;
  18336. newTexture.renderList = this.renderList.slice(0);
  18337. return newTexture;
  18338. };
  18339. RenderTargetTexture.prototype.serialize = function () {
  18340. if (!this.name) {
  18341. return null;
  18342. }
  18343. var serializationObject = _super.prototype.serialize.call(this);
  18344. serializationObject.renderTargetSize = this.getRenderSize();
  18345. serializationObject.renderList = [];
  18346. for (var index = 0; index < this.renderList.length; index++) {
  18347. serializationObject.renderList.push(this.renderList[index].id);
  18348. }
  18349. return serializationObject;
  18350. };
  18351. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  18352. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  18353. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  18354. return RenderTargetTexture;
  18355. })(BABYLON.Texture);
  18356. BABYLON.RenderTargetTexture = RenderTargetTexture;
  18357. })(BABYLON || (BABYLON = {}));
  18358. var BABYLON;
  18359. (function (BABYLON) {
  18360. var ProceduralTexture = (function (_super) {
  18361. __extends(ProceduralTexture, _super);
  18362. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  18363. if (generateMipMaps === void 0) { generateMipMaps = true; }
  18364. if (isCube === void 0) { isCube = false; }
  18365. _super.call(this, null, scene, !generateMipMaps);
  18366. this.isCube = isCube;
  18367. this.isEnabled = true;
  18368. this._currentRefreshId = -1;
  18369. this._refreshRate = 1;
  18370. this._vertexDeclaration = [2];
  18371. this._vertexStrideSize = 2 * 4;
  18372. this._uniforms = new Array();
  18373. this._samplers = new Array();
  18374. this._textures = new Array();
  18375. this._floats = new Array();
  18376. this._floatsArrays = {};
  18377. this._colors3 = new Array();
  18378. this._colors4 = new Array();
  18379. this._vectors2 = new Array();
  18380. this._vectors3 = new Array();
  18381. this._matrices = new Array();
  18382. this._fallbackTextureUsed = false;
  18383. scene._proceduralTextures.push(this);
  18384. this.name = name;
  18385. this.isRenderTarget = true;
  18386. this._size = size;
  18387. this._generateMipMaps = generateMipMaps;
  18388. this.setFragment(fragment);
  18389. this._fallbackTexture = fallbackTexture;
  18390. if (isCube) {
  18391. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  18392. this.setFloat("face", 0);
  18393. }
  18394. else {
  18395. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  18396. }
  18397. // VBO
  18398. var vertices = [];
  18399. vertices.push(1, 1);
  18400. vertices.push(-1, 1);
  18401. vertices.push(-1, -1);
  18402. vertices.push(1, -1);
  18403. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  18404. // Indices
  18405. var indices = [];
  18406. indices.push(0);
  18407. indices.push(1);
  18408. indices.push(2);
  18409. indices.push(0);
  18410. indices.push(2);
  18411. indices.push(3);
  18412. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  18413. }
  18414. ProceduralTexture.prototype.reset = function () {
  18415. if (this._effect === undefined) {
  18416. return;
  18417. }
  18418. var engine = this.getScene().getEngine();
  18419. engine._releaseEffect(this._effect);
  18420. };
  18421. ProceduralTexture.prototype.isReady = function () {
  18422. var _this = this;
  18423. var engine = this.getScene().getEngine();
  18424. var shaders;
  18425. if (!this._fragment) {
  18426. return false;
  18427. }
  18428. if (this._fallbackTextureUsed) {
  18429. return true;
  18430. }
  18431. if (this._fragment.fragmentElement !== undefined) {
  18432. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  18433. }
  18434. else {
  18435. shaders = { vertex: "procedural", fragment: this._fragment };
  18436. }
  18437. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  18438. _this.releaseInternalTexture();
  18439. if (_this._fallbackTexture) {
  18440. _this._texture = _this._fallbackTexture._texture;
  18441. _this._texture.references++;
  18442. }
  18443. _this._fallbackTextureUsed = true;
  18444. });
  18445. return this._effect.isReady();
  18446. };
  18447. ProceduralTexture.prototype.resetRefreshCounter = function () {
  18448. this._currentRefreshId = -1;
  18449. };
  18450. ProceduralTexture.prototype.setFragment = function (fragment) {
  18451. this._fragment = fragment;
  18452. };
  18453. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  18454. get: function () {
  18455. return this._refreshRate;
  18456. },
  18457. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  18458. set: function (value) {
  18459. this._refreshRate = value;
  18460. this.resetRefreshCounter();
  18461. },
  18462. enumerable: true,
  18463. configurable: true
  18464. });
  18465. ProceduralTexture.prototype._shouldRender = function () {
  18466. if (!this.isEnabled || !this.isReady() || !this._texture) {
  18467. return false;
  18468. }
  18469. if (this._fallbackTextureUsed) {
  18470. return false;
  18471. }
  18472. if (this._currentRefreshId === -1) {
  18473. this._currentRefreshId = 1;
  18474. return true;
  18475. }
  18476. if (this.refreshRate === this._currentRefreshId) {
  18477. this._currentRefreshId = 1;
  18478. return true;
  18479. }
  18480. this._currentRefreshId++;
  18481. return false;
  18482. };
  18483. ProceduralTexture.prototype.getRenderSize = function () {
  18484. return this._size;
  18485. };
  18486. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  18487. if (this._fallbackTextureUsed) {
  18488. return;
  18489. }
  18490. this.releaseInternalTexture();
  18491. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  18492. };
  18493. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  18494. if (this._uniforms.indexOf(uniformName) === -1) {
  18495. this._uniforms.push(uniformName);
  18496. }
  18497. };
  18498. ProceduralTexture.prototype.setTexture = function (name, texture) {
  18499. if (this._samplers.indexOf(name) === -1) {
  18500. this._samplers.push(name);
  18501. }
  18502. this._textures[name] = texture;
  18503. return this;
  18504. };
  18505. ProceduralTexture.prototype.setFloat = function (name, value) {
  18506. this._checkUniform(name);
  18507. this._floats[name] = value;
  18508. return this;
  18509. };
  18510. ProceduralTexture.prototype.setFloats = function (name, value) {
  18511. this._checkUniform(name);
  18512. this._floatsArrays[name] = value;
  18513. return this;
  18514. };
  18515. ProceduralTexture.prototype.setColor3 = function (name, value) {
  18516. this._checkUniform(name);
  18517. this._colors3[name] = value;
  18518. return this;
  18519. };
  18520. ProceduralTexture.prototype.setColor4 = function (name, value) {
  18521. this._checkUniform(name);
  18522. this._colors4[name] = value;
  18523. return this;
  18524. };
  18525. ProceduralTexture.prototype.setVector2 = function (name, value) {
  18526. this._checkUniform(name);
  18527. this._vectors2[name] = value;
  18528. return this;
  18529. };
  18530. ProceduralTexture.prototype.setVector3 = function (name, value) {
  18531. this._checkUniform(name);
  18532. this._vectors3[name] = value;
  18533. return this;
  18534. };
  18535. ProceduralTexture.prototype.setMatrix = function (name, value) {
  18536. this._checkUniform(name);
  18537. this._matrices[name] = value;
  18538. return this;
  18539. };
  18540. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  18541. var scene = this.getScene();
  18542. var engine = scene.getEngine();
  18543. // Render
  18544. engine.enableEffect(this._effect);
  18545. engine.setState(false);
  18546. // Texture
  18547. for (var name in this._textures) {
  18548. this._effect.setTexture(name, this._textures[name]);
  18549. }
  18550. // Float
  18551. for (name in this._floats) {
  18552. this._effect.setFloat(name, this._floats[name]);
  18553. }
  18554. // Floats
  18555. for (name in this._floatsArrays) {
  18556. this._effect.setArray(name, this._floatsArrays[name]);
  18557. }
  18558. // Color3
  18559. for (name in this._colors3) {
  18560. this._effect.setColor3(name, this._colors3[name]);
  18561. }
  18562. // Color4
  18563. for (name in this._colors4) {
  18564. var color = this._colors4[name];
  18565. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  18566. }
  18567. // Vector2
  18568. for (name in this._vectors2) {
  18569. this._effect.setVector2(name, this._vectors2[name]);
  18570. }
  18571. // Vector3
  18572. for (name in this._vectors3) {
  18573. this._effect.setVector3(name, this._vectors3[name]);
  18574. }
  18575. // Matrix
  18576. for (name in this._matrices) {
  18577. this._effect.setMatrix(name, this._matrices[name]);
  18578. }
  18579. // VBOs
  18580. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  18581. if (this.isCube) {
  18582. for (var face = 0; face < 6; face++) {
  18583. engine.bindFramebuffer(this._texture, face);
  18584. this._effect.setFloat("face", face);
  18585. // Clear
  18586. engine.clear(scene.clearColor, true, true);
  18587. // Draw order
  18588. engine.draw(true, 0, 6);
  18589. // Mipmaps
  18590. if (face === 5) {
  18591. engine.generateMipMapsForCubemap(this._texture);
  18592. }
  18593. }
  18594. }
  18595. else {
  18596. engine.bindFramebuffer(this._texture);
  18597. // Clear
  18598. engine.clear(scene.clearColor, true, true);
  18599. // Draw order
  18600. engine.draw(true, 0, 6);
  18601. }
  18602. // Unbind
  18603. engine.unBindFramebuffer(this._texture, this.isCube);
  18604. if (this.onGenerated) {
  18605. this.onGenerated();
  18606. }
  18607. };
  18608. ProceduralTexture.prototype.clone = function () {
  18609. var textureSize = this.getSize();
  18610. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  18611. // Base texture
  18612. newTexture.hasAlpha = this.hasAlpha;
  18613. newTexture.level = this.level;
  18614. // RenderTarget Texture
  18615. newTexture.coordinatesMode = this.coordinatesMode;
  18616. return newTexture;
  18617. };
  18618. ProceduralTexture.prototype.dispose = function () {
  18619. var index = this.getScene()._proceduralTextures.indexOf(this);
  18620. if (index >= 0) {
  18621. this.getScene()._proceduralTextures.splice(index, 1);
  18622. }
  18623. _super.prototype.dispose.call(this);
  18624. };
  18625. return ProceduralTexture;
  18626. })(BABYLON.Texture);
  18627. BABYLON.ProceduralTexture = ProceduralTexture;
  18628. })(BABYLON || (BABYLON = {}));
  18629. var BABYLON;
  18630. (function (BABYLON) {
  18631. var MirrorTexture = (function (_super) {
  18632. __extends(MirrorTexture, _super);
  18633. function MirrorTexture(name, size, scene, generateMipMaps) {
  18634. var _this = this;
  18635. _super.call(this, name, size, scene, generateMipMaps, true);
  18636. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  18637. this._transformMatrix = BABYLON.Matrix.Zero();
  18638. this._mirrorMatrix = BABYLON.Matrix.Zero();
  18639. this.onBeforeRender = function () {
  18640. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  18641. _this._savedViewMatrix = scene.getViewMatrix();
  18642. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  18643. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  18644. scene.clipPlane = _this.mirrorPlane;
  18645. scene.getEngine().cullBackFaces = false;
  18646. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  18647. };
  18648. this.onAfterRender = function () {
  18649. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  18650. scene.getEngine().cullBackFaces = true;
  18651. scene._mirroredCameraPosition = null;
  18652. delete scene.clipPlane;
  18653. };
  18654. }
  18655. MirrorTexture.prototype.clone = function () {
  18656. var textureSize = this.getSize();
  18657. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  18658. // Base texture
  18659. newTexture.hasAlpha = this.hasAlpha;
  18660. newTexture.level = this.level;
  18661. // Mirror Texture
  18662. newTexture.mirrorPlane = this.mirrorPlane.clone();
  18663. newTexture.renderList = this.renderList.slice(0);
  18664. return newTexture;
  18665. };
  18666. MirrorTexture.prototype.serialize = function () {
  18667. if (!this.name) {
  18668. return null;
  18669. }
  18670. var serializationObject = _super.prototype.serialize.call(this);
  18671. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  18672. return serializationObject;
  18673. };
  18674. return MirrorTexture;
  18675. })(BABYLON.RenderTargetTexture);
  18676. BABYLON.MirrorTexture = MirrorTexture;
  18677. })(BABYLON || (BABYLON = {}));
  18678. var BABYLON;
  18679. (function (BABYLON) {
  18680. /**
  18681. * Creates a refraction texture used by refraction channel of the standard material.
  18682. * @param name the texture name
  18683. * @param size size of the underlying texture
  18684. * @param scene root scene
  18685. */
  18686. var RefractionTexture = (function (_super) {
  18687. __extends(RefractionTexture, _super);
  18688. function RefractionTexture(name, size, scene, generateMipMaps) {
  18689. var _this = this;
  18690. _super.call(this, name, size, scene, generateMipMaps, true);
  18691. this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  18692. this.depth = 2.0;
  18693. this.onBeforeRender = function () {
  18694. scene.clipPlane = _this.refractionPlane;
  18695. };
  18696. this.onAfterRender = function () {
  18697. delete scene.clipPlane;
  18698. };
  18699. }
  18700. RefractionTexture.prototype.clone = function () {
  18701. var textureSize = this.getSize();
  18702. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  18703. // Base texture
  18704. newTexture.hasAlpha = this.hasAlpha;
  18705. newTexture.level = this.level;
  18706. // Refraction Texture
  18707. newTexture.refractionPlane = this.refractionPlane.clone();
  18708. newTexture.renderList = this.renderList.slice(0);
  18709. newTexture.depth = this.depth;
  18710. return newTexture;
  18711. };
  18712. RefractionTexture.prototype.serialize = function () {
  18713. if (!this.name) {
  18714. return null;
  18715. }
  18716. var serializationObject = _super.prototype.serialize.call(this);
  18717. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  18718. serializationObject.depth = this.depth;
  18719. return serializationObject;
  18720. };
  18721. return RefractionTexture;
  18722. })(BABYLON.RenderTargetTexture);
  18723. BABYLON.RefractionTexture = RefractionTexture;
  18724. })(BABYLON || (BABYLON = {}));
  18725. var BABYLON;
  18726. (function (BABYLON) {
  18727. var DynamicTexture = (function (_super) {
  18728. __extends(DynamicTexture, _super);
  18729. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  18730. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  18731. _super.call(this, null, scene, !generateMipMaps);
  18732. this.name = name;
  18733. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  18734. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  18735. this._generateMipMaps = generateMipMaps;
  18736. if (options.getContext) {
  18737. this._canvas = options;
  18738. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  18739. }
  18740. else {
  18741. this._canvas = document.createElement("canvas");
  18742. if (options.width) {
  18743. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  18744. }
  18745. else {
  18746. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  18747. }
  18748. }
  18749. var textureSize = this.getSize();
  18750. this._canvas.width = textureSize.width;
  18751. this._canvas.height = textureSize.height;
  18752. this._context = this._canvas.getContext("2d");
  18753. }
  18754. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  18755. get: function () {
  18756. return true;
  18757. },
  18758. enumerable: true,
  18759. configurable: true
  18760. });
  18761. DynamicTexture.prototype.scale = function (ratio) {
  18762. var textureSize = this.getSize();
  18763. textureSize.width *= ratio;
  18764. textureSize.height *= ratio;
  18765. this._canvas.width = textureSize.width;
  18766. this._canvas.height = textureSize.height;
  18767. this.releaseInternalTexture();
  18768. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  18769. };
  18770. DynamicTexture.prototype.getContext = function () {
  18771. return this._context;
  18772. };
  18773. DynamicTexture.prototype.clear = function () {
  18774. var size = this.getSize();
  18775. this._context.fillRect(0, 0, size.width, size.height);
  18776. };
  18777. DynamicTexture.prototype.update = function (invertY) {
  18778. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  18779. };
  18780. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  18781. if (update === void 0) { update = true; }
  18782. var size = this.getSize();
  18783. if (clearColor) {
  18784. this._context.fillStyle = clearColor;
  18785. this._context.fillRect(0, 0, size.width, size.height);
  18786. }
  18787. this._context.font = font;
  18788. if (x === null) {
  18789. var textSize = this._context.measureText(text);
  18790. x = (size.width - textSize.width) / 2;
  18791. }
  18792. this._context.fillStyle = color;
  18793. this._context.fillText(text, x, y);
  18794. if (update) {
  18795. this.update(invertY);
  18796. }
  18797. };
  18798. DynamicTexture.prototype.clone = function () {
  18799. var textureSize = this.getSize();
  18800. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  18801. // Base texture
  18802. newTexture.hasAlpha = this.hasAlpha;
  18803. newTexture.level = this.level;
  18804. // Dynamic Texture
  18805. newTexture.wrapU = this.wrapU;
  18806. newTexture.wrapV = this.wrapV;
  18807. return newTexture;
  18808. };
  18809. return DynamicTexture;
  18810. })(BABYLON.Texture);
  18811. BABYLON.DynamicTexture = DynamicTexture;
  18812. })(BABYLON || (BABYLON = {}));
  18813. var BABYLON;
  18814. (function (BABYLON) {
  18815. var VideoTexture = (function (_super) {
  18816. __extends(VideoTexture, _super);
  18817. function VideoTexture(name, urls, scene, generateMipMaps, invertY, samplingMode) {
  18818. var _this = this;
  18819. if (generateMipMaps === void 0) { generateMipMaps = false; }
  18820. if (invertY === void 0) { invertY = false; }
  18821. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  18822. _super.call(this, null, scene, !generateMipMaps, invertY);
  18823. this._autoLaunch = true;
  18824. this.name = name;
  18825. this.video = document.createElement("video");
  18826. this.video.autoplay = false;
  18827. this.video.loop = true;
  18828. this.video.addEventListener("canplaythrough", function () {
  18829. if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
  18830. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  18831. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  18832. }
  18833. else {
  18834. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  18835. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  18836. generateMipMaps = false;
  18837. }
  18838. _this._texture = scene.getEngine().createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, generateMipMaps, samplingMode, false);
  18839. _this._texture.isReady = true;
  18840. });
  18841. urls.forEach(function (url) {
  18842. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  18843. var source = document.createElement("source");
  18844. source.src = url;
  18845. _this.video.appendChild(source);
  18846. });
  18847. this._lastUpdate = BABYLON.Tools.Now;
  18848. }
  18849. VideoTexture.prototype.update = function () {
  18850. if (this._autoLaunch) {
  18851. this._autoLaunch = false;
  18852. this.video.play();
  18853. }
  18854. var now = BABYLON.Tools.Now;
  18855. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  18856. return false;
  18857. }
  18858. this._lastUpdate = now;
  18859. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  18860. return true;
  18861. };
  18862. return VideoTexture;
  18863. })(BABYLON.Texture);
  18864. BABYLON.VideoTexture = VideoTexture;
  18865. })(BABYLON || (BABYLON = {}));
  18866. var BABYLON;
  18867. (function (BABYLON) {
  18868. var CustomProceduralTexture = (function (_super) {
  18869. __extends(CustomProceduralTexture, _super);
  18870. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  18871. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  18872. this._animate = true;
  18873. this._time = 0;
  18874. this._texturePath = texturePath;
  18875. //Try to load json
  18876. this.loadJson(texturePath);
  18877. this.refreshRate = 1;
  18878. }
  18879. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  18880. var _this = this;
  18881. var that = this;
  18882. function noConfigFile() {
  18883. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  18884. try {
  18885. that.setFragment(that._texturePath);
  18886. }
  18887. catch (ex) {
  18888. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  18889. }
  18890. }
  18891. var configFileUrl = jsonUrl + "/config.json";
  18892. var xhr = new XMLHttpRequest();
  18893. xhr.open("GET", configFileUrl, true);
  18894. xhr.addEventListener("load", function () {
  18895. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  18896. try {
  18897. _this._config = JSON.parse(xhr.response);
  18898. _this.updateShaderUniforms();
  18899. _this.updateTextures();
  18900. _this.setFragment(_this._texturePath + "/custom");
  18901. _this._animate = _this._config.animate;
  18902. _this.refreshRate = _this._config.refreshrate;
  18903. }
  18904. catch (ex) {
  18905. noConfigFile();
  18906. }
  18907. }
  18908. else {
  18909. noConfigFile();
  18910. }
  18911. }, false);
  18912. xhr.addEventListener("error", function () {
  18913. noConfigFile();
  18914. }, false);
  18915. try {
  18916. xhr.send();
  18917. }
  18918. catch (ex) {
  18919. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  18920. }
  18921. };
  18922. CustomProceduralTexture.prototype.isReady = function () {
  18923. if (!_super.prototype.isReady.call(this)) {
  18924. return false;
  18925. }
  18926. for (var name in this._textures) {
  18927. var texture = this._textures[name];
  18928. if (!texture.isReady()) {
  18929. return false;
  18930. }
  18931. }
  18932. return true;
  18933. };
  18934. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  18935. if (this._animate) {
  18936. this._time += this.getScene().getAnimationRatio() * 0.03;
  18937. this.updateShaderUniforms();
  18938. }
  18939. _super.prototype.render.call(this, useCameraPostProcess);
  18940. };
  18941. CustomProceduralTexture.prototype.updateTextures = function () {
  18942. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  18943. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  18944. }
  18945. };
  18946. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  18947. if (this._config) {
  18948. for (var j = 0; j < this._config.uniforms.length; j++) {
  18949. var uniform = this._config.uniforms[j];
  18950. switch (uniform.type) {
  18951. case "float":
  18952. this.setFloat(uniform.name, uniform.value);
  18953. break;
  18954. case "color3":
  18955. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  18956. break;
  18957. case "color4":
  18958. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  18959. break;
  18960. case "vector2":
  18961. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  18962. break;
  18963. case "vector3":
  18964. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  18965. break;
  18966. }
  18967. }
  18968. }
  18969. this.setFloat("time", this._time);
  18970. };
  18971. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  18972. get: function () {
  18973. return this._animate;
  18974. },
  18975. set: function (value) {
  18976. this._animate = value;
  18977. },
  18978. enumerable: true,
  18979. configurable: true
  18980. });
  18981. return CustomProceduralTexture;
  18982. })(BABYLON.ProceduralTexture);
  18983. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  18984. })(BABYLON || (BABYLON = {}));
  18985. var BABYLON;
  18986. (function (BABYLON) {
  18987. var EffectFallbacks = (function () {
  18988. function EffectFallbacks() {
  18989. this._defines = {};
  18990. this._currentRank = 32;
  18991. this._maxRank = -1;
  18992. }
  18993. EffectFallbacks.prototype.addFallback = function (rank, define) {
  18994. if (!this._defines[rank]) {
  18995. if (rank < this._currentRank) {
  18996. this._currentRank = rank;
  18997. }
  18998. if (rank > this._maxRank) {
  18999. this._maxRank = rank;
  19000. }
  19001. this._defines[rank] = new Array();
  19002. }
  19003. this._defines[rank].push(define);
  19004. };
  19005. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  19006. this._meshRank = rank;
  19007. this._mesh = mesh;
  19008. if (rank > this._maxRank) {
  19009. this._maxRank = rank;
  19010. }
  19011. };
  19012. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  19013. get: function () {
  19014. return this._currentRank <= this._maxRank;
  19015. },
  19016. enumerable: true,
  19017. configurable: true
  19018. });
  19019. EffectFallbacks.prototype.reduce = function (currentDefines) {
  19020. var currentFallbacks = this._defines[this._currentRank];
  19021. for (var index = 0; index < currentFallbacks.length; index++) {
  19022. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  19023. }
  19024. if (this._mesh && this._currentRank === this._meshRank) {
  19025. this._mesh.computeBonesUsingShaders = false;
  19026. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  19027. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  19028. }
  19029. this._currentRank++;
  19030. return currentDefines;
  19031. };
  19032. return EffectFallbacks;
  19033. })();
  19034. BABYLON.EffectFallbacks = EffectFallbacks;
  19035. var Effect = (function () {
  19036. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  19037. var _this = this;
  19038. this._isReady = false;
  19039. this._compilationError = "";
  19040. this._valueCache = [];
  19041. this._engine = engine;
  19042. this.name = baseName;
  19043. this.defines = defines;
  19044. this._uniformsNames = uniformsNames.concat(samplers);
  19045. this._samplers = samplers;
  19046. this._attributesNames = attributesNames;
  19047. this.onError = onError;
  19048. this.onCompiled = onCompiled;
  19049. var vertexSource;
  19050. var fragmentSource;
  19051. if (baseName.vertexElement) {
  19052. vertexSource = document.getElementById(baseName.vertexElement);
  19053. if (!vertexSource) {
  19054. vertexSource = baseName.vertexElement;
  19055. }
  19056. }
  19057. else {
  19058. vertexSource = baseName.vertex || baseName;
  19059. }
  19060. if (baseName.fragmentElement) {
  19061. fragmentSource = document.getElementById(baseName.fragmentElement);
  19062. if (!fragmentSource) {
  19063. fragmentSource = baseName.fragmentElement;
  19064. }
  19065. }
  19066. else {
  19067. fragmentSource = baseName.fragment || baseName;
  19068. }
  19069. this._loadVertexShader(vertexSource, function (vertexCode) {
  19070. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  19071. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  19072. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  19073. _this._prepareEffect(vertexCodeWithIncludes, fragmentCodeWithIncludes, attributesNames, defines, fallbacks);
  19074. });
  19075. });
  19076. });
  19077. });
  19078. }
  19079. // Properties
  19080. Effect.prototype.isReady = function () {
  19081. return this._isReady;
  19082. };
  19083. Effect.prototype.getProgram = function () {
  19084. return this._program;
  19085. };
  19086. Effect.prototype.getAttributesNames = function () {
  19087. return this._attributesNames;
  19088. };
  19089. Effect.prototype.getAttributeLocation = function (index) {
  19090. return this._attributes[index];
  19091. };
  19092. Effect.prototype.getAttributeLocationByName = function (name) {
  19093. var index = this._attributesNames.indexOf(name);
  19094. return this._attributes[index];
  19095. };
  19096. Effect.prototype.getAttributesCount = function () {
  19097. return this._attributes.length;
  19098. };
  19099. Effect.prototype.getUniformIndex = function (uniformName) {
  19100. return this._uniformsNames.indexOf(uniformName);
  19101. };
  19102. Effect.prototype.getUniform = function (uniformName) {
  19103. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  19104. };
  19105. Effect.prototype.getSamplers = function () {
  19106. return this._samplers;
  19107. };
  19108. Effect.prototype.getCompilationError = function () {
  19109. return this._compilationError;
  19110. };
  19111. // Methods
  19112. Effect.prototype._loadVertexShader = function (vertex, callback) {
  19113. // DOM element ?
  19114. if (vertex instanceof HTMLElement) {
  19115. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  19116. callback(vertexCode);
  19117. return;
  19118. }
  19119. // Is in local store ?
  19120. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  19121. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  19122. return;
  19123. }
  19124. var vertexShaderUrl;
  19125. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  19126. vertexShaderUrl = vertex;
  19127. }
  19128. else {
  19129. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  19130. }
  19131. // Vertex shader
  19132. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  19133. };
  19134. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  19135. // DOM element ?
  19136. if (fragment instanceof HTMLElement) {
  19137. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  19138. callback(fragmentCode);
  19139. return;
  19140. }
  19141. // Is in local store ?
  19142. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  19143. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  19144. return;
  19145. }
  19146. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  19147. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  19148. return;
  19149. }
  19150. var fragmentShaderUrl;
  19151. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  19152. fragmentShaderUrl = fragment;
  19153. }
  19154. else {
  19155. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  19156. }
  19157. // Fragment shader
  19158. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  19159. };
  19160. Effect.prototype._dumpShadersName = function () {
  19161. if (this.name.vertexElement) {
  19162. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  19163. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  19164. }
  19165. else if (this.name.vertex) {
  19166. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  19167. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  19168. }
  19169. else {
  19170. BABYLON.Tools.Error("Vertex shader:" + this.name);
  19171. BABYLON.Tools.Error("Fragment shader:" + this.name);
  19172. }
  19173. };
  19174. Effect.prototype._processIncludes = function (sourceCode, callback) {
  19175. var _this = this;
  19176. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  19177. var match = regex.exec(sourceCode);
  19178. var returnValue = new String(sourceCode);
  19179. while (match != null) {
  19180. var includeFile = match[1];
  19181. if (Effect.IncludesShadersStore[includeFile]) {
  19182. // Substitution
  19183. var includeContent = Effect.IncludesShadersStore[includeFile];
  19184. if (match[2]) {
  19185. var splits = match[3].split(",");
  19186. for (var index = 0; index < splits.length; index += 2) {
  19187. var source = new RegExp(splits[index], "g");
  19188. var dest = splits[index + 1];
  19189. includeContent = includeContent.replace(source, dest);
  19190. }
  19191. }
  19192. if (match[4]) {
  19193. includeContent = includeContent.replace(/\{X\}/g, match[5]);
  19194. }
  19195. // Replace
  19196. returnValue = returnValue.replace(match[0], includeContent);
  19197. }
  19198. else {
  19199. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  19200. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  19201. Effect.IncludesShadersStore[includeFile] = fileContent;
  19202. _this._processIncludes(returnValue, callback);
  19203. });
  19204. return;
  19205. }
  19206. match = regex.exec(sourceCode);
  19207. }
  19208. callback(returnValue);
  19209. };
  19210. Effect.prototype._processPrecision = function (source) {
  19211. if (source.indexOf("precision highp float") === -1) {
  19212. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  19213. source = "precision mediump float;\n" + source;
  19214. }
  19215. else {
  19216. source = "precision highp float;\n" + source;
  19217. }
  19218. }
  19219. else {
  19220. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  19221. source = source.replace("precision highp float", "precision mediump float");
  19222. }
  19223. }
  19224. return source;
  19225. };
  19226. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  19227. try {
  19228. var engine = this._engine;
  19229. // Precision
  19230. vertexSourceCode = this._processPrecision(vertexSourceCode);
  19231. fragmentSourceCode = this._processPrecision(fragmentSourceCode);
  19232. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  19233. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  19234. this._attributes = engine.getAttributes(this._program, attributesNames);
  19235. for (var index = 0; index < this._samplers.length; index++) {
  19236. var sampler = this.getUniform(this._samplers[index]);
  19237. if (sampler == null) {
  19238. this._samplers.splice(index, 1);
  19239. index--;
  19240. }
  19241. }
  19242. engine.bindSamplers(this);
  19243. this._isReady = true;
  19244. if (this.onCompiled) {
  19245. this.onCompiled(this);
  19246. }
  19247. }
  19248. catch (e) {
  19249. // Is it a problem with precision?
  19250. if (e.message.indexOf("highp") !== -1) {
  19251. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  19252. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  19253. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  19254. return;
  19255. }
  19256. // Let's go through fallbacks then
  19257. if (fallbacks && fallbacks.isMoreFallbacks) {
  19258. BABYLON.Tools.Error("Unable to compile effect with current defines. Trying next fallback.");
  19259. this._dumpShadersName();
  19260. defines = fallbacks.reduce(defines);
  19261. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  19262. }
  19263. else {
  19264. BABYLON.Tools.Error("Unable to compile effect: ");
  19265. this._dumpShadersName();
  19266. BABYLON.Tools.Error("Defines: " + defines);
  19267. BABYLON.Tools.Error("Error: " + e.message);
  19268. this._compilationError = e.message;
  19269. if (this.onError) {
  19270. this.onError(this, this._compilationError);
  19271. }
  19272. }
  19273. }
  19274. };
  19275. Object.defineProperty(Effect.prototype, "isSupported", {
  19276. get: function () {
  19277. return this._compilationError === "";
  19278. },
  19279. enumerable: true,
  19280. configurable: true
  19281. });
  19282. Effect.prototype._bindTexture = function (channel, texture) {
  19283. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  19284. };
  19285. Effect.prototype.setTexture = function (channel, texture) {
  19286. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  19287. };
  19288. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  19289. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  19290. };
  19291. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  19292. if (!this._valueCache[uniformName]) {
  19293. this._valueCache[uniformName] = new BABYLON.Matrix();
  19294. }
  19295. for (var index = 0; index < 16; index++) {
  19296. this._valueCache[uniformName].m[index] = matrix.m[index];
  19297. }
  19298. };
  19299. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  19300. if (!this._valueCache[uniformName]) {
  19301. this._valueCache[uniformName] = [x, y];
  19302. return;
  19303. }
  19304. this._valueCache[uniformName][0] = x;
  19305. this._valueCache[uniformName][1] = y;
  19306. };
  19307. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  19308. if (!this._valueCache[uniformName]) {
  19309. this._valueCache[uniformName] = [x, y, z];
  19310. return;
  19311. }
  19312. this._valueCache[uniformName][0] = x;
  19313. this._valueCache[uniformName][1] = y;
  19314. this._valueCache[uniformName][2] = z;
  19315. };
  19316. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  19317. if (!this._valueCache[uniformName]) {
  19318. this._valueCache[uniformName] = [x, y, z, w];
  19319. return;
  19320. }
  19321. this._valueCache[uniformName][0] = x;
  19322. this._valueCache[uniformName][1] = y;
  19323. this._valueCache[uniformName][2] = z;
  19324. this._valueCache[uniformName][3] = w;
  19325. };
  19326. Effect.prototype.setArray = function (uniformName, array) {
  19327. this._engine.setArray(this.getUniform(uniformName), array);
  19328. return this;
  19329. };
  19330. Effect.prototype.setArray2 = function (uniformName, array) {
  19331. this._engine.setArray2(this.getUniform(uniformName), array);
  19332. return this;
  19333. };
  19334. Effect.prototype.setArray3 = function (uniformName, array) {
  19335. this._engine.setArray3(this.getUniform(uniformName), array);
  19336. return this;
  19337. };
  19338. Effect.prototype.setArray4 = function (uniformName, array) {
  19339. this._engine.setArray4(this.getUniform(uniformName), array);
  19340. return this;
  19341. };
  19342. Effect.prototype.setMatrices = function (uniformName, matrices) {
  19343. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  19344. return this;
  19345. };
  19346. Effect.prototype.setMatrix = function (uniformName, matrix) {
  19347. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  19348. // return this;
  19349. // this._cacheMatrix(uniformName, matrix);
  19350. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  19351. return this;
  19352. };
  19353. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  19354. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  19355. return this;
  19356. };
  19357. Effect.prototype.setMatrix2x2 = function (uniformname, matrix) {
  19358. this._engine.setMatrix2x2(this.getUniform(uniformname), matrix);
  19359. return this;
  19360. };
  19361. Effect.prototype.setFloat = function (uniformName, value) {
  19362. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  19363. return this;
  19364. this._valueCache[uniformName] = value;
  19365. this._engine.setFloat(this.getUniform(uniformName), value);
  19366. return this;
  19367. };
  19368. Effect.prototype.setBool = function (uniformName, bool) {
  19369. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  19370. return this;
  19371. this._valueCache[uniformName] = bool;
  19372. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  19373. return this;
  19374. };
  19375. Effect.prototype.setVector2 = function (uniformName, vector2) {
  19376. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  19377. return this;
  19378. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  19379. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  19380. return this;
  19381. };
  19382. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  19383. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  19384. return this;
  19385. this._cacheFloat2(uniformName, x, y);
  19386. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  19387. return this;
  19388. };
  19389. Effect.prototype.setVector3 = function (uniformName, vector3) {
  19390. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  19391. return this;
  19392. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  19393. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  19394. return this;
  19395. };
  19396. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  19397. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  19398. return this;
  19399. this._cacheFloat3(uniformName, x, y, z);
  19400. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  19401. return this;
  19402. };
  19403. Effect.prototype.setVector4 = function (uniformName, vector4) {
  19404. 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)
  19405. return this;
  19406. this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w);
  19407. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  19408. return this;
  19409. };
  19410. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  19411. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  19412. return this;
  19413. this._cacheFloat4(uniformName, x, y, z, w);
  19414. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  19415. return this;
  19416. };
  19417. Effect.prototype.setColor3 = function (uniformName, color3) {
  19418. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  19419. return this;
  19420. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  19421. this._engine.setColor3(this.getUniform(uniformName), color3);
  19422. return this;
  19423. };
  19424. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  19425. 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)
  19426. return this;
  19427. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  19428. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  19429. return this;
  19430. };
  19431. // Statics
  19432. Effect.ShadersStore = {};
  19433. Effect.IncludesShadersStore = {};
  19434. return Effect;
  19435. })();
  19436. BABYLON.Effect = Effect;
  19437. })(BABYLON || (BABYLON = {}));
  19438. var BABYLON;
  19439. (function (BABYLON) {
  19440. var maxSimultaneousLights = 4;
  19441. var MaterialHelper = (function () {
  19442. function MaterialHelper() {
  19443. }
  19444. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines) {
  19445. var lightIndex = 0;
  19446. var needNormals = false;
  19447. for (var index = 0; index < scene.lights.length; index++) {
  19448. var light = scene.lights[index];
  19449. if (!light.isEnabled()) {
  19450. continue;
  19451. }
  19452. // Excluded check
  19453. if (light._excludedMeshesIds.length > 0) {
  19454. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  19455. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  19456. if (excludedMesh) {
  19457. light.excludedMeshes.push(excludedMesh);
  19458. }
  19459. }
  19460. light._excludedMeshesIds = [];
  19461. }
  19462. // Included check
  19463. if (light._includedOnlyMeshesIds.length > 0) {
  19464. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  19465. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  19466. if (includedOnlyMesh) {
  19467. light.includedOnlyMeshes.push(includedOnlyMesh);
  19468. }
  19469. }
  19470. light._includedOnlyMeshesIds = [];
  19471. }
  19472. if (!light.canAffectMesh(mesh)) {
  19473. continue;
  19474. }
  19475. needNormals = true;
  19476. defines["LIGHT" + lightIndex] = true;
  19477. var type;
  19478. if (light instanceof BABYLON.SpotLight) {
  19479. type = "SPOTLIGHT" + lightIndex;
  19480. }
  19481. else if (light instanceof BABYLON.HemisphericLight) {
  19482. type = "HEMILIGHT" + lightIndex;
  19483. }
  19484. else if (light instanceof BABYLON.PointLight) {
  19485. type = "POINTLIGHT" + lightIndex;
  19486. }
  19487. else {
  19488. type = "DIRLIGHT" + lightIndex;
  19489. }
  19490. defines[type] = true;
  19491. // Specular
  19492. if (!light.specular.equalsFloats(0, 0, 0) && defines["SPECULARTERM"] !== undefined) {
  19493. defines["SPECULARTERM"] = true;
  19494. }
  19495. // Shadows
  19496. if (scene.shadowsEnabled) {
  19497. var shadowGenerator = light.getShadowGenerator();
  19498. if (mesh && mesh.receiveShadows && shadowGenerator) {
  19499. defines["SHADOW" + lightIndex] = true;
  19500. defines["SHADOWS"] = true;
  19501. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  19502. defines["SHADOWVSM" + lightIndex] = true;
  19503. }
  19504. if (shadowGenerator.usePoissonSampling) {
  19505. defines["SHADOWPCF" + lightIndex] = true;
  19506. }
  19507. }
  19508. }
  19509. lightIndex++;
  19510. if (lightIndex === maxSimultaneousLights)
  19511. break;
  19512. }
  19513. return needNormals;
  19514. };
  19515. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks) {
  19516. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  19517. if (!defines["LIGHT" + lightIndex]) {
  19518. continue;
  19519. }
  19520. if (lightIndex > 0) {
  19521. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  19522. }
  19523. if (defines["SHADOW" + lightIndex]) {
  19524. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  19525. }
  19526. if (defines["SHADOWPCF" + lightIndex]) {
  19527. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  19528. }
  19529. if (defines["SHADOWVSM" + lightIndex]) {
  19530. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  19531. }
  19532. }
  19533. };
  19534. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  19535. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  19536. fallbacks.addCPUSkinningFallback(0, mesh);
  19537. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19538. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19539. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  19540. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  19541. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  19542. }
  19543. }
  19544. };
  19545. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  19546. if (defines["INSTANCES"]) {
  19547. attribs.push("world0");
  19548. attribs.push("world1");
  19549. attribs.push("world2");
  19550. attribs.push("world3");
  19551. }
  19552. };
  19553. // Bindings
  19554. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  19555. var shadowGenerator = light.getShadowGenerator();
  19556. if (mesh.receiveShadows && shadowGenerator) {
  19557. if (!light.needCube()) {
  19558. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  19559. }
  19560. else {
  19561. if (!depthValuesAlreadySet) {
  19562. depthValuesAlreadySet = true;
  19563. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  19564. }
  19565. }
  19566. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  19567. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  19568. }
  19569. return depthValuesAlreadySet;
  19570. };
  19571. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  19572. if (light instanceof BABYLON.PointLight) {
  19573. // Point Light
  19574. light.transferToEffect(effect, "vLightData" + lightIndex);
  19575. }
  19576. else if (light instanceof BABYLON.DirectionalLight) {
  19577. // Directional Light
  19578. light.transferToEffect(effect, "vLightData" + lightIndex);
  19579. }
  19580. else if (light instanceof BABYLON.SpotLight) {
  19581. // Spot Light
  19582. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  19583. }
  19584. else if (light instanceof BABYLON.HemisphericLight) {
  19585. // Hemispheric Light
  19586. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  19587. }
  19588. };
  19589. MaterialHelper.BindLights = function (scene, mesh, effect, defines) {
  19590. var lightIndex = 0;
  19591. var depthValuesAlreadySet = false;
  19592. for (var index = 0; index < scene.lights.length; index++) {
  19593. var light = scene.lights[index];
  19594. if (!light.isEnabled()) {
  19595. continue;
  19596. }
  19597. if (!light.canAffectMesh(mesh)) {
  19598. continue;
  19599. }
  19600. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  19601. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  19602. effect.setColor4("vLightDiffuse" + lightIndex, BABYLON.Tmp.Color3[0], light.range);
  19603. if (defines["SPECULARTERM"]) {
  19604. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  19605. effect.setColor3("vLightSpecular" + lightIndex, BABYLON.Tmp.Color3[1]);
  19606. }
  19607. // Shadows
  19608. if (scene.shadowsEnabled) {
  19609. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  19610. }
  19611. lightIndex++;
  19612. if (lightIndex === maxSimultaneousLights)
  19613. break;
  19614. }
  19615. };
  19616. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  19617. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  19618. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  19619. effect.setColor3("vFogColor", scene.fogColor);
  19620. }
  19621. };
  19622. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  19623. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  19624. effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  19625. }
  19626. };
  19627. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  19628. if (defines["LOGARITHMICDEPTH"]) {
  19629. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  19630. }
  19631. };
  19632. MaterialHelper.BindClipPlane = function (effect, scene) {
  19633. if (scene.clipPlane) {
  19634. var clipPlane = scene.clipPlane;
  19635. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  19636. }
  19637. };
  19638. return MaterialHelper;
  19639. })();
  19640. BABYLON.MaterialHelper = MaterialHelper;
  19641. })(BABYLON || (BABYLON = {}));
  19642. var BABYLON;
  19643. (function (BABYLON) {
  19644. var FresnelParameters = (function () {
  19645. function FresnelParameters() {
  19646. this.isEnabled = true;
  19647. this.leftColor = BABYLON.Color3.White();
  19648. this.rightColor = BABYLON.Color3.Black();
  19649. this.bias = 0;
  19650. this.power = 1;
  19651. }
  19652. FresnelParameters.prototype.clone = function () {
  19653. var newFresnelParameters = new FresnelParameters();
  19654. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  19655. return new FresnelParameters;
  19656. };
  19657. FresnelParameters.prototype.serialize = function () {
  19658. var serializationObject = {};
  19659. serializationObject.isEnabled = this.isEnabled;
  19660. serializationObject.leftColor = this.leftColor;
  19661. serializationObject.rightColor = this.rightColor;
  19662. serializationObject.bias = this.bias;
  19663. serializationObject.power = this.power;
  19664. return serializationObject;
  19665. };
  19666. FresnelParameters.Parse = function (parsedFresnelParameters) {
  19667. var fresnelParameters = new FresnelParameters();
  19668. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  19669. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  19670. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  19671. fresnelParameters.bias = parsedFresnelParameters.bias;
  19672. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  19673. return fresnelParameters;
  19674. };
  19675. return FresnelParameters;
  19676. })();
  19677. BABYLON.FresnelParameters = FresnelParameters;
  19678. })(BABYLON || (BABYLON = {}));
  19679. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  19680. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  19681. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  19682. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  19683. return c > 3 && r && Object.defineProperty(target, key, r), r;
  19684. };
  19685. var BABYLON;
  19686. (function (BABYLON) {
  19687. var MaterialDefines = (function () {
  19688. function MaterialDefines() {
  19689. }
  19690. MaterialDefines.prototype.isEqual = function (other) {
  19691. for (var index = 0; index < this._keys.length; index++) {
  19692. var prop = this._keys[index];
  19693. if (this[prop] !== other[prop]) {
  19694. return false;
  19695. }
  19696. }
  19697. return true;
  19698. };
  19699. MaterialDefines.prototype.cloneTo = function (other) {
  19700. for (var index = 0; index < this._keys.length; index++) {
  19701. var prop = this._keys[index];
  19702. other[prop] = this[prop];
  19703. }
  19704. };
  19705. MaterialDefines.prototype.reset = function () {
  19706. for (var index = 0; index < this._keys.length; index++) {
  19707. var prop = this._keys[index];
  19708. if (typeof (this[prop]) === "number") {
  19709. this[prop] = 0;
  19710. }
  19711. else {
  19712. this[prop] = false;
  19713. }
  19714. }
  19715. };
  19716. MaterialDefines.prototype.toString = function () {
  19717. var result = "";
  19718. for (var index = 0; index < this._keys.length; index++) {
  19719. var prop = this._keys[index];
  19720. if (typeof (this[prop]) === "number") {
  19721. result += "#define " + prop + " " + this[prop] + "\n";
  19722. }
  19723. else if (this[prop]) {
  19724. result += "#define " + prop + "\n";
  19725. }
  19726. }
  19727. return result;
  19728. };
  19729. return MaterialDefines;
  19730. })();
  19731. BABYLON.MaterialDefines = MaterialDefines;
  19732. var Material = (function () {
  19733. function Material(name, scene, doNotAdd) {
  19734. this.name = name;
  19735. this.checkReadyOnEveryCall = false;
  19736. this.checkReadyOnlyOnce = false;
  19737. this.state = "";
  19738. this.alpha = 1.0;
  19739. this.backFaceCulling = true;
  19740. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  19741. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  19742. this.disableDepthWrite = false;
  19743. this.fogEnabled = true;
  19744. this.pointSize = 1.0;
  19745. this.zOffset = 0;
  19746. this._wasPreviouslyReady = false;
  19747. this._fillMode = Material.TriangleFillMode;
  19748. this.id = name;
  19749. this._scene = scene;
  19750. if (!doNotAdd) {
  19751. scene.materials.push(this);
  19752. }
  19753. }
  19754. Object.defineProperty(Material, "TriangleFillMode", {
  19755. get: function () {
  19756. return Material._TriangleFillMode;
  19757. },
  19758. enumerable: true,
  19759. configurable: true
  19760. });
  19761. Object.defineProperty(Material, "WireFrameFillMode", {
  19762. get: function () {
  19763. return Material._WireFrameFillMode;
  19764. },
  19765. enumerable: true,
  19766. configurable: true
  19767. });
  19768. Object.defineProperty(Material, "PointFillMode", {
  19769. get: function () {
  19770. return Material._PointFillMode;
  19771. },
  19772. enumerable: true,
  19773. configurable: true
  19774. });
  19775. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  19776. get: function () {
  19777. return Material._ClockWiseSideOrientation;
  19778. },
  19779. enumerable: true,
  19780. configurable: true
  19781. });
  19782. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  19783. get: function () {
  19784. return Material._CounterClockWiseSideOrientation;
  19785. },
  19786. enumerable: true,
  19787. configurable: true
  19788. });
  19789. Object.defineProperty(Material.prototype, "wireframe", {
  19790. get: function () {
  19791. return this._fillMode === Material.WireFrameFillMode;
  19792. },
  19793. set: function (value) {
  19794. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  19795. },
  19796. enumerable: true,
  19797. configurable: true
  19798. });
  19799. Object.defineProperty(Material.prototype, "pointsCloud", {
  19800. get: function () {
  19801. return this._fillMode === Material.PointFillMode;
  19802. },
  19803. set: function (value) {
  19804. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  19805. },
  19806. enumerable: true,
  19807. configurable: true
  19808. });
  19809. Object.defineProperty(Material.prototype, "fillMode", {
  19810. get: function () {
  19811. return this._fillMode;
  19812. },
  19813. set: function (value) {
  19814. this._fillMode = value;
  19815. },
  19816. enumerable: true,
  19817. configurable: true
  19818. });
  19819. Object.defineProperty(Material.prototype, "isFrozen", {
  19820. get: function () {
  19821. return this.checkReadyOnlyOnce;
  19822. },
  19823. enumerable: true,
  19824. configurable: true
  19825. });
  19826. Material.prototype.freeze = function () {
  19827. this.checkReadyOnlyOnce = true;
  19828. };
  19829. Material.prototype.unfreeze = function () {
  19830. this.checkReadyOnlyOnce = false;
  19831. };
  19832. Material.prototype.isReady = function (mesh, useInstances) {
  19833. return true;
  19834. };
  19835. Material.prototype.getEffect = function () {
  19836. return this._effect;
  19837. };
  19838. Material.prototype.getScene = function () {
  19839. return this._scene;
  19840. };
  19841. Material.prototype.needAlphaBlending = function () {
  19842. return (this.alpha < 1.0);
  19843. };
  19844. Material.prototype.needAlphaTesting = function () {
  19845. return false;
  19846. };
  19847. Material.prototype.getAlphaTestTexture = function () {
  19848. return null;
  19849. };
  19850. Material.prototype.trackCreation = function (onCompiled, onError) {
  19851. };
  19852. Material.prototype.markDirty = function () {
  19853. this._wasPreviouslyReady = false;
  19854. };
  19855. Material.prototype._preBind = function () {
  19856. var engine = this._scene.getEngine();
  19857. engine.enableEffect(this._effect);
  19858. engine.setState(this.backFaceCulling, this.zOffset, false, this.sideOrientation === Material.ClockWiseSideOrientation);
  19859. };
  19860. Material.prototype.bind = function (world, mesh) {
  19861. this._scene._cachedMaterial = this;
  19862. if (this.onBind) {
  19863. this.onBind(this, mesh);
  19864. }
  19865. if (this.disableDepthWrite) {
  19866. var engine = this._scene.getEngine();
  19867. this._cachedDepthWriteState = engine.getDepthWrite();
  19868. engine.setDepthWrite(false);
  19869. }
  19870. };
  19871. Material.prototype.bindOnlyWorldMatrix = function (world) {
  19872. };
  19873. Material.prototype.unbind = function () {
  19874. if (this.disableDepthWrite) {
  19875. var engine = this._scene.getEngine();
  19876. engine.setDepthWrite(this._cachedDepthWriteState);
  19877. }
  19878. };
  19879. Material.prototype.clone = function (name) {
  19880. return null;
  19881. };
  19882. Material.prototype.getBindedMeshes = function () {
  19883. var result = new Array();
  19884. for (var index = 0; index < this._scene.meshes.length; index++) {
  19885. var mesh = this._scene.meshes[index];
  19886. if (mesh.material === this) {
  19887. result.push(mesh);
  19888. }
  19889. }
  19890. return result;
  19891. };
  19892. Material.prototype.dispose = function (forceDisposeEffect) {
  19893. // Animations
  19894. this.getScene().stopAnimation(this);
  19895. // Remove from scene
  19896. var index = this._scene.materials.indexOf(this);
  19897. if (index >= 0) {
  19898. this._scene.materials.splice(index, 1);
  19899. }
  19900. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  19901. if (forceDisposeEffect && this._effect) {
  19902. this._scene.getEngine()._releaseEffect(this._effect);
  19903. this._effect = null;
  19904. }
  19905. // Remove from meshes
  19906. for (index = 0; index < this._scene.meshes.length; index++) {
  19907. var mesh = this._scene.meshes[index];
  19908. if (mesh.material === this) {
  19909. mesh.material = null;
  19910. }
  19911. }
  19912. // Callback
  19913. if (this.onDispose) {
  19914. this.onDispose();
  19915. }
  19916. };
  19917. Material.prototype.serialize = function () {
  19918. return BABYLON.SerializationHelper.Serialize(this);
  19919. };
  19920. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  19921. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  19922. multiMaterial.id = parsedMultiMaterial.id;
  19923. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  19924. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  19925. var subMatId = parsedMultiMaterial.materials[matIndex];
  19926. if (subMatId) {
  19927. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  19928. }
  19929. else {
  19930. multiMaterial.subMaterials.push(null);
  19931. }
  19932. }
  19933. return multiMaterial;
  19934. };
  19935. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  19936. if (!parsedMaterial.customType) {
  19937. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  19938. }
  19939. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  19940. return materialType.Parse(parsedMaterial, scene, rootUrl);
  19941. ;
  19942. };
  19943. Material._TriangleFillMode = 0;
  19944. Material._WireFrameFillMode = 1;
  19945. Material._PointFillMode = 2;
  19946. Material._ClockWiseSideOrientation = 0;
  19947. Material._CounterClockWiseSideOrientation = 1;
  19948. __decorate([
  19949. BABYLON.serialize()
  19950. ], Material.prototype, "id", void 0);
  19951. __decorate([
  19952. BABYLON.serialize()
  19953. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  19954. __decorate([
  19955. BABYLON.serialize()
  19956. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  19957. __decorate([
  19958. BABYLON.serialize()
  19959. ], Material.prototype, "state", void 0);
  19960. __decorate([
  19961. BABYLON.serialize()
  19962. ], Material.prototype, "alpha", void 0);
  19963. __decorate([
  19964. BABYLON.serialize()
  19965. ], Material.prototype, "backFaceCulling", void 0);
  19966. __decorate([
  19967. BABYLON.serialize()
  19968. ], Material.prototype, "sideOrientation", void 0);
  19969. __decorate([
  19970. BABYLON.serialize()
  19971. ], Material.prototype, "alphaMode", void 0);
  19972. __decorate([
  19973. BABYLON.serialize()
  19974. ], Material.prototype, "disableDepthWrite", void 0);
  19975. __decorate([
  19976. BABYLON.serialize()
  19977. ], Material.prototype, "fogEnabled", void 0);
  19978. __decorate([
  19979. BABYLON.serialize()
  19980. ], Material.prototype, "pointSize", void 0);
  19981. __decorate([
  19982. BABYLON.serialize()
  19983. ], Material.prototype, "zOffset", void 0);
  19984. __decorate([
  19985. BABYLON.serialize()
  19986. ], Material.prototype, "wireframe", null);
  19987. __decorate([
  19988. BABYLON.serialize()
  19989. ], Material.prototype, "pointsCloud", null);
  19990. __decorate([
  19991. BABYLON.serialize()
  19992. ], Material.prototype, "fillMode", null);
  19993. return Material;
  19994. })();
  19995. BABYLON.Material = Material;
  19996. })(BABYLON || (BABYLON = {}));
  19997. var BABYLON;
  19998. (function (BABYLON) {
  19999. var StandardMaterialDefines = (function (_super) {
  20000. __extends(StandardMaterialDefines, _super);
  20001. function StandardMaterialDefines() {
  20002. _super.call(this);
  20003. this.DIFFUSE = false;
  20004. this.AMBIENT = false;
  20005. this.OPACITY = false;
  20006. this.OPACITYRGB = false;
  20007. this.REFLECTION = false;
  20008. this.EMISSIVE = false;
  20009. this.SPECULAR = false;
  20010. this.BUMP = false;
  20011. this.PARALLAX = false;
  20012. this.PARALLAXOCCLUSION = false;
  20013. this.SPECULAROVERALPHA = false;
  20014. this.CLIPPLANE = false;
  20015. this.ALPHATEST = false;
  20016. this.ALPHAFROMDIFFUSE = false;
  20017. this.POINTSIZE = false;
  20018. this.FOG = false;
  20019. this.LIGHT0 = false;
  20020. this.LIGHT1 = false;
  20021. this.LIGHT2 = false;
  20022. this.LIGHT3 = false;
  20023. this.SPOTLIGHT0 = false;
  20024. this.SPOTLIGHT1 = false;
  20025. this.SPOTLIGHT2 = false;
  20026. this.SPOTLIGHT3 = false;
  20027. this.HEMILIGHT0 = false;
  20028. this.HEMILIGHT1 = false;
  20029. this.HEMILIGHT2 = false;
  20030. this.HEMILIGHT3 = false;
  20031. this.POINTLIGHT0 = false;
  20032. this.POINTLIGHT1 = false;
  20033. this.POINTLIGHT2 = false;
  20034. this.POINTLIGHT3 = false;
  20035. this.DIRLIGHT0 = false;
  20036. this.DIRLIGHT1 = false;
  20037. this.DIRLIGHT2 = false;
  20038. this.DIRLIGHT3 = false;
  20039. this.SPECULARTERM = false;
  20040. this.SHADOW0 = false;
  20041. this.SHADOW1 = false;
  20042. this.SHADOW2 = false;
  20043. this.SHADOW3 = false;
  20044. this.SHADOWS = false;
  20045. this.SHADOWVSM0 = false;
  20046. this.SHADOWVSM1 = false;
  20047. this.SHADOWVSM2 = false;
  20048. this.SHADOWVSM3 = false;
  20049. this.SHADOWPCF0 = false;
  20050. this.SHADOWPCF1 = false;
  20051. this.SHADOWPCF2 = false;
  20052. this.SHADOWPCF3 = false;
  20053. this.DIFFUSEFRESNEL = false;
  20054. this.OPACITYFRESNEL = false;
  20055. this.REFLECTIONFRESNEL = false;
  20056. this.REFRACTIONFRESNEL = false;
  20057. this.EMISSIVEFRESNEL = false;
  20058. this.FRESNEL = false;
  20059. this.NORMAL = false;
  20060. this.UV1 = false;
  20061. this.UV2 = false;
  20062. this.VERTEXCOLOR = false;
  20063. this.VERTEXALPHA = false;
  20064. this.NUM_BONE_INFLUENCERS = 0;
  20065. this.BonesPerMesh = 0;
  20066. this.INSTANCES = false;
  20067. this.GLOSSINESS = false;
  20068. this.ROUGHNESS = false;
  20069. this.EMISSIVEASILLUMINATION = false;
  20070. this.LINKEMISSIVEWITHDIFFUSE = false;
  20071. this.REFLECTIONFRESNELFROMSPECULAR = false;
  20072. this.LIGHTMAP = false;
  20073. this.USELIGHTMAPASSHADOWMAP = false;
  20074. this.REFLECTIONMAP_3D = false;
  20075. this.REFLECTIONMAP_SPHERICAL = false;
  20076. this.REFLECTIONMAP_PLANAR = false;
  20077. this.REFLECTIONMAP_CUBIC = false;
  20078. this.REFLECTIONMAP_PROJECTION = false;
  20079. this.REFLECTIONMAP_SKYBOX = false;
  20080. this.REFLECTIONMAP_EXPLICIT = false;
  20081. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  20082. this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  20083. this.INVERTCUBICMAP = false;
  20084. this.LOGARITHMICDEPTH = false;
  20085. this.REFRACTION = false;
  20086. this.REFRACTIONMAP_3D = false;
  20087. this.REFLECTIONOVERALPHA = false;
  20088. this._keys = Object.keys(this);
  20089. }
  20090. return StandardMaterialDefines;
  20091. })(BABYLON.MaterialDefines);
  20092. var StandardMaterial = (function (_super) {
  20093. __extends(StandardMaterial, _super);
  20094. function StandardMaterial(name, scene) {
  20095. var _this = this;
  20096. _super.call(this, name, scene);
  20097. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  20098. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  20099. this.specularColor = new BABYLON.Color3(1, 1, 1);
  20100. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  20101. this.specularPower = 64;
  20102. this.useAlphaFromDiffuseTexture = false;
  20103. this.useEmissiveAsIllumination = false;
  20104. this.linkEmissiveWithDiffuse = false;
  20105. this.useReflectionFresnelFromSpecular = false;
  20106. this.useSpecularOverAlpha = false;
  20107. this.useReflectionOverAlpha = false;
  20108. this.disableLighting = false;
  20109. this.useParallax = false;
  20110. this.useParallaxOcclusion = false;
  20111. this.parallaxScaleBias = 0.05;
  20112. this.roughness = 0;
  20113. this.indexOfRefraction = 0.98;
  20114. this.invertRefractionY = true;
  20115. this.useLightmapAsShadowmap = false;
  20116. this.useGlossinessFromSpecularMapAlpha = false;
  20117. this._renderTargets = new BABYLON.SmartArray(16);
  20118. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  20119. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  20120. this._defines = new StandardMaterialDefines();
  20121. this._cachedDefines = new StandardMaterialDefines();
  20122. this._cachedDefines.BonesPerMesh = -1;
  20123. this.getRenderTargetTextures = function () {
  20124. _this._renderTargets.reset();
  20125. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  20126. _this._renderTargets.push(_this.reflectionTexture);
  20127. }
  20128. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  20129. _this._renderTargets.push(_this.refractionTexture);
  20130. }
  20131. return _this._renderTargets;
  20132. };
  20133. }
  20134. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  20135. get: function () {
  20136. return this._useLogarithmicDepth;
  20137. },
  20138. set: function (value) {
  20139. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  20140. },
  20141. enumerable: true,
  20142. configurable: true
  20143. });
  20144. StandardMaterial.prototype.needAlphaBlending = function () {
  20145. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  20146. };
  20147. StandardMaterial.prototype.needAlphaTesting = function () {
  20148. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  20149. };
  20150. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  20151. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  20152. };
  20153. StandardMaterial.prototype.getAlphaTestTexture = function () {
  20154. return this.diffuseTexture;
  20155. };
  20156. // Methods
  20157. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  20158. if (!mesh) {
  20159. return true;
  20160. }
  20161. if (this._defines.INSTANCES !== useInstances) {
  20162. return false;
  20163. }
  20164. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  20165. return true;
  20166. }
  20167. return false;
  20168. };
  20169. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  20170. if (this.isFrozen) {
  20171. if (this._wasPreviouslyReady) {
  20172. return true;
  20173. }
  20174. }
  20175. var scene = this.getScene();
  20176. if (!this.checkReadyOnEveryCall) {
  20177. if (this._renderId === scene.getRenderId()) {
  20178. if (this._checkCache(scene, mesh, useInstances)) {
  20179. return true;
  20180. }
  20181. }
  20182. }
  20183. var engine = scene.getEngine();
  20184. var needNormals = false;
  20185. var needUVs = false;
  20186. this._defines.reset();
  20187. // Textures
  20188. if (scene.texturesEnabled) {
  20189. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  20190. if (!this.diffuseTexture.isReady()) {
  20191. return false;
  20192. }
  20193. else {
  20194. needUVs = true;
  20195. this._defines.DIFFUSE = true;
  20196. }
  20197. }
  20198. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  20199. if (!this.ambientTexture.isReady()) {
  20200. return false;
  20201. }
  20202. else {
  20203. needUVs = true;
  20204. this._defines.AMBIENT = true;
  20205. }
  20206. }
  20207. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  20208. if (!this.opacityTexture.isReady()) {
  20209. return false;
  20210. }
  20211. else {
  20212. needUVs = true;
  20213. this._defines.OPACITY = true;
  20214. if (this.opacityTexture.getAlphaFromRGB) {
  20215. this._defines.OPACITYRGB = true;
  20216. }
  20217. }
  20218. }
  20219. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  20220. if (!this.reflectionTexture.isReady()) {
  20221. return false;
  20222. }
  20223. else {
  20224. needNormals = true;
  20225. this._defines.REFLECTION = true;
  20226. if (this.roughness > 0) {
  20227. this._defines.ROUGHNESS = true;
  20228. }
  20229. if (this.useReflectionOverAlpha) {
  20230. this._defines.REFLECTIONOVERALPHA = true;
  20231. }
  20232. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  20233. this._defines.INVERTCUBICMAP = true;
  20234. }
  20235. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  20236. switch (this.reflectionTexture.coordinatesMode) {
  20237. case BABYLON.Texture.CUBIC_MODE:
  20238. case BABYLON.Texture.INVCUBIC_MODE:
  20239. this._defines.REFLECTIONMAP_CUBIC = true;
  20240. break;
  20241. case BABYLON.Texture.EXPLICIT_MODE:
  20242. this._defines.REFLECTIONMAP_EXPLICIT = true;
  20243. break;
  20244. case BABYLON.Texture.PLANAR_MODE:
  20245. this._defines.REFLECTIONMAP_PLANAR = true;
  20246. break;
  20247. case BABYLON.Texture.PROJECTION_MODE:
  20248. this._defines.REFLECTIONMAP_PROJECTION = true;
  20249. break;
  20250. case BABYLON.Texture.SKYBOX_MODE:
  20251. this._defines.REFLECTIONMAP_SKYBOX = true;
  20252. break;
  20253. case BABYLON.Texture.SPHERICAL_MODE:
  20254. this._defines.REFLECTIONMAP_SPHERICAL = true;
  20255. break;
  20256. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  20257. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  20258. break;
  20259. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  20260. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  20261. break;
  20262. }
  20263. }
  20264. }
  20265. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  20266. if (!this.emissiveTexture.isReady()) {
  20267. return false;
  20268. }
  20269. else {
  20270. needUVs = true;
  20271. this._defines.EMISSIVE = true;
  20272. }
  20273. }
  20274. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  20275. if (!this.lightmapTexture.isReady()) {
  20276. return false;
  20277. }
  20278. else {
  20279. needUVs = true;
  20280. this._defines.LIGHTMAP = true;
  20281. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  20282. }
  20283. }
  20284. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  20285. if (!this.specularTexture.isReady()) {
  20286. return false;
  20287. }
  20288. else {
  20289. needUVs = true;
  20290. this._defines.SPECULAR = true;
  20291. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  20292. }
  20293. }
  20294. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  20295. if (!this.bumpTexture.isReady()) {
  20296. return false;
  20297. }
  20298. else {
  20299. needUVs = true;
  20300. this._defines.BUMP = true;
  20301. if (this.useParallax) {
  20302. this._defines.PARALLAX = true;
  20303. if (this.useParallaxOcclusion) {
  20304. this._defines.PARALLAXOCCLUSION = true;
  20305. }
  20306. }
  20307. }
  20308. }
  20309. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  20310. if (!this.refractionTexture.isReady()) {
  20311. return false;
  20312. }
  20313. else {
  20314. needUVs = true;
  20315. this._defines.REFRACTION = true;
  20316. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  20317. }
  20318. }
  20319. }
  20320. // Effect
  20321. if (scene.clipPlane) {
  20322. this._defines.CLIPPLANE = true;
  20323. }
  20324. if (engine.getAlphaTesting()) {
  20325. this._defines.ALPHATEST = true;
  20326. }
  20327. if (this._shouldUseAlphaFromDiffuseTexture()) {
  20328. this._defines.ALPHAFROMDIFFUSE = true;
  20329. }
  20330. if (this.useEmissiveAsIllumination) {
  20331. this._defines.EMISSIVEASILLUMINATION = true;
  20332. }
  20333. if (this.linkEmissiveWithDiffuse) {
  20334. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  20335. }
  20336. if (this.useLogarithmicDepth) {
  20337. this._defines.LOGARITHMICDEPTH = true;
  20338. }
  20339. // Point size
  20340. if (this.pointsCloud || scene.forcePointsCloud) {
  20341. this._defines.POINTSIZE = true;
  20342. }
  20343. // Fog
  20344. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  20345. this._defines.FOG = true;
  20346. }
  20347. if (scene.lightsEnabled && !this.disableLighting) {
  20348. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines);
  20349. }
  20350. if (StandardMaterial.FresnelEnabled) {
  20351. // Fresnel
  20352. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  20353. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  20354. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  20355. this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled ||
  20356. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  20357. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  20358. this._defines.DIFFUSEFRESNEL = true;
  20359. }
  20360. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  20361. this._defines.OPACITYFRESNEL = true;
  20362. }
  20363. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  20364. this._defines.REFLECTIONFRESNEL = true;
  20365. if (this.useReflectionFresnelFromSpecular) {
  20366. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  20367. }
  20368. }
  20369. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  20370. this._defines.REFRACTIONFRESNEL = true;
  20371. }
  20372. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  20373. this._defines.EMISSIVEFRESNEL = true;
  20374. }
  20375. needNormals = true;
  20376. this._defines.FRESNEL = true;
  20377. }
  20378. }
  20379. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  20380. this._defines.SPECULAROVERALPHA = true;
  20381. }
  20382. // Attribs
  20383. if (mesh) {
  20384. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20385. this._defines.NORMAL = true;
  20386. }
  20387. if (needUVs) {
  20388. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  20389. this._defines.UV1 = true;
  20390. }
  20391. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  20392. this._defines.UV2 = true;
  20393. }
  20394. }
  20395. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  20396. this._defines.VERTEXCOLOR = true;
  20397. if (mesh.hasVertexAlpha) {
  20398. this._defines.VERTEXALPHA = true;
  20399. }
  20400. }
  20401. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  20402. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  20403. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  20404. }
  20405. // Instances
  20406. if (useInstances) {
  20407. this._defines.INSTANCES = true;
  20408. }
  20409. }
  20410. // Get correct effect
  20411. if (!this._defines.isEqual(this._cachedDefines)) {
  20412. this._defines.cloneTo(this._cachedDefines);
  20413. scene.resetCachedMaterial();
  20414. // Fallbacks
  20415. var fallbacks = new BABYLON.EffectFallbacks();
  20416. if (this._defines.REFLECTION) {
  20417. fallbacks.addFallback(0, "REFLECTION");
  20418. }
  20419. if (this._defines.SPECULAR) {
  20420. fallbacks.addFallback(0, "SPECULAR");
  20421. }
  20422. if (this._defines.BUMP) {
  20423. fallbacks.addFallback(0, "BUMP");
  20424. }
  20425. if (this._defines.PARALLAX) {
  20426. fallbacks.addFallback(1, "PARALLAX");
  20427. }
  20428. if (this._defines.PARALLAXOCCLUSION) {
  20429. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  20430. }
  20431. if (this._defines.SPECULAROVERALPHA) {
  20432. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  20433. }
  20434. if (this._defines.FOG) {
  20435. fallbacks.addFallback(1, "FOG");
  20436. }
  20437. if (this._defines.POINTSIZE) {
  20438. fallbacks.addFallback(0, "POINTSIZE");
  20439. }
  20440. if (this._defines.LOGARITHMICDEPTH) {
  20441. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  20442. }
  20443. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks);
  20444. if (this._defines.SPECULARTERM) {
  20445. fallbacks.addFallback(0, "SPECULARTERM");
  20446. }
  20447. if (this._defines.DIFFUSEFRESNEL) {
  20448. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  20449. }
  20450. if (this._defines.OPACITYFRESNEL) {
  20451. fallbacks.addFallback(2, "OPACITYFRESNEL");
  20452. }
  20453. if (this._defines.REFLECTIONFRESNEL) {
  20454. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  20455. }
  20456. if (this._defines.EMISSIVEFRESNEL) {
  20457. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  20458. }
  20459. if (this._defines.FRESNEL) {
  20460. fallbacks.addFallback(4, "FRESNEL");
  20461. }
  20462. //Attributes
  20463. var attribs = [BABYLON.VertexBuffer.PositionKind];
  20464. if (this._defines.NORMAL) {
  20465. attribs.push(BABYLON.VertexBuffer.NormalKind);
  20466. }
  20467. if (this._defines.UV1) {
  20468. attribs.push(BABYLON.VertexBuffer.UVKind);
  20469. }
  20470. if (this._defines.UV2) {
  20471. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  20472. }
  20473. if (this._defines.VERTEXCOLOR) {
  20474. attribs.push(BABYLON.VertexBuffer.ColorKind);
  20475. }
  20476. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  20477. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  20478. // Legacy browser patch
  20479. var shaderName = "default";
  20480. if (!scene.getEngine().getCaps().standardDerivatives) {
  20481. shaderName = "legacydefault";
  20482. }
  20483. var join = this._defines.toString();
  20484. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  20485. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  20486. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  20487. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  20488. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  20489. "vFogInfos", "vFogColor", "pointSize",
  20490. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  20491. "mBones",
  20492. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  20493. "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3", "depthValues",
  20494. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  20495. "logarithmicDepthConstant"
  20496. ], ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler",
  20497. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  20498. ], join, fallbacks, this.onCompiled, this.onError);
  20499. }
  20500. if (!this._effect.isReady()) {
  20501. return false;
  20502. }
  20503. this._renderId = scene.getRenderId();
  20504. this._wasPreviouslyReady = true;
  20505. if (mesh) {
  20506. if (!mesh._materialDefines) {
  20507. mesh._materialDefines = new StandardMaterialDefines();
  20508. }
  20509. this._defines.cloneTo(mesh._materialDefines);
  20510. }
  20511. return true;
  20512. };
  20513. StandardMaterial.prototype.unbind = function () {
  20514. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  20515. this._effect.setTexture("reflection2DSampler", null);
  20516. }
  20517. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  20518. this._effect.setTexture("refraction2DSampler", null);
  20519. }
  20520. _super.prototype.unbind.call(this);
  20521. };
  20522. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  20523. this._effect.setMatrix("world", world);
  20524. };
  20525. StandardMaterial.prototype.bind = function (world, mesh) {
  20526. var scene = this.getScene();
  20527. // Matrices
  20528. this.bindOnlyWorldMatrix(world);
  20529. // Bones
  20530. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  20531. if (scene.getCachedMaterial() !== this) {
  20532. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  20533. if (StandardMaterial.FresnelEnabled) {
  20534. // Fresnel
  20535. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  20536. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  20537. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  20538. }
  20539. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  20540. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  20541. }
  20542. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  20543. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  20544. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  20545. }
  20546. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  20547. this._effect.setColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  20548. this._effect.setColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  20549. }
  20550. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  20551. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  20552. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  20553. }
  20554. }
  20555. // Textures
  20556. if (scene.texturesEnabled) {
  20557. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  20558. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  20559. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  20560. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  20561. }
  20562. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  20563. this._effect.setTexture("ambientSampler", this.ambientTexture);
  20564. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  20565. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  20566. }
  20567. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  20568. this._effect.setTexture("opacitySampler", this.opacityTexture);
  20569. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  20570. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  20571. }
  20572. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  20573. if (this.reflectionTexture.isCube) {
  20574. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  20575. }
  20576. else {
  20577. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  20578. }
  20579. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  20580. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  20581. }
  20582. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  20583. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  20584. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  20585. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  20586. }
  20587. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  20588. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  20589. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  20590. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  20591. }
  20592. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  20593. this._effect.setTexture("specularSampler", this.specularTexture);
  20594. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  20595. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  20596. }
  20597. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  20598. this._effect.setTexture("bumpSampler", this.bumpTexture);
  20599. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  20600. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  20601. }
  20602. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  20603. var depth = 1.0;
  20604. if (this.refractionTexture.isCube) {
  20605. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  20606. }
  20607. else {
  20608. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  20609. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  20610. if (this.refractionTexture.depth) {
  20611. depth = this.refractionTexture.depth;
  20612. }
  20613. }
  20614. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  20615. }
  20616. }
  20617. // Clip plane
  20618. BABYLON.MaterialHelper.BindClipPlane(this._effect, scene);
  20619. // Point size
  20620. if (this.pointsCloud) {
  20621. this._effect.setFloat("pointSize", this.pointSize);
  20622. }
  20623. // Colors
  20624. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  20625. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  20626. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  20627. if (this._defines.SPECULARTERM) {
  20628. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  20629. }
  20630. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  20631. }
  20632. if (scene.getCachedMaterial() !== this || !this.isFrozen) {
  20633. // Diffuse
  20634. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  20635. // Lights
  20636. if (scene.lightsEnabled && !this.disableLighting) {
  20637. BABYLON.MaterialHelper.BindLights(scene, mesh, this._effect, this._defines);
  20638. }
  20639. // View
  20640. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture || this.refractionTexture) {
  20641. this._effect.setMatrix("view", scene.getViewMatrix());
  20642. }
  20643. // Fog
  20644. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._effect);
  20645. // Log. depth
  20646. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, scene);
  20647. }
  20648. _super.prototype.bind.call(this, world, mesh);
  20649. };
  20650. StandardMaterial.prototype.getAnimatables = function () {
  20651. var results = [];
  20652. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  20653. results.push(this.diffuseTexture);
  20654. }
  20655. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  20656. results.push(this.ambientTexture);
  20657. }
  20658. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  20659. results.push(this.opacityTexture);
  20660. }
  20661. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  20662. results.push(this.reflectionTexture);
  20663. }
  20664. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  20665. results.push(this.emissiveTexture);
  20666. }
  20667. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  20668. results.push(this.specularTexture);
  20669. }
  20670. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  20671. results.push(this.bumpTexture);
  20672. }
  20673. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  20674. results.push(this.lightmapTexture);
  20675. }
  20676. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  20677. results.push(this.refractionTexture);
  20678. }
  20679. return results;
  20680. };
  20681. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  20682. if (this.diffuseTexture) {
  20683. this.diffuseTexture.dispose();
  20684. }
  20685. if (this.ambientTexture) {
  20686. this.ambientTexture.dispose();
  20687. }
  20688. if (this.opacityTexture) {
  20689. this.opacityTexture.dispose();
  20690. }
  20691. if (this.reflectionTexture) {
  20692. this.reflectionTexture.dispose();
  20693. }
  20694. if (this.emissiveTexture) {
  20695. this.emissiveTexture.dispose();
  20696. }
  20697. if (this.specularTexture) {
  20698. this.specularTexture.dispose();
  20699. }
  20700. if (this.bumpTexture) {
  20701. this.bumpTexture.dispose();
  20702. }
  20703. if (this.lightmapTexture) {
  20704. this.lightmapTexture.dispose();
  20705. }
  20706. if (this.refractionTexture) {
  20707. this.refractionTexture.dispose();
  20708. }
  20709. _super.prototype.dispose.call(this, forceDisposeEffect);
  20710. };
  20711. StandardMaterial.prototype.clone = function (name) {
  20712. var _this = this;
  20713. return BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  20714. };
  20715. StandardMaterial.prototype.serialize = function () {
  20716. return BABYLON.SerializationHelper.Serialize(this);
  20717. };
  20718. // Statics
  20719. StandardMaterial.Parse = function (source, scene, rootUrl) {
  20720. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  20721. };
  20722. // Flags used to enable or disable a type of texture for all Standard Materials
  20723. StandardMaterial.DiffuseTextureEnabled = true;
  20724. StandardMaterial.AmbientTextureEnabled = true;
  20725. StandardMaterial.OpacityTextureEnabled = true;
  20726. StandardMaterial.ReflectionTextureEnabled = true;
  20727. StandardMaterial.EmissiveTextureEnabled = true;
  20728. StandardMaterial.SpecularTextureEnabled = true;
  20729. StandardMaterial.BumpTextureEnabled = true;
  20730. StandardMaterial.FresnelEnabled = true;
  20731. StandardMaterial.LightmapTextureEnabled = true;
  20732. StandardMaterial.RefractionTextureEnabled = true;
  20733. __decorate([
  20734. BABYLON.serializeAsTexture()
  20735. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  20736. __decorate([
  20737. BABYLON.serializeAsTexture()
  20738. ], StandardMaterial.prototype, "ambientTexture", void 0);
  20739. __decorate([
  20740. BABYLON.serializeAsTexture()
  20741. ], StandardMaterial.prototype, "opacityTexture", void 0);
  20742. __decorate([
  20743. BABYLON.serializeAsTexture()
  20744. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  20745. __decorate([
  20746. BABYLON.serializeAsTexture()
  20747. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  20748. __decorate([
  20749. BABYLON.serializeAsTexture()
  20750. ], StandardMaterial.prototype, "specularTexture", void 0);
  20751. __decorate([
  20752. BABYLON.serializeAsTexture()
  20753. ], StandardMaterial.prototype, "bumpTexture", void 0);
  20754. __decorate([
  20755. BABYLON.serializeAsTexture()
  20756. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  20757. __decorate([
  20758. BABYLON.serializeAsTexture()
  20759. ], StandardMaterial.prototype, "refractionTexture", void 0);
  20760. __decorate([
  20761. BABYLON.serializeAsColor3("ambient")
  20762. ], StandardMaterial.prototype, "ambientColor", void 0);
  20763. __decorate([
  20764. BABYLON.serializeAsColor3("diffuse")
  20765. ], StandardMaterial.prototype, "diffuseColor", void 0);
  20766. __decorate([
  20767. BABYLON.serializeAsColor3("specular")
  20768. ], StandardMaterial.prototype, "specularColor", void 0);
  20769. __decorate([
  20770. BABYLON.serializeAsColor3("emissive")
  20771. ], StandardMaterial.prototype, "emissiveColor", void 0);
  20772. __decorate([
  20773. BABYLON.serialize()
  20774. ], StandardMaterial.prototype, "specularPower", void 0);
  20775. __decorate([
  20776. BABYLON.serialize()
  20777. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  20778. __decorate([
  20779. BABYLON.serialize()
  20780. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  20781. __decorate([
  20782. BABYLON.serialize()
  20783. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  20784. __decorate([
  20785. BABYLON.serialize()
  20786. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  20787. __decorate([
  20788. BABYLON.serialize()
  20789. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  20790. __decorate([
  20791. BABYLON.serialize()
  20792. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  20793. __decorate([
  20794. BABYLON.serialize()
  20795. ], StandardMaterial.prototype, "disableLighting", void 0);
  20796. __decorate([
  20797. BABYLON.serialize()
  20798. ], StandardMaterial.prototype, "useParallax", void 0);
  20799. __decorate([
  20800. BABYLON.serialize()
  20801. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  20802. __decorate([
  20803. BABYLON.serialize()
  20804. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  20805. __decorate([
  20806. BABYLON.serialize()
  20807. ], StandardMaterial.prototype, "roughness", void 0);
  20808. __decorate([
  20809. BABYLON.serialize()
  20810. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  20811. __decorate([
  20812. BABYLON.serialize()
  20813. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  20814. __decorate([
  20815. BABYLON.serialize()
  20816. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  20817. __decorate([
  20818. BABYLON.serializeAsFresnelParameters()
  20819. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  20820. __decorate([
  20821. BABYLON.serializeAsFresnelParameters()
  20822. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  20823. __decorate([
  20824. BABYLON.serializeAsFresnelParameters()
  20825. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  20826. __decorate([
  20827. BABYLON.serializeAsFresnelParameters()
  20828. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  20829. __decorate([
  20830. BABYLON.serializeAsFresnelParameters()
  20831. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  20832. __decorate([
  20833. BABYLON.serialize()
  20834. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  20835. __decorate([
  20836. BABYLON.serialize()
  20837. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  20838. return StandardMaterial;
  20839. })(BABYLON.Material);
  20840. BABYLON.StandardMaterial = StandardMaterial;
  20841. })(BABYLON || (BABYLON = {}));
  20842. var BABYLON;
  20843. (function (BABYLON) {
  20844. var MultiMaterial = (function (_super) {
  20845. __extends(MultiMaterial, _super);
  20846. function MultiMaterial(name, scene) {
  20847. _super.call(this, name, scene, true);
  20848. this.subMaterials = new Array();
  20849. scene.multiMaterials.push(this);
  20850. }
  20851. // Properties
  20852. MultiMaterial.prototype.getSubMaterial = function (index) {
  20853. if (index < 0 || index >= this.subMaterials.length) {
  20854. return this.getScene().defaultMaterial;
  20855. }
  20856. return this.subMaterials[index];
  20857. };
  20858. // Methods
  20859. MultiMaterial.prototype.isReady = function (mesh) {
  20860. for (var index = 0; index < this.subMaterials.length; index++) {
  20861. var subMaterial = this.subMaterials[index];
  20862. if (subMaterial) {
  20863. if (!this.subMaterials[index].isReady(mesh)) {
  20864. return false;
  20865. }
  20866. }
  20867. }
  20868. return true;
  20869. };
  20870. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  20871. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  20872. for (var index = 0; index < this.subMaterials.length; index++) {
  20873. var subMaterial = null;
  20874. if (cloneChildren) {
  20875. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  20876. }
  20877. else {
  20878. subMaterial = this.subMaterials[index];
  20879. }
  20880. newMultiMaterial.subMaterials.push(subMaterial);
  20881. }
  20882. return newMultiMaterial;
  20883. };
  20884. MultiMaterial.prototype.serialize = function () {
  20885. var serializationObject = {};
  20886. serializationObject.name = this.name;
  20887. serializationObject.id = this.id;
  20888. serializationObject.tags = BABYLON.Tags.GetTags(this);
  20889. serializationObject.materials = [];
  20890. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  20891. var subMat = this.subMaterials[matIndex];
  20892. if (subMat) {
  20893. serializationObject.materials.push(subMat.id);
  20894. }
  20895. else {
  20896. serializationObject.materials.push(null);
  20897. }
  20898. }
  20899. return serializationObject;
  20900. };
  20901. return MultiMaterial;
  20902. })(BABYLON.Material);
  20903. BABYLON.MultiMaterial = MultiMaterial;
  20904. })(BABYLON || (BABYLON = {}));
  20905. var BABYLON;
  20906. (function (BABYLON) {
  20907. var SceneLoader = (function () {
  20908. function SceneLoader() {
  20909. }
  20910. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  20911. get: function () {
  20912. return SceneLoader._ForceFullSceneLoadingForIncremental;
  20913. },
  20914. set: function (value) {
  20915. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  20916. },
  20917. enumerable: true,
  20918. configurable: true
  20919. });
  20920. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  20921. get: function () {
  20922. return SceneLoader._ShowLoadingScreen;
  20923. },
  20924. set: function (value) {
  20925. SceneLoader._ShowLoadingScreen = value;
  20926. },
  20927. enumerable: true,
  20928. configurable: true
  20929. });
  20930. SceneLoader._getPluginForFilename = function (sceneFilename) {
  20931. var dotPosition = sceneFilename.lastIndexOf(".");
  20932. var queryStringPosition = sceneFilename.indexOf("?");
  20933. if (queryStringPosition === -1) {
  20934. queryStringPosition = sceneFilename.length;
  20935. }
  20936. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  20937. for (var index = 0; index < this._registeredPlugins.length; index++) {
  20938. var plugin = this._registeredPlugins[index];
  20939. if (plugin.extensions.indexOf(extension) !== -1) {
  20940. return plugin;
  20941. }
  20942. }
  20943. return this._registeredPlugins[this._registeredPlugins.length - 1];
  20944. };
  20945. // Public functions
  20946. SceneLoader.GetPluginForExtension = function (extension) {
  20947. for (var index = 0; index < this._registeredPlugins.length; index++) {
  20948. var plugin = this._registeredPlugins[index];
  20949. if (plugin.extensions.indexOf(extension) !== -1) {
  20950. return plugin;
  20951. }
  20952. }
  20953. return null;
  20954. };
  20955. SceneLoader.RegisterPlugin = function (plugin) {
  20956. plugin.extensions = plugin.extensions.toLowerCase();
  20957. SceneLoader._registeredPlugins.push(plugin);
  20958. };
  20959. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  20960. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  20961. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  20962. return;
  20963. }
  20964. var loadingToken = {};
  20965. scene._addPendingData(loadingToken);
  20966. var manifestChecked = function (success) {
  20967. scene.database = database;
  20968. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  20969. var importMeshFromData = function (data) {
  20970. var meshes = [];
  20971. var particleSystems = [];
  20972. var skeletons = [];
  20973. try {
  20974. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  20975. if (onerror) {
  20976. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  20977. }
  20978. scene._removePendingData(loadingToken);
  20979. return;
  20980. }
  20981. }
  20982. catch (e) {
  20983. if (onerror) {
  20984. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename + ' (Exception: ' + e + ')');
  20985. }
  20986. scene._removePendingData(loadingToken);
  20987. return;
  20988. }
  20989. if (onsuccess) {
  20990. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  20991. onsuccess(meshes, particleSystems, skeletons);
  20992. scene._removePendingData(loadingToken);
  20993. }
  20994. };
  20995. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  20996. // Direct load
  20997. importMeshFromData(sceneFilename.substr(5));
  20998. return;
  20999. }
  21000. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  21001. importMeshFromData(data);
  21002. }, progressCallBack, database);
  21003. };
  21004. if (scene.getEngine().enableOfflineSupport && !(sceneFilename.substr && sceneFilename.substr(0, 5) === "data:")) {
  21005. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  21006. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  21007. }
  21008. else {
  21009. // If the scene is a data stream or offline support is not enabled, it's a direct load
  21010. manifestChecked(true);
  21011. }
  21012. };
  21013. /**
  21014. * Load a scene
  21015. * @param rootUrl a string that defines the root url for scene and resources
  21016. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  21017. * @param engine is the instance of BABYLON.Engine to use to create the scene
  21018. */
  21019. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  21020. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  21021. };
  21022. /**
  21023. * Append a scene
  21024. * @param rootUrl a string that defines the root url for scene and resources
  21025. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  21026. * @param scene is the instance of BABYLON.Scene to append to
  21027. */
  21028. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  21029. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  21030. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  21031. return;
  21032. }
  21033. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  21034. var database;
  21035. var loadingToken = {};
  21036. scene._addPendingData(loadingToken);
  21037. if (SceneLoader.ShowLoadingScreen) {
  21038. scene.getEngine().displayLoadingUI();
  21039. }
  21040. var loadSceneFromData = function (data) {
  21041. scene.database = database;
  21042. if (!plugin.load(scene, data, rootUrl)) {
  21043. if (onerror) {
  21044. onerror(scene);
  21045. }
  21046. scene._removePendingData(loadingToken);
  21047. scene.getEngine().hideLoadingUI();
  21048. return;
  21049. }
  21050. if (onsuccess) {
  21051. onsuccess(scene);
  21052. }
  21053. scene._removePendingData(loadingToken);
  21054. if (SceneLoader.ShowLoadingScreen) {
  21055. scene.executeWhenReady(function () {
  21056. scene.getEngine().hideLoadingUI();
  21057. });
  21058. }
  21059. };
  21060. var manifestChecked = function (success) {
  21061. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  21062. };
  21063. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  21064. // Direct load
  21065. loadSceneFromData(sceneFilename.substr(5));
  21066. return;
  21067. }
  21068. if (rootUrl.indexOf("file:") === -1) {
  21069. if (scene.getEngine().enableOfflineSupport) {
  21070. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  21071. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  21072. }
  21073. else {
  21074. manifestChecked(true);
  21075. }
  21076. }
  21077. else {
  21078. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  21079. }
  21080. };
  21081. // Flags
  21082. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  21083. SceneLoader._ShowLoadingScreen = true;
  21084. // Members
  21085. SceneLoader._registeredPlugins = new Array();
  21086. return SceneLoader;
  21087. })();
  21088. BABYLON.SceneLoader = SceneLoader;
  21089. ;
  21090. })(BABYLON || (BABYLON = {}));
  21091. var BABYLON;
  21092. (function (BABYLON) {
  21093. var Internals;
  21094. (function (Internals) {
  21095. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  21096. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  21097. var parsedMaterial = parsedData.materials[index];
  21098. if (parsedMaterial.id === id) {
  21099. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  21100. }
  21101. }
  21102. return null;
  21103. };
  21104. var isDescendantOf = function (mesh, names, hierarchyIds) {
  21105. names = (names instanceof Array) ? names : [names];
  21106. for (var i in names) {
  21107. if (mesh.name === names[i]) {
  21108. hierarchyIds.push(mesh.id);
  21109. return true;
  21110. }
  21111. }
  21112. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  21113. hierarchyIds.push(mesh.id);
  21114. return true;
  21115. }
  21116. return false;
  21117. };
  21118. BABYLON.SceneLoader.RegisterPlugin({
  21119. extensions: ".babylon",
  21120. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  21121. var parsedData = JSON.parse(data);
  21122. var loadedSkeletonsIds = [];
  21123. var loadedMaterialsIds = [];
  21124. var hierarchyIds = [];
  21125. var index;
  21126. var cache;
  21127. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  21128. var parsedMesh = parsedData.meshes[index];
  21129. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  21130. if (meshesNames instanceof Array) {
  21131. // Remove found mesh name from list.
  21132. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  21133. }
  21134. //Geometry?
  21135. if (parsedMesh.geometryId) {
  21136. //does the file contain geometries?
  21137. if (parsedData.geometries) {
  21138. //find the correct geometry and add it to the scene
  21139. var found = false;
  21140. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  21141. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  21142. return;
  21143. }
  21144. else {
  21145. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  21146. if (parsedGeometryData.id === parsedMesh.geometryId) {
  21147. switch (geometryType) {
  21148. case "boxes":
  21149. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  21150. break;
  21151. case "spheres":
  21152. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  21153. break;
  21154. case "cylinders":
  21155. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  21156. break;
  21157. case "toruses":
  21158. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  21159. break;
  21160. case "grounds":
  21161. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  21162. break;
  21163. case "planes":
  21164. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  21165. break;
  21166. case "torusKnots":
  21167. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  21168. break;
  21169. case "vertexData":
  21170. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  21171. break;
  21172. }
  21173. found = true;
  21174. }
  21175. });
  21176. }
  21177. });
  21178. if (!found) {
  21179. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  21180. }
  21181. }
  21182. }
  21183. // Material ?
  21184. if (parsedMesh.materialId) {
  21185. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  21186. if (!materialFound && parsedData.multiMaterials) {
  21187. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  21188. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  21189. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  21190. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  21191. var subMatId = parsedMultiMaterial.materials[matIndex];
  21192. loadedMaterialsIds.push(subMatId);
  21193. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  21194. }
  21195. loadedMaterialsIds.push(parsedMultiMaterial.id);
  21196. BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  21197. materialFound = true;
  21198. break;
  21199. }
  21200. }
  21201. }
  21202. if (!materialFound) {
  21203. loadedMaterialsIds.push(parsedMesh.materialId);
  21204. if (!parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl)) {
  21205. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  21206. }
  21207. }
  21208. }
  21209. // Skeleton ?
  21210. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  21211. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  21212. if (!skeletonAlreadyLoaded) {
  21213. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  21214. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  21215. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  21216. skeletons.push(BABYLON.Skeleton.Parse(parsedSkeleton, scene));
  21217. loadedSkeletonsIds.push(parsedSkeleton.id);
  21218. }
  21219. }
  21220. }
  21221. }
  21222. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  21223. meshes.push(mesh);
  21224. }
  21225. }
  21226. // Connecting parents
  21227. var currentMesh;
  21228. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  21229. currentMesh = scene.meshes[index];
  21230. if (currentMesh._waitingParentId) {
  21231. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  21232. currentMesh._waitingParentId = undefined;
  21233. }
  21234. }
  21235. // freeze and compute world matrix application
  21236. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  21237. currentMesh = scene.meshes[index];
  21238. if (currentMesh._waitingFreezeWorldMatrix) {
  21239. currentMesh.freezeWorldMatrix();
  21240. currentMesh._waitingFreezeWorldMatrix = undefined;
  21241. }
  21242. else {
  21243. currentMesh.computeWorldMatrix(true);
  21244. }
  21245. }
  21246. // Particles
  21247. if (parsedData.particleSystems) {
  21248. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  21249. var parsedParticleSystem = parsedData.particleSystems[index];
  21250. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  21251. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  21252. }
  21253. }
  21254. }
  21255. return true;
  21256. },
  21257. load: function (scene, data, rootUrl) {
  21258. var parsedData = JSON.parse(data);
  21259. // Scene
  21260. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  21261. scene.autoClear = parsedData.autoClear;
  21262. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  21263. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  21264. if (parsedData.gravity) {
  21265. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  21266. }
  21267. // Fog
  21268. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  21269. scene.fogMode = parsedData.fogMode;
  21270. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  21271. scene.fogStart = parsedData.fogStart;
  21272. scene.fogEnd = parsedData.fogEnd;
  21273. scene.fogDensity = parsedData.fogDensity;
  21274. }
  21275. //Physics
  21276. if (parsedData.physicsEnabled) {
  21277. var physicsPlugin;
  21278. if (parsedData.physicsEngine === "cannon") {
  21279. physicsPlugin = new BABYLON.CannonJSPlugin();
  21280. }
  21281. else if (parsedData.physicsEngine === "oimo") {
  21282. physicsPlugin = new BABYLON.OimoJSPlugin();
  21283. }
  21284. //else - default engine, which is currently oimo
  21285. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  21286. scene.enablePhysics(physicsGravity, physicsPlugin);
  21287. }
  21288. //collisions, if defined. otherwise, default is true
  21289. if (parsedData.collisionsEnabled != undefined) {
  21290. scene.collisionsEnabled = parsedData.collisionsEnabled;
  21291. }
  21292. scene.workerCollisions = !!parsedData.workerCollisions;
  21293. var index;
  21294. var cache;
  21295. // Lights
  21296. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  21297. var parsedLight = parsedData.lights[index];
  21298. BABYLON.Light.Parse(parsedLight, scene);
  21299. }
  21300. // Animations
  21301. if (parsedData.animations) {
  21302. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  21303. var parsedAnimation = parsedData.animations[index];
  21304. scene.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21305. }
  21306. }
  21307. if (parsedData.autoAnimate) {
  21308. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  21309. }
  21310. // Materials
  21311. if (parsedData.materials) {
  21312. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  21313. var parsedMaterial = parsedData.materials[index];
  21314. BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  21315. }
  21316. }
  21317. if (parsedData.multiMaterials) {
  21318. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  21319. var parsedMultiMaterial = parsedData.multiMaterials[index];
  21320. BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  21321. }
  21322. }
  21323. // Skeletons
  21324. if (parsedData.skeletons) {
  21325. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  21326. var parsedSkeleton = parsedData.skeletons[index];
  21327. BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  21328. }
  21329. }
  21330. // Geometries
  21331. var geometries = parsedData.geometries;
  21332. if (geometries) {
  21333. // Boxes
  21334. var boxes = geometries.boxes;
  21335. if (boxes) {
  21336. for (index = 0, cache = boxes.length; index < cache; index++) {
  21337. var parsedBox = boxes[index];
  21338. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  21339. }
  21340. }
  21341. // Spheres
  21342. var spheres = geometries.spheres;
  21343. if (spheres) {
  21344. for (index = 0, cache = spheres.length; index < cache; index++) {
  21345. var parsedSphere = spheres[index];
  21346. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  21347. }
  21348. }
  21349. // Cylinders
  21350. var cylinders = geometries.cylinders;
  21351. if (cylinders) {
  21352. for (index = 0, cache = cylinders.length; index < cache; index++) {
  21353. var parsedCylinder = cylinders[index];
  21354. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  21355. }
  21356. }
  21357. // Toruses
  21358. var toruses = geometries.toruses;
  21359. if (toruses) {
  21360. for (index = 0, cache = toruses.length; index < cache; index++) {
  21361. var parsedTorus = toruses[index];
  21362. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  21363. }
  21364. }
  21365. // Grounds
  21366. var grounds = geometries.grounds;
  21367. if (grounds) {
  21368. for (index = 0, cache = grounds.length; index < cache; index++) {
  21369. var parsedGround = grounds[index];
  21370. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  21371. }
  21372. }
  21373. // Planes
  21374. var planes = geometries.planes;
  21375. if (planes) {
  21376. for (index = 0, cache = planes.length; index < cache; index++) {
  21377. var parsedPlane = planes[index];
  21378. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  21379. }
  21380. }
  21381. // TorusKnots
  21382. var torusKnots = geometries.torusKnots;
  21383. if (torusKnots) {
  21384. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  21385. var parsedTorusKnot = torusKnots[index];
  21386. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  21387. }
  21388. }
  21389. // VertexData
  21390. var vertexData = geometries.vertexData;
  21391. if (vertexData) {
  21392. for (index = 0, cache = vertexData.length; index < cache; index++) {
  21393. var parsedVertexData = vertexData[index];
  21394. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  21395. }
  21396. }
  21397. }
  21398. // Meshes
  21399. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  21400. var parsedMesh = parsedData.meshes[index];
  21401. BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  21402. }
  21403. // Cameras
  21404. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  21405. var parsedCamera = parsedData.cameras[index];
  21406. BABYLON.Camera.Parse(parsedCamera, scene);
  21407. }
  21408. if (parsedData.activeCameraID) {
  21409. scene.setActiveCameraByID(parsedData.activeCameraID);
  21410. }
  21411. // Browsing all the graph to connect the dots
  21412. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  21413. var camera = scene.cameras[index];
  21414. if (camera._waitingParentId) {
  21415. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  21416. camera._waitingParentId = undefined;
  21417. }
  21418. }
  21419. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  21420. var light = scene.lights[index];
  21421. if (light._waitingParentId) {
  21422. light.parent = scene.getLastEntryByID(light._waitingParentId);
  21423. light._waitingParentId = undefined;
  21424. }
  21425. }
  21426. // Sounds
  21427. var loadedSounds = [];
  21428. var loadedSound;
  21429. if (BABYLON.AudioEngine && parsedData.sounds) {
  21430. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  21431. var parsedSound = parsedData.sounds[index];
  21432. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  21433. if (!parsedSound.url)
  21434. parsedSound.url = parsedSound.name;
  21435. if (!loadedSounds[parsedSound.url]) {
  21436. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  21437. loadedSounds[parsedSound.url] = loadedSound;
  21438. }
  21439. else {
  21440. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  21441. }
  21442. }
  21443. else {
  21444. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  21445. }
  21446. }
  21447. }
  21448. loadedSounds = [];
  21449. // Connect parents & children and parse actions
  21450. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  21451. var mesh = scene.meshes[index];
  21452. if (mesh._waitingParentId) {
  21453. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  21454. mesh._waitingParentId = undefined;
  21455. }
  21456. if (mesh._waitingActions) {
  21457. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  21458. mesh._waitingActions = undefined;
  21459. }
  21460. }
  21461. // freeze world matrix application
  21462. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  21463. var currentMesh = scene.meshes[index];
  21464. if (currentMesh._waitingFreezeWorldMatrix) {
  21465. currentMesh.freezeWorldMatrix();
  21466. currentMesh._waitingFreezeWorldMatrix = undefined;
  21467. }
  21468. else {
  21469. currentMesh.computeWorldMatrix(true);
  21470. }
  21471. }
  21472. // Particles Systems
  21473. if (parsedData.particleSystems) {
  21474. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  21475. var parsedParticleSystem = parsedData.particleSystems[index];
  21476. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  21477. }
  21478. }
  21479. // Lens flares
  21480. if (parsedData.lensFlareSystems) {
  21481. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  21482. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  21483. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  21484. }
  21485. }
  21486. // Shadows
  21487. if (parsedData.shadowGenerators) {
  21488. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  21489. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  21490. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  21491. }
  21492. }
  21493. // Actions (scene)
  21494. if (parsedData.actions) {
  21495. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  21496. }
  21497. // Finish
  21498. return true;
  21499. }
  21500. });
  21501. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  21502. })(BABYLON || (BABYLON = {}));
  21503. var BABYLON;
  21504. (function (BABYLON) {
  21505. var SpriteManager = (function () {
  21506. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  21507. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  21508. this.name = name;
  21509. this.cellSize = cellSize;
  21510. this.sprites = new Array();
  21511. this.renderingGroupId = 0;
  21512. this.layerMask = 0x0FFFFFFF;
  21513. this.fogEnabled = true;
  21514. this.isPickable = false;
  21515. this._vertexDeclaration = [4, 4, 4, 4];
  21516. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  21517. this._capacity = capacity;
  21518. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  21519. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21520. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21521. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  21522. this._scene = scene;
  21523. this._scene.spriteManagers.push(this);
  21524. // VBO
  21525. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  21526. var indices = [];
  21527. var index = 0;
  21528. for (var count = 0; count < capacity; count++) {
  21529. indices.push(index);
  21530. indices.push(index + 1);
  21531. indices.push(index + 2);
  21532. indices.push(index);
  21533. indices.push(index + 2);
  21534. indices.push(index + 3);
  21535. index += 4;
  21536. }
  21537. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21538. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  21539. // Effects
  21540. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  21541. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  21542. }
  21543. Object.defineProperty(SpriteManager.prototype, "texture", {
  21544. get: function () {
  21545. return this._spriteTexture;
  21546. },
  21547. set: function (value) {
  21548. this._spriteTexture = value;
  21549. },
  21550. enumerable: true,
  21551. configurable: true
  21552. });
  21553. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  21554. var arrayOffset = index * 16;
  21555. if (offsetX === 0)
  21556. offsetX = this._epsilon;
  21557. else if (offsetX === 1)
  21558. offsetX = 1 - this._epsilon;
  21559. if (offsetY === 0)
  21560. offsetY = this._epsilon;
  21561. else if (offsetY === 1)
  21562. offsetY = 1 - this._epsilon;
  21563. this._vertices[arrayOffset] = sprite.position.x;
  21564. this._vertices[arrayOffset + 1] = sprite.position.y;
  21565. this._vertices[arrayOffset + 2] = sprite.position.z;
  21566. this._vertices[arrayOffset + 3] = sprite.angle;
  21567. this._vertices[arrayOffset + 4] = sprite.width;
  21568. this._vertices[arrayOffset + 5] = sprite.height;
  21569. this._vertices[arrayOffset + 6] = offsetX;
  21570. this._vertices[arrayOffset + 7] = offsetY;
  21571. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  21572. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  21573. var offset = (sprite.cellIndex / rowSize) >> 0;
  21574. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  21575. this._vertices[arrayOffset + 11] = offset;
  21576. // Color
  21577. this._vertices[arrayOffset + 12] = sprite.color.r;
  21578. this._vertices[arrayOffset + 13] = sprite.color.g;
  21579. this._vertices[arrayOffset + 14] = sprite.color.b;
  21580. this._vertices[arrayOffset + 15] = sprite.color.a;
  21581. };
  21582. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  21583. var count = Math.min(this._capacity, this.sprites.length);
  21584. var min = BABYLON.Vector3.Zero();
  21585. var max = BABYLON.Vector3.Zero();
  21586. var distance = Number.MAX_VALUE;
  21587. var currentSprite;
  21588. var cameraSpacePosition = BABYLON.Vector3.Zero();
  21589. var cameraView = camera.getViewMatrix();
  21590. for (var index = 0; index < count; index++) {
  21591. var sprite = this.sprites[index];
  21592. if (!sprite) {
  21593. continue;
  21594. }
  21595. if (predicate) {
  21596. if (!predicate(sprite)) {
  21597. continue;
  21598. }
  21599. }
  21600. else if (!sprite.isPickable) {
  21601. continue;
  21602. }
  21603. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  21604. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  21605. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  21606. if (ray.intersectsBoxMinMax(min, max)) {
  21607. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  21608. if (distance > currentDistance) {
  21609. distance = currentDistance;
  21610. currentSprite = sprite;
  21611. if (fastCheck) {
  21612. break;
  21613. }
  21614. }
  21615. }
  21616. }
  21617. if (currentSprite) {
  21618. var result = new BABYLON.PickingInfo();
  21619. result.hit = true;
  21620. result.pickedSprite = currentSprite;
  21621. result.distance = distance;
  21622. return result;
  21623. }
  21624. return null;
  21625. };
  21626. SpriteManager.prototype.render = function () {
  21627. // Check
  21628. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  21629. return;
  21630. var engine = this._scene.getEngine();
  21631. var baseSize = this._spriteTexture.getBaseSize();
  21632. // Sprites
  21633. var deltaTime = engine.getDeltaTime();
  21634. var max = Math.min(this._capacity, this.sprites.length);
  21635. var rowSize = baseSize.width / this.cellSize;
  21636. var offset = 0;
  21637. for (var index = 0; index < max; index++) {
  21638. var sprite = this.sprites[index];
  21639. if (!sprite) {
  21640. continue;
  21641. }
  21642. sprite._animate(deltaTime);
  21643. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  21644. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  21645. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  21646. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  21647. }
  21648. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  21649. // Render
  21650. var effect = this._effectBase;
  21651. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  21652. effect = this._effectFog;
  21653. }
  21654. engine.enableEffect(effect);
  21655. var viewMatrix = this._scene.getViewMatrix();
  21656. effect.setTexture("diffuseSampler", this._spriteTexture);
  21657. effect.setMatrix("view", viewMatrix);
  21658. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  21659. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  21660. // Fog
  21661. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  21662. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  21663. effect.setColor3("vFogColor", this._scene.fogColor);
  21664. }
  21665. // VBOs
  21666. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  21667. // Draw order
  21668. engine.setDepthFunctionToLessOrEqual();
  21669. effect.setBool("alphaTest", true);
  21670. engine.setColorWrite(false);
  21671. engine.draw(true, 0, max * 6);
  21672. engine.setColorWrite(true);
  21673. effect.setBool("alphaTest", false);
  21674. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21675. engine.draw(true, 0, max * 6);
  21676. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21677. };
  21678. SpriteManager.prototype.dispose = function () {
  21679. if (this._vertexBuffer) {
  21680. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21681. this._vertexBuffer = null;
  21682. }
  21683. if (this._indexBuffer) {
  21684. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21685. this._indexBuffer = null;
  21686. }
  21687. if (this._spriteTexture) {
  21688. this._spriteTexture.dispose();
  21689. this._spriteTexture = null;
  21690. }
  21691. // Remove from scene
  21692. var index = this._scene.spriteManagers.indexOf(this);
  21693. this._scene.spriteManagers.splice(index, 1);
  21694. // Callback
  21695. if (this.onDispose) {
  21696. this.onDispose();
  21697. }
  21698. };
  21699. return SpriteManager;
  21700. })();
  21701. BABYLON.SpriteManager = SpriteManager;
  21702. })(BABYLON || (BABYLON = {}));
  21703. var BABYLON;
  21704. (function (BABYLON) {
  21705. var Sprite = (function () {
  21706. function Sprite(name, manager) {
  21707. this.name = name;
  21708. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21709. this.width = 1.0;
  21710. this.height = 1.0;
  21711. this.angle = 0;
  21712. this.cellIndex = 0;
  21713. this.invertU = 0;
  21714. this.invertV = 0;
  21715. this.animations = new Array();
  21716. this.isPickable = false;
  21717. this._animationStarted = false;
  21718. this._loopAnimation = false;
  21719. this._fromIndex = 0;
  21720. this._toIndex = 0;
  21721. this._delay = 0;
  21722. this._direction = 1;
  21723. this._frameCount = 0;
  21724. this._time = 0;
  21725. this._manager = manager;
  21726. this._manager.sprites.push(this);
  21727. this.position = BABYLON.Vector3.Zero();
  21728. }
  21729. Object.defineProperty(Sprite.prototype, "size", {
  21730. get: function () {
  21731. return this.width;
  21732. },
  21733. set: function (value) {
  21734. this.width = value;
  21735. this.height = value;
  21736. },
  21737. enumerable: true,
  21738. configurable: true
  21739. });
  21740. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  21741. this._fromIndex = from;
  21742. this._toIndex = to;
  21743. this._loopAnimation = loop;
  21744. this._delay = delay;
  21745. this._animationStarted = true;
  21746. this._direction = from < to ? 1 : -1;
  21747. this.cellIndex = from;
  21748. this._time = 0;
  21749. };
  21750. Sprite.prototype.stopAnimation = function () {
  21751. this._animationStarted = false;
  21752. };
  21753. Sprite.prototype._animate = function (deltaTime) {
  21754. if (!this._animationStarted)
  21755. return;
  21756. this._time += deltaTime;
  21757. if (this._time > this._delay) {
  21758. this._time = this._time % this._delay;
  21759. this.cellIndex += this._direction;
  21760. if (this.cellIndex == this._toIndex) {
  21761. if (this._loopAnimation) {
  21762. this.cellIndex = this._fromIndex;
  21763. }
  21764. else {
  21765. this._animationStarted = false;
  21766. if (this.disposeWhenFinishedAnimating) {
  21767. this.dispose();
  21768. }
  21769. }
  21770. }
  21771. }
  21772. };
  21773. Sprite.prototype.dispose = function () {
  21774. for (var i = 0; i < this._manager.sprites.length; i++) {
  21775. if (this._manager.sprites[i] == this) {
  21776. this._manager.sprites.splice(i, 1);
  21777. }
  21778. }
  21779. };
  21780. return Sprite;
  21781. })();
  21782. BABYLON.Sprite = Sprite;
  21783. })(BABYLON || (BABYLON = {}));
  21784. var BABYLON;
  21785. (function (BABYLON) {
  21786. var Layer = (function () {
  21787. function Layer(name, imgUrl, scene, isBackground, color) {
  21788. this.name = name;
  21789. this.scale = new BABYLON.Vector2(1, 1);
  21790. this.offset = new BABYLON.Vector2(0, 0);
  21791. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  21792. this._vertexDeclaration = [2];
  21793. this._vertexStrideSize = 2 * 4;
  21794. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  21795. this.isBackground = isBackground === undefined ? true : isBackground;
  21796. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  21797. this._scene = scene;
  21798. this._scene.layers.push(this);
  21799. // VBO
  21800. var vertices = [];
  21801. vertices.push(1, 1);
  21802. vertices.push(-1, 1);
  21803. vertices.push(-1, -1);
  21804. vertices.push(1, -1);
  21805. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  21806. // Indices
  21807. var indices = [];
  21808. indices.push(0);
  21809. indices.push(1);
  21810. indices.push(2);
  21811. indices.push(0);
  21812. indices.push(2);
  21813. indices.push(3);
  21814. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21815. // Effects
  21816. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  21817. this._alphaTestEffect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  21818. }
  21819. Layer.prototype.render = function () {
  21820. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  21821. // Check
  21822. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  21823. return;
  21824. var engine = this._scene.getEngine();
  21825. if (this.onBeforeRender) {
  21826. this.onBeforeRender();
  21827. }
  21828. // Render
  21829. engine.enableEffect(currentEffect);
  21830. engine.setState(false);
  21831. // Texture
  21832. currentEffect.setTexture("textureSampler", this.texture);
  21833. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  21834. // Color
  21835. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  21836. // Scale / offset
  21837. currentEffect.setVector2("offset", this.offset);
  21838. currentEffect.setVector2("scale", this.scale);
  21839. // VBOs
  21840. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, currentEffect);
  21841. // Draw order
  21842. if (!this._alphaTestEffect) {
  21843. engine.setAlphaMode(this.alphaBlendingMode);
  21844. engine.draw(true, 0, 6);
  21845. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21846. }
  21847. else {
  21848. engine.draw(true, 0, 6);
  21849. }
  21850. if (this.onAfterRender) {
  21851. this.onAfterRender();
  21852. }
  21853. };
  21854. Layer.prototype.dispose = function () {
  21855. if (this._vertexBuffer) {
  21856. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21857. this._vertexBuffer = null;
  21858. }
  21859. if (this._indexBuffer) {
  21860. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21861. this._indexBuffer = null;
  21862. }
  21863. if (this.texture) {
  21864. this.texture.dispose();
  21865. this.texture = null;
  21866. }
  21867. // Remove from scene
  21868. var index = this._scene.layers.indexOf(this);
  21869. this._scene.layers.splice(index, 1);
  21870. // Callback
  21871. if (this.onDispose) {
  21872. this.onDispose();
  21873. }
  21874. };
  21875. return Layer;
  21876. })();
  21877. BABYLON.Layer = Layer;
  21878. })(BABYLON || (BABYLON = {}));
  21879. var BABYLON;
  21880. (function (BABYLON) {
  21881. var Particle = (function () {
  21882. function Particle() {
  21883. this.position = BABYLON.Vector3.Zero();
  21884. this.direction = BABYLON.Vector3.Zero();
  21885. this.color = new BABYLON.Color4(0, 0, 0, 0);
  21886. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  21887. this.lifeTime = 1.0;
  21888. this.age = 0;
  21889. this.size = 0;
  21890. this.angle = 0;
  21891. this.angularSpeed = 0;
  21892. }
  21893. Particle.prototype.copyTo = function (other) {
  21894. other.position.copyFrom(this.position);
  21895. other.direction.copyFrom(this.direction);
  21896. other.color.copyFrom(this.color);
  21897. other.colorStep.copyFrom(this.colorStep);
  21898. other.lifeTime = this.lifeTime;
  21899. other.age = this.age;
  21900. other.size = this.size;
  21901. other.angle = this.angle;
  21902. other.angularSpeed = this.angularSpeed;
  21903. };
  21904. return Particle;
  21905. })();
  21906. BABYLON.Particle = Particle;
  21907. })(BABYLON || (BABYLON = {}));
  21908. var BABYLON;
  21909. (function (BABYLON) {
  21910. var randomNumber = function (min, max) {
  21911. if (min === max) {
  21912. return (min);
  21913. }
  21914. var random = Math.random();
  21915. return ((random * (max - min)) + min);
  21916. };
  21917. var ParticleSystem = (function () {
  21918. function ParticleSystem(name, capacity, scene, customEffect) {
  21919. var _this = this;
  21920. this.name = name;
  21921. // Members
  21922. this.animations = [];
  21923. this.renderingGroupId = 0;
  21924. this.emitter = null;
  21925. this.emitRate = 10;
  21926. this.manualEmitCount = -1;
  21927. this.updateSpeed = 0.01;
  21928. this.targetStopDuration = 0;
  21929. this.disposeOnStop = false;
  21930. this.minEmitPower = 1;
  21931. this.maxEmitPower = 1;
  21932. this.minLifeTime = 1;
  21933. this.maxLifeTime = 1;
  21934. this.minSize = 1;
  21935. this.maxSize = 1;
  21936. this.minAngularSpeed = 0;
  21937. this.maxAngularSpeed = 0;
  21938. this.layerMask = 0x0FFFFFFF;
  21939. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  21940. this.forceDepthWrite = false;
  21941. this.gravity = BABYLON.Vector3.Zero();
  21942. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  21943. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  21944. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  21945. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  21946. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21947. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21948. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  21949. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21950. this.particles = new Array();
  21951. this._vertexDeclaration = [3, 4, 4];
  21952. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  21953. this._stockParticles = new Array();
  21954. this._newPartsExcess = 0;
  21955. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  21956. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  21957. this._scaledDirection = BABYLON.Vector3.Zero();
  21958. this._scaledGravity = BABYLON.Vector3.Zero();
  21959. this._currentRenderId = -1;
  21960. this._started = false;
  21961. this._stopped = false;
  21962. this._actualFrame = 0;
  21963. this.id = name;
  21964. this._capacity = capacity;
  21965. this._scene = scene;
  21966. this._customEffect = customEffect;
  21967. scene.particleSystems.push(this);
  21968. // VBO
  21969. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  21970. var indices = [];
  21971. var index = 0;
  21972. for (var count = 0; count < capacity; count++) {
  21973. indices.push(index);
  21974. indices.push(index + 1);
  21975. indices.push(index + 2);
  21976. indices.push(index);
  21977. indices.push(index + 2);
  21978. indices.push(index + 3);
  21979. index += 4;
  21980. }
  21981. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21982. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  21983. // Default behaviors
  21984. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  21985. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  21986. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  21987. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  21988. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  21989. };
  21990. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  21991. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  21992. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  21993. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  21994. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  21995. };
  21996. this.updateFunction = function (particles) {
  21997. for (var index = 0; index < particles.length; index++) {
  21998. var particle = particles[index];
  21999. particle.age += _this._scaledUpdateSpeed;
  22000. if (particle.age >= particle.lifeTime) {
  22001. _this.recycleParticle(particle);
  22002. index--;
  22003. continue;
  22004. }
  22005. else {
  22006. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  22007. particle.color.addInPlace(_this._scaledColorStep);
  22008. if (particle.color.a < 0)
  22009. particle.color.a = 0;
  22010. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  22011. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  22012. particle.position.addInPlace(_this._scaledDirection);
  22013. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  22014. particle.direction.addInPlace(_this._scaledGravity);
  22015. }
  22016. }
  22017. };
  22018. }
  22019. ParticleSystem.prototype.recycleParticle = function (particle) {
  22020. var lastParticle = this.particles.pop();
  22021. if (lastParticle !== particle) {
  22022. lastParticle.copyTo(particle);
  22023. this._stockParticles.push(lastParticle);
  22024. }
  22025. };
  22026. ParticleSystem.prototype.getCapacity = function () {
  22027. return this._capacity;
  22028. };
  22029. ParticleSystem.prototype.isAlive = function () {
  22030. return this._alive;
  22031. };
  22032. ParticleSystem.prototype.isStarted = function () {
  22033. return this._started;
  22034. };
  22035. ParticleSystem.prototype.start = function () {
  22036. this._started = true;
  22037. this._stopped = false;
  22038. this._actualFrame = 0;
  22039. };
  22040. ParticleSystem.prototype.stop = function () {
  22041. this._stopped = true;
  22042. };
  22043. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  22044. var offset = index * 11;
  22045. this._vertices[offset] = particle.position.x;
  22046. this._vertices[offset + 1] = particle.position.y;
  22047. this._vertices[offset + 2] = particle.position.z;
  22048. this._vertices[offset + 3] = particle.color.r;
  22049. this._vertices[offset + 4] = particle.color.g;
  22050. this._vertices[offset + 5] = particle.color.b;
  22051. this._vertices[offset + 6] = particle.color.a;
  22052. this._vertices[offset + 7] = particle.angle;
  22053. this._vertices[offset + 8] = particle.size;
  22054. this._vertices[offset + 9] = offsetX;
  22055. this._vertices[offset + 10] = offsetY;
  22056. };
  22057. ParticleSystem.prototype._update = function (newParticles) {
  22058. // Update current
  22059. this._alive = this.particles.length > 0;
  22060. this.updateFunction(this.particles);
  22061. // Add new ones
  22062. var worldMatrix;
  22063. if (this.emitter.position) {
  22064. worldMatrix = this.emitter.getWorldMatrix();
  22065. }
  22066. else {
  22067. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  22068. }
  22069. var particle;
  22070. for (var index = 0; index < newParticles; index++) {
  22071. if (this.particles.length === this._capacity) {
  22072. break;
  22073. }
  22074. if (this._stockParticles.length !== 0) {
  22075. particle = this._stockParticles.pop();
  22076. particle.age = 0;
  22077. }
  22078. else {
  22079. particle = new BABYLON.Particle();
  22080. }
  22081. this.particles.push(particle);
  22082. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  22083. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  22084. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  22085. particle.size = randomNumber(this.minSize, this.maxSize);
  22086. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  22087. this.startPositionFunction(worldMatrix, particle.position, particle);
  22088. var step = randomNumber(0, 1.0);
  22089. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  22090. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  22091. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  22092. }
  22093. };
  22094. ParticleSystem.prototype._getEffect = function () {
  22095. if (this._customEffect) {
  22096. return this._customEffect;
  22097. }
  22098. ;
  22099. var defines = [];
  22100. if (this._scene.clipPlane) {
  22101. defines.push("#define CLIPPLANE");
  22102. }
  22103. // Effect
  22104. var join = defines.join("\n");
  22105. if (this._cachedDefines !== join) {
  22106. this._cachedDefines = join;
  22107. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  22108. }
  22109. return this._effect;
  22110. };
  22111. ParticleSystem.prototype.animate = function () {
  22112. if (!this._started)
  22113. return;
  22114. var effect = this._getEffect();
  22115. // Check
  22116. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  22117. return;
  22118. if (this._currentRenderId === this._scene.getRenderId()) {
  22119. return;
  22120. }
  22121. this._currentRenderId = this._scene.getRenderId();
  22122. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  22123. // determine the number of particles we need to create
  22124. var newParticles;
  22125. if (this.manualEmitCount > -1) {
  22126. newParticles = this.manualEmitCount;
  22127. this._newPartsExcess = 0;
  22128. this.manualEmitCount = 0;
  22129. }
  22130. else {
  22131. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  22132. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  22133. }
  22134. if (this._newPartsExcess > 1.0) {
  22135. newParticles += this._newPartsExcess >> 0;
  22136. this._newPartsExcess -= this._newPartsExcess >> 0;
  22137. }
  22138. this._alive = false;
  22139. if (!this._stopped) {
  22140. this._actualFrame += this._scaledUpdateSpeed;
  22141. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  22142. this.stop();
  22143. }
  22144. else {
  22145. newParticles = 0;
  22146. }
  22147. this._update(newParticles);
  22148. // Stopped?
  22149. if (this._stopped) {
  22150. if (!this._alive) {
  22151. this._started = false;
  22152. if (this.disposeOnStop) {
  22153. this._scene._toBeDisposed.push(this);
  22154. }
  22155. }
  22156. }
  22157. // Update VBO
  22158. var offset = 0;
  22159. for (var index = 0; index < this.particles.length; index++) {
  22160. var particle = this.particles[index];
  22161. this._appendParticleVertex(offset++, particle, 0, 0);
  22162. this._appendParticleVertex(offset++, particle, 1, 0);
  22163. this._appendParticleVertex(offset++, particle, 1, 1);
  22164. this._appendParticleVertex(offset++, particle, 0, 1);
  22165. }
  22166. var engine = this._scene.getEngine();
  22167. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  22168. };
  22169. ParticleSystem.prototype.render = function () {
  22170. var effect = this._getEffect();
  22171. // Check
  22172. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  22173. return 0;
  22174. var engine = this._scene.getEngine();
  22175. // Render
  22176. engine.enableEffect(effect);
  22177. engine.setState(false);
  22178. var viewMatrix = this._scene.getViewMatrix();
  22179. effect.setTexture("diffuseSampler", this.particleTexture);
  22180. effect.setMatrix("view", viewMatrix);
  22181. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  22182. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  22183. if (this._scene.clipPlane) {
  22184. var clipPlane = this._scene.clipPlane;
  22185. var invView = viewMatrix.clone();
  22186. invView.invert();
  22187. effect.setMatrix("invView", invView);
  22188. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  22189. }
  22190. // VBOs
  22191. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  22192. // Draw order
  22193. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  22194. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  22195. }
  22196. else {
  22197. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  22198. }
  22199. if (this.forceDepthWrite) {
  22200. engine.setDepthWrite(true);
  22201. }
  22202. engine.draw(true, 0, this.particles.length * 6);
  22203. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  22204. return this.particles.length;
  22205. };
  22206. ParticleSystem.prototype.dispose = function () {
  22207. if (this._vertexBuffer) {
  22208. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  22209. this._vertexBuffer = null;
  22210. }
  22211. if (this._indexBuffer) {
  22212. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  22213. this._indexBuffer = null;
  22214. }
  22215. if (this.particleTexture) {
  22216. this.particleTexture.dispose();
  22217. this.particleTexture = null;
  22218. }
  22219. // Remove from scene
  22220. var index = this._scene.particleSystems.indexOf(this);
  22221. this._scene.particleSystems.splice(index, 1);
  22222. // Callback
  22223. if (this.onDispose) {
  22224. this.onDispose();
  22225. }
  22226. };
  22227. // Clone
  22228. ParticleSystem.prototype.clone = function (name, newEmitter) {
  22229. var result = new ParticleSystem(name, this._capacity, this._scene);
  22230. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  22231. if (newEmitter === undefined) {
  22232. newEmitter = this.emitter;
  22233. }
  22234. result.emitter = newEmitter;
  22235. if (this.particleTexture) {
  22236. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  22237. }
  22238. result.start();
  22239. return result;
  22240. };
  22241. ParticleSystem.prototype.serialize = function () {
  22242. var serializationObject = {};
  22243. serializationObject.name = this.name;
  22244. serializationObject.id = this.id;
  22245. // Emitter
  22246. if (this.emitter.position) {
  22247. serializationObject.emitterId = this.emitter.id;
  22248. }
  22249. else {
  22250. serializationObject.emitter = this.emitter.asArray();
  22251. }
  22252. serializationObject.capacity = this.getCapacity();
  22253. if (this.particleTexture) {
  22254. serializationObject.textureName = this.particleTexture.name;
  22255. }
  22256. // Animations
  22257. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22258. // Particle system
  22259. serializationObject.minAngularSpeed = this.minAngularSpeed;
  22260. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  22261. serializationObject.minSize = this.minSize;
  22262. serializationObject.maxSize = this.maxSize;
  22263. serializationObject.minEmitPower = this.minEmitPower;
  22264. serializationObject.maxEmitPower = this.maxEmitPower;
  22265. serializationObject.minLifeTime = this.minLifeTime;
  22266. serializationObject.maxLifeTime = this.maxLifeTime;
  22267. serializationObject.emitRate = this.emitRate;
  22268. serializationObject.minEmitBox = this.minEmitBox.asArray();
  22269. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  22270. serializationObject.gravity = this.gravity.asArray();
  22271. serializationObject.direction1 = this.direction1.asArray();
  22272. serializationObject.direction2 = this.direction2.asArray();
  22273. serializationObject.color1 = this.color1.asArray();
  22274. serializationObject.color2 = this.color2.asArray();
  22275. serializationObject.colorDead = this.colorDead.asArray();
  22276. serializationObject.updateSpeed = this.updateSpeed;
  22277. serializationObject.targetStopDuration = this.targetStopDuration;
  22278. serializationObject.textureMask = this.textureMask.asArray();
  22279. serializationObject.blendMode = this.blendMode;
  22280. return serializationObject;
  22281. };
  22282. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  22283. var name = parsedParticleSystem.name;
  22284. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene);
  22285. if (parsedParticleSystem.id) {
  22286. particleSystem.id = parsedParticleSystem.id;
  22287. }
  22288. // Texture
  22289. if (parsedParticleSystem.textureName) {
  22290. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  22291. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  22292. }
  22293. // Emitter
  22294. if (parsedParticleSystem.emitterId) {
  22295. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  22296. }
  22297. else {
  22298. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  22299. }
  22300. // Animations
  22301. if (parsedParticleSystem.animations) {
  22302. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  22303. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  22304. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22305. }
  22306. }
  22307. if (parsedParticleSystem.autoAnimate) {
  22308. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  22309. }
  22310. // Particle system
  22311. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  22312. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  22313. particleSystem.minSize = parsedParticleSystem.minSize;
  22314. particleSystem.maxSize = parsedParticleSystem.maxSize;
  22315. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  22316. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  22317. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  22318. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  22319. particleSystem.emitRate = parsedParticleSystem.emitRate;
  22320. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  22321. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  22322. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  22323. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  22324. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  22325. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  22326. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  22327. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  22328. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  22329. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  22330. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  22331. particleSystem.blendMode = parsedParticleSystem.blendMode;
  22332. particleSystem.start();
  22333. return particleSystem;
  22334. };
  22335. // Statics
  22336. ParticleSystem.BLENDMODE_ONEONE = 0;
  22337. ParticleSystem.BLENDMODE_STANDARD = 1;
  22338. return ParticleSystem;
  22339. })();
  22340. BABYLON.ParticleSystem = ParticleSystem;
  22341. })(BABYLON || (BABYLON = {}));
  22342. var BABYLON;
  22343. (function (BABYLON) {
  22344. var AnimationRange = (function () {
  22345. function AnimationRange(name, from, to) {
  22346. this.name = name;
  22347. this.from = from;
  22348. this.to = to;
  22349. }
  22350. return AnimationRange;
  22351. })();
  22352. BABYLON.AnimationRange = AnimationRange;
  22353. /**
  22354. * Composed of a frame, and an action function
  22355. */
  22356. var AnimationEvent = (function () {
  22357. function AnimationEvent(frame, action, onlyOnce) {
  22358. this.frame = frame;
  22359. this.action = action;
  22360. this.onlyOnce = onlyOnce;
  22361. this.isDone = false;
  22362. }
  22363. return AnimationEvent;
  22364. })();
  22365. BABYLON.AnimationEvent = AnimationEvent;
  22366. var PathCursor = (function () {
  22367. function PathCursor(path) {
  22368. this.path = path;
  22369. this._onchange = new Array();
  22370. this.value = 0;
  22371. this.animations = new Array();
  22372. }
  22373. PathCursor.prototype.getPoint = function () {
  22374. var point = this.path.getPointAtLengthPosition(this.value);
  22375. return new BABYLON.Vector3(point.x, 0, point.y);
  22376. };
  22377. PathCursor.prototype.moveAhead = function (step) {
  22378. if (step === void 0) { step = 0.002; }
  22379. this.move(step);
  22380. return this;
  22381. };
  22382. PathCursor.prototype.moveBack = function (step) {
  22383. if (step === void 0) { step = 0.002; }
  22384. this.move(-step);
  22385. return this;
  22386. };
  22387. PathCursor.prototype.move = function (step) {
  22388. if (Math.abs(step) > 1) {
  22389. throw "step size should be less than 1.";
  22390. }
  22391. this.value += step;
  22392. this.ensureLimits();
  22393. this.raiseOnChange();
  22394. return this;
  22395. };
  22396. PathCursor.prototype.ensureLimits = function () {
  22397. while (this.value > 1) {
  22398. this.value -= 1;
  22399. }
  22400. while (this.value < 0) {
  22401. this.value += 1;
  22402. }
  22403. return this;
  22404. };
  22405. // used by animation engine
  22406. PathCursor.prototype.markAsDirty = function (propertyName) {
  22407. this.ensureLimits();
  22408. this.raiseOnChange();
  22409. return this;
  22410. };
  22411. PathCursor.prototype.raiseOnChange = function () {
  22412. var _this = this;
  22413. this._onchange.forEach(function (f) { return f(_this); });
  22414. return this;
  22415. };
  22416. PathCursor.prototype.onchange = function (f) {
  22417. this._onchange.push(f);
  22418. return this;
  22419. };
  22420. return PathCursor;
  22421. })();
  22422. BABYLON.PathCursor = PathCursor;
  22423. var Animation = (function () {
  22424. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  22425. this.name = name;
  22426. this.targetProperty = targetProperty;
  22427. this.framePerSecond = framePerSecond;
  22428. this.dataType = dataType;
  22429. this.loopMode = loopMode;
  22430. this.enableBlending = enableBlending;
  22431. this._offsetsCache = {};
  22432. this._highLimitsCache = {};
  22433. this._stopped = false;
  22434. this._blendingFactor = 0;
  22435. // The set of event that will be linked to this animation
  22436. this._events = new Array();
  22437. this.allowMatricesInterpolation = false;
  22438. this.blendingSpeed = 0.01;
  22439. this._ranges = {};
  22440. this.targetPropertyPath = targetProperty.split(".");
  22441. this.dataType = dataType;
  22442. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  22443. }
  22444. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  22445. var dataType = undefined;
  22446. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  22447. dataType = Animation.ANIMATIONTYPE_FLOAT;
  22448. }
  22449. else if (from instanceof BABYLON.Quaternion) {
  22450. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  22451. }
  22452. else if (from instanceof BABYLON.Vector3) {
  22453. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  22454. }
  22455. else if (from instanceof BABYLON.Vector2) {
  22456. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  22457. }
  22458. else if (from instanceof BABYLON.Color3) {
  22459. dataType = Animation.ANIMATIONTYPE_COLOR3;
  22460. }
  22461. if (dataType == undefined) {
  22462. return null;
  22463. }
  22464. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  22465. var keys = [];
  22466. keys.push({ frame: 0, value: from });
  22467. keys.push({ frame: totalFrame, value: to });
  22468. animation.setKeys(keys);
  22469. if (easingFunction !== undefined) {
  22470. animation.setEasingFunction(easingFunction);
  22471. }
  22472. return animation;
  22473. };
  22474. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  22475. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  22476. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  22477. };
  22478. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  22479. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  22480. node.animations.push(animation);
  22481. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  22482. };
  22483. // Methods
  22484. /**
  22485. * Add an event to this animation.
  22486. */
  22487. Animation.prototype.addEvent = function (event) {
  22488. this._events.push(event);
  22489. };
  22490. /**
  22491. * Remove all events found at the given frame
  22492. * @param frame
  22493. */
  22494. Animation.prototype.removeEvents = function (frame) {
  22495. for (var index = 0; index < this._events.length; index++) {
  22496. if (this._events[index].frame === frame) {
  22497. this._events.splice(index, 1);
  22498. index--;
  22499. }
  22500. }
  22501. };
  22502. Animation.prototype.createRange = function (name, from, to) {
  22503. // check name not already in use; could happen for bones after serialized
  22504. if (!this._ranges[name]) {
  22505. this._ranges[name] = new AnimationRange(name, from, to);
  22506. }
  22507. };
  22508. Animation.prototype.deleteRange = function (name, deleteFrames) {
  22509. if (deleteFrames === void 0) { deleteFrames = true; }
  22510. if (this._ranges[name]) {
  22511. if (deleteFrames) {
  22512. var from = this._ranges[name].from;
  22513. var to = this._ranges[name].to;
  22514. // this loop MUST go high to low for multiple splices to work
  22515. for (var key = this._keys.length - 1; key >= 0; key--) {
  22516. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  22517. this._keys.splice(key, 1);
  22518. }
  22519. }
  22520. }
  22521. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  22522. }
  22523. };
  22524. Animation.prototype.getRange = function (name) {
  22525. return this._ranges[name];
  22526. };
  22527. Animation.prototype.reset = function () {
  22528. this._offsetsCache = {};
  22529. this._highLimitsCache = {};
  22530. this.currentFrame = 0;
  22531. this._blendingFactor = 0;
  22532. this._originalBlendValue = null;
  22533. };
  22534. Animation.prototype.isStopped = function () {
  22535. return this._stopped;
  22536. };
  22537. Animation.prototype.getKeys = function () {
  22538. return this._keys;
  22539. };
  22540. Animation.prototype.getHighestFrame = function () {
  22541. var ret = 0;
  22542. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  22543. if (ret < this._keys[key].frame) {
  22544. ret = this._keys[key].frame;
  22545. }
  22546. }
  22547. return ret;
  22548. };
  22549. Animation.prototype.getEasingFunction = function () {
  22550. return this._easingFunction;
  22551. };
  22552. Animation.prototype.setEasingFunction = function (easingFunction) {
  22553. this._easingFunction = easingFunction;
  22554. };
  22555. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  22556. return startValue + (endValue - startValue) * gradient;
  22557. };
  22558. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  22559. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  22560. };
  22561. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  22562. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  22563. };
  22564. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  22565. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  22566. };
  22567. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  22568. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  22569. };
  22570. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  22571. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  22572. };
  22573. Animation.prototype.clone = function () {
  22574. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  22575. if (this._keys) {
  22576. clone.setKeys(this._keys);
  22577. }
  22578. return clone;
  22579. };
  22580. Animation.prototype.setKeys = function (values) {
  22581. this._keys = values.slice(0);
  22582. this._offsetsCache = {};
  22583. this._highLimitsCache = {};
  22584. };
  22585. Animation.prototype._getKeyValue = function (value) {
  22586. if (typeof value === "function") {
  22587. return value();
  22588. }
  22589. return value;
  22590. };
  22591. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  22592. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  22593. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  22594. }
  22595. this.currentFrame = currentFrame;
  22596. // Try to get a hash to find the right key
  22597. 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));
  22598. if (this._keys[startKey].frame >= currentFrame) {
  22599. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  22600. startKey--;
  22601. }
  22602. }
  22603. for (var key = startKey; key < this._keys.length; key++) {
  22604. if (this._keys[key + 1].frame >= currentFrame) {
  22605. var startValue = this._getKeyValue(this._keys[key].value);
  22606. var endValue = this._getKeyValue(this._keys[key + 1].value);
  22607. // gradient : percent of currentFrame between the frame inf and the frame sup
  22608. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  22609. // check for easingFunction and correction of gradient
  22610. if (this._easingFunction != null) {
  22611. gradient = this._easingFunction.ease(gradient);
  22612. }
  22613. switch (this.dataType) {
  22614. // Float
  22615. case Animation.ANIMATIONTYPE_FLOAT:
  22616. switch (loopMode) {
  22617. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22618. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22619. return this.floatInterpolateFunction(startValue, endValue, gradient);
  22620. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22621. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  22622. }
  22623. break;
  22624. // Quaternion
  22625. case Animation.ANIMATIONTYPE_QUATERNION:
  22626. var quaternion = null;
  22627. switch (loopMode) {
  22628. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22629. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22630. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  22631. break;
  22632. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22633. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  22634. break;
  22635. }
  22636. return quaternion;
  22637. // Vector3
  22638. case Animation.ANIMATIONTYPE_VECTOR3:
  22639. switch (loopMode) {
  22640. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22641. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22642. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  22643. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22644. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  22645. }
  22646. // Vector2
  22647. case Animation.ANIMATIONTYPE_VECTOR2:
  22648. switch (loopMode) {
  22649. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22650. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22651. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  22652. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22653. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  22654. }
  22655. // Color3
  22656. case Animation.ANIMATIONTYPE_COLOR3:
  22657. switch (loopMode) {
  22658. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22659. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22660. return this.color3InterpolateFunction(startValue, endValue, gradient);
  22661. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22662. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  22663. }
  22664. // Matrix
  22665. case Animation.ANIMATIONTYPE_MATRIX:
  22666. switch (loopMode) {
  22667. case Animation.ANIMATIONLOOPMODE_CYCLE:
  22668. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  22669. if (this.allowMatricesInterpolation) {
  22670. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  22671. }
  22672. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  22673. return startValue;
  22674. }
  22675. default:
  22676. break;
  22677. }
  22678. break;
  22679. }
  22680. }
  22681. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  22682. };
  22683. Animation.prototype.setValue = function (currentValue, blend) {
  22684. if (blend === void 0) { blend = false; }
  22685. // Set value
  22686. var path;
  22687. var destination;
  22688. if (this.targetPropertyPath.length > 1) {
  22689. var property = this._target[this.targetPropertyPath[0]];
  22690. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  22691. property = property[this.targetPropertyPath[index]];
  22692. }
  22693. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  22694. destination = property;
  22695. }
  22696. else {
  22697. path = this.targetPropertyPath[0];
  22698. destination = this._target;
  22699. }
  22700. // Blending
  22701. if (this.enableBlending && this._blendingFactor <= 1.0) {
  22702. if (!this._originalBlendValue) {
  22703. this._originalBlendValue = destination[path];
  22704. }
  22705. if (this._originalBlendValue.prototype) {
  22706. if (this._originalBlendValue.prototype.Lerp) {
  22707. destination[path] = this._originalBlendValue.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  22708. }
  22709. else {
  22710. destination[path] = currentValue;
  22711. }
  22712. }
  22713. else {
  22714. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  22715. }
  22716. this._blendingFactor += this.blendingSpeed;
  22717. }
  22718. else {
  22719. destination[path] = currentValue;
  22720. }
  22721. if (this._target.markAsDirty) {
  22722. this._target.markAsDirty(this.targetProperty);
  22723. }
  22724. };
  22725. Animation.prototype.goToFrame = function (frame) {
  22726. if (frame < this._keys[0].frame) {
  22727. frame = this._keys[0].frame;
  22728. }
  22729. else if (frame > this._keys[this._keys.length - 1].frame) {
  22730. frame = this._keys[this._keys.length - 1].frame;
  22731. }
  22732. var currentValue = this._interpolate(frame, 0, this.loopMode);
  22733. this.setValue(currentValue);
  22734. };
  22735. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  22736. if (blend === void 0) { blend = false; }
  22737. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  22738. this._stopped = true;
  22739. return false;
  22740. }
  22741. var returnValue = true;
  22742. // Adding a start key at frame 0 if missing
  22743. if (this._keys[0].frame !== 0) {
  22744. var newKey = { frame: 0, value: this._keys[0].value };
  22745. this._keys.splice(0, 0, newKey);
  22746. }
  22747. // Check limits
  22748. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  22749. from = this._keys[0].frame;
  22750. }
  22751. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  22752. to = this._keys[this._keys.length - 1].frame;
  22753. }
  22754. // Compute ratio
  22755. var range = to - from;
  22756. var offsetValue;
  22757. // ratio represents the frame delta between from and to
  22758. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  22759. var highLimitValue = 0;
  22760. if (ratio > range && !loop) {
  22761. returnValue = false;
  22762. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  22763. }
  22764. else {
  22765. // Get max value if required
  22766. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  22767. var keyOffset = to.toString() + from.toString();
  22768. if (!this._offsetsCache[keyOffset]) {
  22769. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  22770. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  22771. switch (this.dataType) {
  22772. // Float
  22773. case Animation.ANIMATIONTYPE_FLOAT:
  22774. this._offsetsCache[keyOffset] = toValue - fromValue;
  22775. break;
  22776. // Quaternion
  22777. case Animation.ANIMATIONTYPE_QUATERNION:
  22778. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  22779. break;
  22780. // Vector3
  22781. case Animation.ANIMATIONTYPE_VECTOR3:
  22782. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  22783. // Vector2
  22784. case Animation.ANIMATIONTYPE_VECTOR2:
  22785. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  22786. // Color3
  22787. case Animation.ANIMATIONTYPE_COLOR3:
  22788. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  22789. default:
  22790. break;
  22791. }
  22792. this._highLimitsCache[keyOffset] = toValue;
  22793. }
  22794. highLimitValue = this._highLimitsCache[keyOffset];
  22795. offsetValue = this._offsetsCache[keyOffset];
  22796. }
  22797. }
  22798. if (offsetValue === undefined) {
  22799. switch (this.dataType) {
  22800. // Float
  22801. case Animation.ANIMATIONTYPE_FLOAT:
  22802. offsetValue = 0;
  22803. break;
  22804. // Quaternion
  22805. case Animation.ANIMATIONTYPE_QUATERNION:
  22806. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  22807. break;
  22808. // Vector3
  22809. case Animation.ANIMATIONTYPE_VECTOR3:
  22810. offsetValue = BABYLON.Vector3.Zero();
  22811. break;
  22812. // Vector2
  22813. case Animation.ANIMATIONTYPE_VECTOR2:
  22814. offsetValue = BABYLON.Vector2.Zero();
  22815. break;
  22816. // Color3
  22817. case Animation.ANIMATIONTYPE_COLOR3:
  22818. offsetValue = BABYLON.Color3.Black();
  22819. }
  22820. }
  22821. // Compute value
  22822. var repeatCount = (ratio / range) >> 0;
  22823. var currentFrame = returnValue ? from + ratio % range : to;
  22824. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  22825. // Set value
  22826. this.setValue(currentValue);
  22827. // Check events
  22828. for (var index = 0; index < this._events.length; index++) {
  22829. if (currentFrame >= this._events[index].frame) {
  22830. var event = this._events[index];
  22831. if (!event.isDone) {
  22832. // If event should be done only once, remove it.
  22833. if (event.onlyOnce) {
  22834. this._events.splice(index, 1);
  22835. index--;
  22836. }
  22837. event.isDone = true;
  22838. event.action();
  22839. } // Don't do anything if the event has already be done.
  22840. }
  22841. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  22842. // reset event, the animation is looping
  22843. this._events[index].isDone = false;
  22844. }
  22845. }
  22846. if (!returnValue) {
  22847. this._stopped = true;
  22848. }
  22849. return returnValue;
  22850. };
  22851. Animation.prototype.serialize = function () {
  22852. var serializationObject = {};
  22853. serializationObject.name = this.name;
  22854. serializationObject.property = this.targetProperty;
  22855. serializationObject.framePerSecond = this.framePerSecond;
  22856. serializationObject.dataType = this.dataType;
  22857. serializationObject.loopBehavior = this.loopMode;
  22858. var dataType = this.dataType;
  22859. serializationObject.keys = [];
  22860. var keys = this.getKeys();
  22861. for (var index = 0; index < keys.length; index++) {
  22862. var animationKey = keys[index];
  22863. var key = {};
  22864. key.frame = animationKey.frame;
  22865. switch (dataType) {
  22866. case Animation.ANIMATIONTYPE_FLOAT:
  22867. key.values = [animationKey.value];
  22868. break;
  22869. case Animation.ANIMATIONTYPE_QUATERNION:
  22870. case Animation.ANIMATIONTYPE_MATRIX:
  22871. case Animation.ANIMATIONTYPE_VECTOR3:
  22872. case Animation.ANIMATIONTYPE_COLOR3:
  22873. key.values = animationKey.value.asArray();
  22874. break;
  22875. }
  22876. serializationObject.keys.push(key);
  22877. }
  22878. serializationObject.ranges = [];
  22879. for (var name in this._ranges) {
  22880. var range = {};
  22881. range.name = name;
  22882. range.from = this._ranges[name].from;
  22883. range.to = this._ranges[name].to;
  22884. serializationObject.ranges.push(range);
  22885. }
  22886. return serializationObject;
  22887. };
  22888. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  22889. get: function () {
  22890. return Animation._ANIMATIONTYPE_FLOAT;
  22891. },
  22892. enumerable: true,
  22893. configurable: true
  22894. });
  22895. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  22896. get: function () {
  22897. return Animation._ANIMATIONTYPE_VECTOR3;
  22898. },
  22899. enumerable: true,
  22900. configurable: true
  22901. });
  22902. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  22903. get: function () {
  22904. return Animation._ANIMATIONTYPE_VECTOR2;
  22905. },
  22906. enumerable: true,
  22907. configurable: true
  22908. });
  22909. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  22910. get: function () {
  22911. return Animation._ANIMATIONTYPE_QUATERNION;
  22912. },
  22913. enumerable: true,
  22914. configurable: true
  22915. });
  22916. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  22917. get: function () {
  22918. return Animation._ANIMATIONTYPE_MATRIX;
  22919. },
  22920. enumerable: true,
  22921. configurable: true
  22922. });
  22923. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  22924. get: function () {
  22925. return Animation._ANIMATIONTYPE_COLOR3;
  22926. },
  22927. enumerable: true,
  22928. configurable: true
  22929. });
  22930. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  22931. get: function () {
  22932. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  22933. },
  22934. enumerable: true,
  22935. configurable: true
  22936. });
  22937. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  22938. get: function () {
  22939. return Animation._ANIMATIONLOOPMODE_CYCLE;
  22940. },
  22941. enumerable: true,
  22942. configurable: true
  22943. });
  22944. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  22945. get: function () {
  22946. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  22947. },
  22948. enumerable: true,
  22949. configurable: true
  22950. });
  22951. Animation.Parse = function (parsedAnimation) {
  22952. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  22953. var dataType = parsedAnimation.dataType;
  22954. var keys = [];
  22955. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  22956. var key = parsedAnimation.keys[index];
  22957. var data;
  22958. switch (dataType) {
  22959. case Animation.ANIMATIONTYPE_FLOAT:
  22960. data = key.values[0];
  22961. break;
  22962. case Animation.ANIMATIONTYPE_QUATERNION:
  22963. data = BABYLON.Quaternion.FromArray(key.values);
  22964. break;
  22965. case Animation.ANIMATIONTYPE_MATRIX:
  22966. data = BABYLON.Matrix.FromArray(key.values);
  22967. break;
  22968. case Animation.ANIMATIONTYPE_COLOR3:
  22969. data = BABYLON.Color3.FromArray(key.values);
  22970. break;
  22971. case Animation.ANIMATIONTYPE_VECTOR3:
  22972. default:
  22973. data = BABYLON.Vector3.FromArray(key.values);
  22974. break;
  22975. }
  22976. keys.push({
  22977. frame: key.frame,
  22978. value: data
  22979. });
  22980. }
  22981. animation.setKeys(keys);
  22982. if (parsedAnimation.ranges) {
  22983. for (var index = 0; index < parsedAnimation.ranges.length; index++) {
  22984. data = parsedAnimation.ranges[index];
  22985. animation.createRange(data.name, data.from, data.to);
  22986. }
  22987. }
  22988. return animation;
  22989. };
  22990. Animation.AppendSerializedAnimations = function (source, destination) {
  22991. if (source.animations) {
  22992. destination.animations = [];
  22993. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  22994. var animation = source.animations[animationIndex];
  22995. destination.animations.push(animation.serialize());
  22996. }
  22997. }
  22998. };
  22999. // Statics
  23000. Animation._ANIMATIONTYPE_FLOAT = 0;
  23001. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  23002. Animation._ANIMATIONTYPE_QUATERNION = 2;
  23003. Animation._ANIMATIONTYPE_MATRIX = 3;
  23004. Animation._ANIMATIONTYPE_COLOR3 = 4;
  23005. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  23006. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  23007. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  23008. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  23009. return Animation;
  23010. })();
  23011. BABYLON.Animation = Animation;
  23012. })(BABYLON || (BABYLON = {}));
  23013. var BABYLON;
  23014. (function (BABYLON) {
  23015. var Animatable = (function () {
  23016. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  23017. if (fromFrame === void 0) { fromFrame = 0; }
  23018. if (toFrame === void 0) { toFrame = 100; }
  23019. if (loopAnimation === void 0) { loopAnimation = false; }
  23020. if (speedRatio === void 0) { speedRatio = 1.0; }
  23021. this.target = target;
  23022. this.fromFrame = fromFrame;
  23023. this.toFrame = toFrame;
  23024. this.loopAnimation = loopAnimation;
  23025. this.speedRatio = speedRatio;
  23026. this.onAnimationEnd = onAnimationEnd;
  23027. this._animations = new Array();
  23028. this._paused = false;
  23029. this.animationStarted = false;
  23030. if (animations) {
  23031. this.appendAnimations(target, animations);
  23032. }
  23033. this._scene = scene;
  23034. scene._activeAnimatables.push(this);
  23035. }
  23036. // Methods
  23037. Animatable.prototype.getAnimations = function () {
  23038. return this._animations;
  23039. };
  23040. Animatable.prototype.appendAnimations = function (target, animations) {
  23041. for (var index = 0; index < animations.length; index++) {
  23042. var animation = animations[index];
  23043. animation._target = target;
  23044. this._animations.push(animation);
  23045. }
  23046. };
  23047. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  23048. var animations = this._animations;
  23049. for (var index = 0; index < animations.length; index++) {
  23050. if (animations[index].targetProperty === property) {
  23051. return animations[index];
  23052. }
  23053. }
  23054. return null;
  23055. };
  23056. Animatable.prototype.reset = function () {
  23057. var animations = this._animations;
  23058. for (var index = 0; index < animations.length; index++) {
  23059. animations[index].reset();
  23060. }
  23061. this._localDelayOffset = null;
  23062. this._pausedDelay = null;
  23063. };
  23064. Animatable.prototype.enableBlending = function (blendingSpeed) {
  23065. var animations = this._animations;
  23066. for (var index = 0; index < animations.length; index++) {
  23067. animations[index].enableBlending = true;
  23068. animations[index].blendingSpeed = blendingSpeed;
  23069. }
  23070. };
  23071. Animatable.prototype.disableBlending = function () {
  23072. var animations = this._animations;
  23073. for (var index = 0; index < animations.length; index++) {
  23074. animations[index].enableBlending = false;
  23075. }
  23076. };
  23077. Animatable.prototype.goToFrame = function (frame) {
  23078. var animations = this._animations;
  23079. for (var index = 0; index < animations.length; index++) {
  23080. animations[index].goToFrame(frame);
  23081. }
  23082. };
  23083. Animatable.prototype.pause = function () {
  23084. if (this._paused) {
  23085. return;
  23086. }
  23087. this._paused = true;
  23088. };
  23089. Animatable.prototype.restart = function () {
  23090. this._paused = false;
  23091. };
  23092. Animatable.prototype.stop = function () {
  23093. var index = this._scene._activeAnimatables.indexOf(this);
  23094. if (index > -1) {
  23095. this._scene._activeAnimatables.splice(index, 1);
  23096. var animations = this._animations;
  23097. for (var index = 0; index < animations.length; index++) {
  23098. animations[index].reset();
  23099. }
  23100. if (this.onAnimationEnd) {
  23101. this.onAnimationEnd();
  23102. }
  23103. }
  23104. };
  23105. Animatable.prototype._animate = function (delay) {
  23106. if (this._paused) {
  23107. this.animationStarted = false;
  23108. if (!this._pausedDelay) {
  23109. this._pausedDelay = delay;
  23110. }
  23111. return true;
  23112. }
  23113. if (!this._localDelayOffset) {
  23114. this._localDelayOffset = delay;
  23115. }
  23116. else if (this._pausedDelay) {
  23117. this._localDelayOffset += delay - this._pausedDelay;
  23118. this._pausedDelay = null;
  23119. }
  23120. // Animating
  23121. var running = false;
  23122. var animations = this._animations;
  23123. var index;
  23124. for (index = 0; index < animations.length; index++) {
  23125. var animation = animations[index];
  23126. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  23127. running = running || isRunning;
  23128. }
  23129. this.animationStarted = running;
  23130. if (!running) {
  23131. // Remove from active animatables
  23132. index = this._scene._activeAnimatables.indexOf(this);
  23133. this._scene._activeAnimatables.splice(index, 1);
  23134. }
  23135. if (!running && this.onAnimationEnd) {
  23136. this.onAnimationEnd();
  23137. this.onAnimationEnd = null;
  23138. }
  23139. return running;
  23140. };
  23141. return Animatable;
  23142. })();
  23143. BABYLON.Animatable = Animatable;
  23144. })(BABYLON || (BABYLON = {}));
  23145. var BABYLON;
  23146. (function (BABYLON) {
  23147. var EasingFunction = (function () {
  23148. function EasingFunction() {
  23149. // Properties
  23150. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  23151. }
  23152. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  23153. get: function () {
  23154. return EasingFunction._EASINGMODE_EASEIN;
  23155. },
  23156. enumerable: true,
  23157. configurable: true
  23158. });
  23159. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  23160. get: function () {
  23161. return EasingFunction._EASINGMODE_EASEOUT;
  23162. },
  23163. enumerable: true,
  23164. configurable: true
  23165. });
  23166. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  23167. get: function () {
  23168. return EasingFunction._EASINGMODE_EASEINOUT;
  23169. },
  23170. enumerable: true,
  23171. configurable: true
  23172. });
  23173. EasingFunction.prototype.setEasingMode = function (easingMode) {
  23174. var n = Math.min(Math.max(easingMode, 0), 2);
  23175. this._easingMode = n;
  23176. };
  23177. EasingFunction.prototype.getEasingMode = function () {
  23178. return this._easingMode;
  23179. };
  23180. EasingFunction.prototype.easeInCore = function (gradient) {
  23181. throw new Error('You must implement this method');
  23182. };
  23183. EasingFunction.prototype.ease = function (gradient) {
  23184. switch (this._easingMode) {
  23185. case EasingFunction.EASINGMODE_EASEIN:
  23186. return this.easeInCore(gradient);
  23187. case EasingFunction.EASINGMODE_EASEOUT:
  23188. return (1 - this.easeInCore(1 - gradient));
  23189. }
  23190. if (gradient >= 0.5) {
  23191. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  23192. }
  23193. return (this.easeInCore(gradient * 2) * 0.5);
  23194. };
  23195. //Statics
  23196. EasingFunction._EASINGMODE_EASEIN = 0;
  23197. EasingFunction._EASINGMODE_EASEOUT = 1;
  23198. EasingFunction._EASINGMODE_EASEINOUT = 2;
  23199. return EasingFunction;
  23200. })();
  23201. BABYLON.EasingFunction = EasingFunction;
  23202. var CircleEase = (function (_super) {
  23203. __extends(CircleEase, _super);
  23204. function CircleEase() {
  23205. _super.apply(this, arguments);
  23206. }
  23207. CircleEase.prototype.easeInCore = function (gradient) {
  23208. gradient = Math.max(0, Math.min(1, gradient));
  23209. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  23210. };
  23211. return CircleEase;
  23212. })(EasingFunction);
  23213. BABYLON.CircleEase = CircleEase;
  23214. var BackEase = (function (_super) {
  23215. __extends(BackEase, _super);
  23216. function BackEase(amplitude) {
  23217. if (amplitude === void 0) { amplitude = 1; }
  23218. _super.call(this);
  23219. this.amplitude = amplitude;
  23220. }
  23221. BackEase.prototype.easeInCore = function (gradient) {
  23222. var num = Math.max(0, this.amplitude);
  23223. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  23224. };
  23225. return BackEase;
  23226. })(EasingFunction);
  23227. BABYLON.BackEase = BackEase;
  23228. var BounceEase = (function (_super) {
  23229. __extends(BounceEase, _super);
  23230. function BounceEase(bounces, bounciness) {
  23231. if (bounces === void 0) { bounces = 3; }
  23232. if (bounciness === void 0) { bounciness = 2; }
  23233. _super.call(this);
  23234. this.bounces = bounces;
  23235. this.bounciness = bounciness;
  23236. }
  23237. BounceEase.prototype.easeInCore = function (gradient) {
  23238. var y = Math.max(0.0, this.bounces);
  23239. var bounciness = this.bounciness;
  23240. if (bounciness <= 1.0) {
  23241. bounciness = 1.001;
  23242. }
  23243. var num9 = Math.pow(bounciness, y);
  23244. var num5 = 1.0 - bounciness;
  23245. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  23246. var num15 = gradient * num4;
  23247. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  23248. var num3 = Math.floor(num65);
  23249. var num13 = num3 + 1.0;
  23250. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  23251. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  23252. var num7 = (num8 + num12) * 0.5;
  23253. var num6 = gradient - num7;
  23254. var num2 = num7 - num8;
  23255. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  23256. };
  23257. return BounceEase;
  23258. })(EasingFunction);
  23259. BABYLON.BounceEase = BounceEase;
  23260. var CubicEase = (function (_super) {
  23261. __extends(CubicEase, _super);
  23262. function CubicEase() {
  23263. _super.apply(this, arguments);
  23264. }
  23265. CubicEase.prototype.easeInCore = function (gradient) {
  23266. return (gradient * gradient * gradient);
  23267. };
  23268. return CubicEase;
  23269. })(EasingFunction);
  23270. BABYLON.CubicEase = CubicEase;
  23271. var ElasticEase = (function (_super) {
  23272. __extends(ElasticEase, _super);
  23273. function ElasticEase(oscillations, springiness) {
  23274. if (oscillations === void 0) { oscillations = 3; }
  23275. if (springiness === void 0) { springiness = 3; }
  23276. _super.call(this);
  23277. this.oscillations = oscillations;
  23278. this.springiness = springiness;
  23279. }
  23280. ElasticEase.prototype.easeInCore = function (gradient) {
  23281. var num2;
  23282. var num3 = Math.max(0.0, this.oscillations);
  23283. var num = Math.max(0.0, this.springiness);
  23284. if (num == 0) {
  23285. num2 = gradient;
  23286. }
  23287. else {
  23288. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  23289. }
  23290. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  23291. };
  23292. return ElasticEase;
  23293. })(EasingFunction);
  23294. BABYLON.ElasticEase = ElasticEase;
  23295. var ExponentialEase = (function (_super) {
  23296. __extends(ExponentialEase, _super);
  23297. function ExponentialEase(exponent) {
  23298. if (exponent === void 0) { exponent = 2; }
  23299. _super.call(this);
  23300. this.exponent = exponent;
  23301. }
  23302. ExponentialEase.prototype.easeInCore = function (gradient) {
  23303. if (this.exponent <= 0) {
  23304. return gradient;
  23305. }
  23306. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  23307. };
  23308. return ExponentialEase;
  23309. })(EasingFunction);
  23310. BABYLON.ExponentialEase = ExponentialEase;
  23311. var PowerEase = (function (_super) {
  23312. __extends(PowerEase, _super);
  23313. function PowerEase(power) {
  23314. if (power === void 0) { power = 2; }
  23315. _super.call(this);
  23316. this.power = power;
  23317. }
  23318. PowerEase.prototype.easeInCore = function (gradient) {
  23319. var y = Math.max(0.0, this.power);
  23320. return Math.pow(gradient, y);
  23321. };
  23322. return PowerEase;
  23323. })(EasingFunction);
  23324. BABYLON.PowerEase = PowerEase;
  23325. var QuadraticEase = (function (_super) {
  23326. __extends(QuadraticEase, _super);
  23327. function QuadraticEase() {
  23328. _super.apply(this, arguments);
  23329. }
  23330. QuadraticEase.prototype.easeInCore = function (gradient) {
  23331. return (gradient * gradient);
  23332. };
  23333. return QuadraticEase;
  23334. })(EasingFunction);
  23335. BABYLON.QuadraticEase = QuadraticEase;
  23336. var QuarticEase = (function (_super) {
  23337. __extends(QuarticEase, _super);
  23338. function QuarticEase() {
  23339. _super.apply(this, arguments);
  23340. }
  23341. QuarticEase.prototype.easeInCore = function (gradient) {
  23342. return (gradient * gradient * gradient * gradient);
  23343. };
  23344. return QuarticEase;
  23345. })(EasingFunction);
  23346. BABYLON.QuarticEase = QuarticEase;
  23347. var QuinticEase = (function (_super) {
  23348. __extends(QuinticEase, _super);
  23349. function QuinticEase() {
  23350. _super.apply(this, arguments);
  23351. }
  23352. QuinticEase.prototype.easeInCore = function (gradient) {
  23353. return (gradient * gradient * gradient * gradient * gradient);
  23354. };
  23355. return QuinticEase;
  23356. })(EasingFunction);
  23357. BABYLON.QuinticEase = QuinticEase;
  23358. var SineEase = (function (_super) {
  23359. __extends(SineEase, _super);
  23360. function SineEase() {
  23361. _super.apply(this, arguments);
  23362. }
  23363. SineEase.prototype.easeInCore = function (gradient) {
  23364. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  23365. };
  23366. return SineEase;
  23367. })(EasingFunction);
  23368. BABYLON.SineEase = SineEase;
  23369. var BezierCurveEase = (function (_super) {
  23370. __extends(BezierCurveEase, _super);
  23371. function BezierCurveEase(x1, y1, x2, y2) {
  23372. if (x1 === void 0) { x1 = 0; }
  23373. if (y1 === void 0) { y1 = 0; }
  23374. if (x2 === void 0) { x2 = 1; }
  23375. if (y2 === void 0) { y2 = 1; }
  23376. _super.call(this);
  23377. this.x1 = x1;
  23378. this.y1 = y1;
  23379. this.x2 = x2;
  23380. this.y2 = y2;
  23381. }
  23382. BezierCurveEase.prototype.easeInCore = function (gradient) {
  23383. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  23384. };
  23385. return BezierCurveEase;
  23386. })(EasingFunction);
  23387. BABYLON.BezierCurveEase = BezierCurveEase;
  23388. })(BABYLON || (BABYLON = {}));
  23389. var BABYLON;
  23390. (function (BABYLON) {
  23391. var Bone = (function (_super) {
  23392. __extends(Bone, _super);
  23393. function Bone(name, skeleton, parentBone, matrix, restPose) {
  23394. _super.call(this, name, skeleton.getScene());
  23395. this.name = name;
  23396. this.children = new Array();
  23397. this.animations = new Array();
  23398. this._worldTransform = new BABYLON.Matrix();
  23399. this._absoluteTransform = new BABYLON.Matrix();
  23400. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  23401. this._skeleton = skeleton;
  23402. this._matrix = matrix;
  23403. this._baseMatrix = matrix;
  23404. this._restPose = restPose ? restPose : matrix.clone();
  23405. skeleton.bones.push(this);
  23406. if (parentBone) {
  23407. this._parent = parentBone;
  23408. parentBone.children.push(this);
  23409. }
  23410. else {
  23411. this._parent = null;
  23412. }
  23413. this._updateDifferenceMatrix();
  23414. }
  23415. // Members
  23416. Bone.prototype.getParent = function () {
  23417. return this._parent;
  23418. };
  23419. Bone.prototype.getLocalMatrix = function () {
  23420. return this._matrix;
  23421. };
  23422. Bone.prototype.getBaseMatrix = function () {
  23423. return this._baseMatrix;
  23424. };
  23425. Bone.prototype.getRestPose = function () {
  23426. return this._restPose;
  23427. };
  23428. Bone.prototype.returnToRest = function () {
  23429. this.updateMatrix(this._restPose.clone());
  23430. };
  23431. Bone.prototype.getWorldMatrix = function () {
  23432. return this._worldTransform;
  23433. };
  23434. Bone.prototype.getInvertedAbsoluteTransform = function () {
  23435. return this._invertedAbsoluteTransform;
  23436. };
  23437. Bone.prototype.getAbsoluteTransform = function () {
  23438. return this._absoluteTransform;
  23439. };
  23440. // Methods
  23441. Bone.prototype.updateMatrix = function (matrix) {
  23442. this._baseMatrix = matrix.clone();
  23443. this._matrix = matrix.clone();
  23444. this._skeleton._markAsDirty();
  23445. this._updateDifferenceMatrix();
  23446. };
  23447. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  23448. if (!rootMatrix) {
  23449. rootMatrix = this._baseMatrix;
  23450. }
  23451. if (this._parent) {
  23452. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  23453. }
  23454. else {
  23455. this._absoluteTransform.copyFrom(rootMatrix);
  23456. }
  23457. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  23458. for (var index = 0; index < this.children.length; index++) {
  23459. this.children[index]._updateDifferenceMatrix();
  23460. }
  23461. };
  23462. Bone.prototype.markAsDirty = function () {
  23463. this._currentRenderId++;
  23464. this._skeleton._markAsDirty();
  23465. };
  23466. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired) {
  23467. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  23468. // all animation may be coming from a library skeleton, so may need to create animation
  23469. if (this.animations.length === 0) {
  23470. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  23471. this.animations[0].setKeys([{}]);
  23472. }
  23473. // get animation info / verify there is such a range from the source bone
  23474. var sourceRange = source.animations[0].getRange(rangeName);
  23475. if (!sourceRange) {
  23476. return false;
  23477. }
  23478. var from = sourceRange.from;
  23479. var to = sourceRange.to;
  23480. var sourceKeys = source.animations[0].getKeys();
  23481. // rescaling prep
  23482. var sourceBoneLength = source.length;
  23483. var scalingReqd = rescaleAsRequired && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  23484. var ratio = scalingReqd ? this.length / sourceBoneLength : null;
  23485. var destKeys = this.animations[0].getKeys();
  23486. // loop vars declaration / initialization
  23487. var orig;
  23488. var origScale = scalingReqd ? BABYLON.Vector3.Zero() : null;
  23489. var origRotation = scalingReqd ? new BABYLON.Quaternion() : null;
  23490. var origTranslation = scalingReqd ? BABYLON.Vector3.Zero() : null;
  23491. var mat;
  23492. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  23493. orig = sourceKeys[key];
  23494. if (orig.frame >= from && orig.frame <= to) {
  23495. if (scalingReqd) {
  23496. orig.value.decompose(origScale, origRotation, origTranslation);
  23497. origTranslation.scaleInPlace(ratio);
  23498. mat = BABYLON.Matrix.Compose(origScale, origRotation, origTranslation);
  23499. }
  23500. else {
  23501. mat = orig.value;
  23502. }
  23503. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  23504. }
  23505. }
  23506. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  23507. return true;
  23508. };
  23509. return Bone;
  23510. })(BABYLON.Node);
  23511. BABYLON.Bone = Bone;
  23512. })(BABYLON || (BABYLON = {}));
  23513. var BABYLON;
  23514. (function (BABYLON) {
  23515. var Skeleton = (function () {
  23516. function Skeleton(name, id, scene) {
  23517. this.name = name;
  23518. this.id = id;
  23519. this.bones = new Array();
  23520. this.needInitialSkinMatrix = false;
  23521. this._isDirty = true;
  23522. this._meshesWithPoseMatrix = new Array();
  23523. this._identity = BABYLON.Matrix.Identity();
  23524. this._ranges = {};
  23525. this.bones = [];
  23526. this._scene = scene;
  23527. scene.skeletons.push(this);
  23528. this.prepare();
  23529. //make sure it will recalculate the matrix next time prepare is called.
  23530. this._isDirty = true;
  23531. }
  23532. // Members
  23533. Skeleton.prototype.getTransformMatrices = function (mesh) {
  23534. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  23535. return mesh._bonesTransformMatrices;
  23536. }
  23537. return this._transformMatrices;
  23538. };
  23539. Skeleton.prototype.getScene = function () {
  23540. return this._scene;
  23541. };
  23542. // Methods
  23543. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  23544. // check name not already in use
  23545. if (!this._ranges[name]) {
  23546. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  23547. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  23548. if (this.bones[i].animations[0]) {
  23549. this.bones[i].animations[0].createRange(name, from, to);
  23550. }
  23551. }
  23552. }
  23553. };
  23554. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  23555. if (deleteFrames === void 0) { deleteFrames = true; }
  23556. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  23557. if (this.bones[i].animations[0]) {
  23558. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  23559. }
  23560. }
  23561. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  23562. };
  23563. Skeleton.prototype.getAnimationRange = function (name) {
  23564. return this._ranges[name];
  23565. };
  23566. /**
  23567. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  23568. */
  23569. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  23570. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  23571. if (this._ranges[name] || !source.getAnimationRange(name)) {
  23572. return false;
  23573. }
  23574. var ret = true;
  23575. var frameOffset = this._getHighestAnimationFrame() + 1;
  23576. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  23577. var boneDict = {};
  23578. var sourceBones = source.bones;
  23579. for (var i = 0, nBones = sourceBones.length; i < nBones; i++) {
  23580. boneDict[sourceBones[i].name] = sourceBones[i];
  23581. }
  23582. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  23583. var boneName = this.bones[i].name;
  23584. var sourceBone = boneDict[boneName];
  23585. if (sourceBone) {
  23586. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired);
  23587. }
  23588. else {
  23589. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  23590. ret = false;
  23591. }
  23592. }
  23593. // do not call createAnimationRange(), since it also is done to bones, which was already done
  23594. var range = source.getAnimationRange(name);
  23595. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  23596. return ret;
  23597. };
  23598. Skeleton.prototype.returnToRest = function () {
  23599. for (var index = 0; index < this.bones.length; index++) {
  23600. this.bones[index].returnToRest();
  23601. }
  23602. };
  23603. Skeleton.prototype._getHighestAnimationFrame = function () {
  23604. var ret = 0;
  23605. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  23606. if (this.bones[i].animations[0]) {
  23607. var highest = this.bones[i].animations[0].getHighestFrame();
  23608. if (ret < highest) {
  23609. ret = highest;
  23610. }
  23611. }
  23612. }
  23613. return ret;
  23614. };
  23615. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  23616. var range = this.getAnimationRange(name);
  23617. if (!range) {
  23618. return null;
  23619. }
  23620. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  23621. };
  23622. Skeleton.prototype._markAsDirty = function () {
  23623. this._isDirty = true;
  23624. };
  23625. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  23626. this._meshesWithPoseMatrix.push(mesh);
  23627. };
  23628. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  23629. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  23630. if (index > -1) {
  23631. this._meshesWithPoseMatrix.splice(index, 1);
  23632. }
  23633. };
  23634. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  23635. for (var index = 0; index < this.bones.length; index++) {
  23636. var bone = this.bones[index];
  23637. var parentBone = bone.getParent();
  23638. if (parentBone) {
  23639. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  23640. }
  23641. else {
  23642. if (initialSkinMatrix) {
  23643. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  23644. }
  23645. else {
  23646. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  23647. }
  23648. }
  23649. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  23650. }
  23651. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  23652. };
  23653. Skeleton.prototype.prepare = function () {
  23654. if (!this._isDirty) {
  23655. return;
  23656. }
  23657. if (this.needInitialSkinMatrix) {
  23658. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  23659. var mesh = this._meshesWithPoseMatrix[index];
  23660. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  23661. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  23662. }
  23663. var poseMatrix = mesh.getPoseMatrix();
  23664. // Prepare bones
  23665. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  23666. var bone = this.bones[boneIndex];
  23667. if (!bone.getParent()) {
  23668. var matrix = bone.getBaseMatrix();
  23669. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[0]);
  23670. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[0]);
  23671. }
  23672. }
  23673. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  23674. }
  23675. }
  23676. else {
  23677. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  23678. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  23679. }
  23680. this._computeTransformMatrices(this._transformMatrices, null);
  23681. }
  23682. this._isDirty = false;
  23683. this._scene._activeBones += this.bones.length;
  23684. };
  23685. Skeleton.prototype.getAnimatables = function () {
  23686. if (!this._animatables || this._animatables.length !== this.bones.length) {
  23687. this._animatables = [];
  23688. for (var index = 0; index < this.bones.length; index++) {
  23689. this._animatables.push(this.bones[index]);
  23690. }
  23691. }
  23692. return this._animatables;
  23693. };
  23694. Skeleton.prototype.clone = function (name, id) {
  23695. var result = new Skeleton(name, id || name, this._scene);
  23696. for (var index = 0; index < this.bones.length; index++) {
  23697. var source = this.bones[index];
  23698. var parentBone = null;
  23699. if (source.getParent()) {
  23700. var parentIndex = this.bones.indexOf(source.getParent());
  23701. parentBone = result.bones[parentIndex];
  23702. }
  23703. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  23704. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  23705. }
  23706. return result;
  23707. };
  23708. Skeleton.prototype.dispose = function () {
  23709. this._meshesWithPoseMatrix = [];
  23710. // Animations
  23711. this.getScene().stopAnimation(this);
  23712. // Remove from scene
  23713. this.getScene().removeSkeleton(this);
  23714. };
  23715. Skeleton.prototype.serialize = function () {
  23716. var serializationObject = {};
  23717. serializationObject.name = this.name;
  23718. serializationObject.id = this.id;
  23719. serializationObject.bones = [];
  23720. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  23721. for (var index = 0; index < this.bones.length; index++) {
  23722. var bone = this.bones[index];
  23723. var serializedBone = {
  23724. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  23725. name: bone.name,
  23726. matrix: bone.getLocalMatrix().toArray(),
  23727. rest: bone.getRestPose().toArray()
  23728. };
  23729. serializationObject.bones.push(serializedBone);
  23730. if (bone.length) {
  23731. serializedBone.length = bone.length;
  23732. }
  23733. if (bone.animations && bone.animations.length > 0) {
  23734. serializedBone.animation = bone.animations[0].serialize();
  23735. }
  23736. serializationObject.ranges = [];
  23737. for (var name in this._ranges) {
  23738. var range = {};
  23739. range.name = name;
  23740. range.from = this._ranges[name].from;
  23741. range.to = this._ranges[name].to;
  23742. serializationObject.ranges.push(range);
  23743. }
  23744. }
  23745. return serializationObject;
  23746. };
  23747. Skeleton.Parse = function (parsedSkeleton, scene) {
  23748. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  23749. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  23750. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  23751. var parsedBone = parsedSkeleton.bones[index];
  23752. var parentBone = null;
  23753. if (parsedBone.parentBoneIndex > -1) {
  23754. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  23755. }
  23756. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  23757. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  23758. if (parsedBone.length) {
  23759. bone.length = parsedBone.length;
  23760. }
  23761. if (parsedBone.animation) {
  23762. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  23763. }
  23764. }
  23765. // placed after bones, so createAnimationRange can cascade down
  23766. if (parsedSkeleton.ranges) {
  23767. for (var index = 0; index < parsedSkeleton.ranges.length; index++) {
  23768. var data = parsedSkeleton.ranges[index];
  23769. skeleton.createAnimationRange(data.name, data.from, data.to);
  23770. }
  23771. }
  23772. return skeleton;
  23773. };
  23774. return Skeleton;
  23775. })();
  23776. BABYLON.Skeleton = Skeleton;
  23777. })(BABYLON || (BABYLON = {}));
  23778. var BABYLON;
  23779. (function (BABYLON) {
  23780. var PostProcess = (function () {
  23781. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines, textureType) {
  23782. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  23783. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  23784. this.name = name;
  23785. this.width = -1;
  23786. this.height = -1;
  23787. this._reusable = false;
  23788. this._textures = new BABYLON.SmartArray(2);
  23789. this._currentRenderTextureInd = 0;
  23790. if (camera != null) {
  23791. this._camera = camera;
  23792. this._scene = camera.getScene();
  23793. camera.attachPostProcess(this);
  23794. this._engine = this._scene.getEngine();
  23795. }
  23796. else {
  23797. this._engine = engine;
  23798. }
  23799. this._renderRatio = ratio;
  23800. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  23801. this._reusable = reusable || false;
  23802. this._textureType = textureType;
  23803. this._samplers = samplers || [];
  23804. this._samplers.push("textureSampler");
  23805. this._fragmentUrl = fragmentUrl;
  23806. this._parameters = parameters || [];
  23807. this.updateEffect(defines);
  23808. }
  23809. PostProcess.prototype.updateEffect = function (defines) {
  23810. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  23811. };
  23812. PostProcess.prototype.isReusable = function () {
  23813. return this._reusable;
  23814. };
  23815. PostProcess.prototype.activate = function (camera, sourceTexture) {
  23816. camera = camera || this._camera;
  23817. var scene = camera.getScene();
  23818. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  23819. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  23820. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  23821. desiredWidth = this._renderRatio.width || BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  23822. desiredHeight = this._renderRatio.height || BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  23823. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  23824. if (this._textures.length > 0) {
  23825. for (var i = 0; i < this._textures.length; i++) {
  23826. this._engine._releaseTexture(this._textures.data[i]);
  23827. }
  23828. this._textures.reset();
  23829. }
  23830. this.width = desiredWidth;
  23831. this.height = desiredHeight;
  23832. 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 }));
  23833. if (this._reusable) {
  23834. 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 }));
  23835. }
  23836. if (this.onSizeChanged) {
  23837. this.onSizeChanged();
  23838. }
  23839. }
  23840. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  23841. if (this.onActivate) {
  23842. this.onActivate(camera);
  23843. }
  23844. // Clear
  23845. if (this.clearColor) {
  23846. this._engine.clear(this.clearColor, true, true);
  23847. }
  23848. else {
  23849. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  23850. }
  23851. if (this._reusable) {
  23852. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  23853. }
  23854. };
  23855. Object.defineProperty(PostProcess.prototype, "isSupported", {
  23856. get: function () {
  23857. return this._effect.isSupported;
  23858. },
  23859. enumerable: true,
  23860. configurable: true
  23861. });
  23862. PostProcess.prototype.apply = function () {
  23863. // Check
  23864. if (!this._effect.isReady())
  23865. return null;
  23866. // States
  23867. this._engine.enableEffect(this._effect);
  23868. this._engine.setState(false);
  23869. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23870. this._engine.setDepthBuffer(false);
  23871. this._engine.setDepthWrite(false);
  23872. // Texture
  23873. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  23874. // Parameters
  23875. if (this.onApply) {
  23876. this.onApply(this._effect);
  23877. }
  23878. return this._effect;
  23879. };
  23880. PostProcess.prototype.dispose = function (camera) {
  23881. camera = camera || this._camera;
  23882. if (this._textures.length > 0) {
  23883. for (var i = 0; i < this._textures.length; i++) {
  23884. this._engine._releaseTexture(this._textures.data[i]);
  23885. }
  23886. this._textures.reset();
  23887. }
  23888. if (!camera) {
  23889. return;
  23890. }
  23891. camera.detachPostProcess(this);
  23892. var index = camera._postProcesses.indexOf(this);
  23893. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  23894. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  23895. }
  23896. };
  23897. return PostProcess;
  23898. })();
  23899. BABYLON.PostProcess = PostProcess;
  23900. })(BABYLON || (BABYLON = {}));
  23901. var BABYLON;
  23902. (function (BABYLON) {
  23903. var PostProcessManager = (function () {
  23904. function PostProcessManager(scene) {
  23905. this._vertexDeclaration = [2];
  23906. this._vertexStrideSize = 2 * 4;
  23907. this._scene = scene;
  23908. }
  23909. PostProcessManager.prototype._prepareBuffers = function () {
  23910. if (this._vertexBuffer) {
  23911. return;
  23912. }
  23913. // VBO
  23914. var vertices = [];
  23915. vertices.push(1, 1);
  23916. vertices.push(-1, 1);
  23917. vertices.push(-1, -1);
  23918. vertices.push(1, -1);
  23919. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  23920. // Indices
  23921. var indices = [];
  23922. indices.push(0);
  23923. indices.push(1);
  23924. indices.push(2);
  23925. indices.push(0);
  23926. indices.push(2);
  23927. indices.push(3);
  23928. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  23929. };
  23930. // Methods
  23931. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  23932. var postProcesses = this._scene.activeCamera._postProcesses;
  23933. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  23934. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  23935. return false;
  23936. }
  23937. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  23938. return true;
  23939. };
  23940. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  23941. var engine = this._scene.getEngine();
  23942. for (var index = 0; index < postProcesses.length; index++) {
  23943. if (index < postProcesses.length - 1) {
  23944. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  23945. }
  23946. else {
  23947. if (targetTexture) {
  23948. engine.bindFramebuffer(targetTexture);
  23949. }
  23950. else {
  23951. engine.restoreDefaultFramebuffer();
  23952. }
  23953. }
  23954. var pp = postProcesses[index];
  23955. var effect = pp.apply();
  23956. if (effect) {
  23957. if (pp.onBeforeRender) {
  23958. pp.onBeforeRender(effect);
  23959. }
  23960. // VBOs
  23961. this._prepareBuffers();
  23962. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  23963. // Draw order
  23964. engine.draw(true, 0, 6);
  23965. if (pp.onAfterRender) {
  23966. pp.onAfterRender(effect);
  23967. }
  23968. }
  23969. }
  23970. // Restore depth buffer
  23971. engine.setDepthBuffer(true);
  23972. engine.setDepthWrite(true);
  23973. };
  23974. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  23975. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  23976. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  23977. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  23978. return;
  23979. }
  23980. var engine = this._scene.getEngine();
  23981. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  23982. if (index < postProcessesTakenIndices.length - 1) {
  23983. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera, targetTexture);
  23984. }
  23985. else {
  23986. if (targetTexture) {
  23987. engine.bindFramebuffer(targetTexture, faceIndex);
  23988. }
  23989. else {
  23990. engine.restoreDefaultFramebuffer();
  23991. }
  23992. }
  23993. if (doNotPresent) {
  23994. break;
  23995. }
  23996. var pp = postProcesses[postProcessesTakenIndices[index]];
  23997. var effect = pp.apply();
  23998. if (effect) {
  23999. if (pp.onBeforeRender) {
  24000. pp.onBeforeRender(effect);
  24001. }
  24002. // VBOs
  24003. this._prepareBuffers();
  24004. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  24005. // Draw order
  24006. engine.draw(true, 0, 6);
  24007. if (pp.onAfterRender) {
  24008. pp.onAfterRender(effect);
  24009. }
  24010. }
  24011. }
  24012. // Restore depth buffer
  24013. engine.setDepthBuffer(true);
  24014. engine.setDepthWrite(true);
  24015. };
  24016. PostProcessManager.prototype.dispose = function () {
  24017. if (this._vertexBuffer) {
  24018. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  24019. this._vertexBuffer = null;
  24020. }
  24021. if (this._indexBuffer) {
  24022. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  24023. this._indexBuffer = null;
  24024. }
  24025. };
  24026. return PostProcessManager;
  24027. })();
  24028. BABYLON.PostProcessManager = PostProcessManager;
  24029. })(BABYLON || (BABYLON = {}));
  24030. var BABYLON;
  24031. (function (BABYLON) {
  24032. var PassPostProcess = (function (_super) {
  24033. __extends(PassPostProcess, _super);
  24034. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  24035. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  24036. }
  24037. return PassPostProcess;
  24038. })(BABYLON.PostProcess);
  24039. BABYLON.PassPostProcess = PassPostProcess;
  24040. })(BABYLON || (BABYLON = {}));
  24041. var BABYLON;
  24042. (function (BABYLON) {
  24043. var PhysicsJoint = (function () {
  24044. function PhysicsJoint(type, jointData) {
  24045. this.type = type;
  24046. this.jointData = jointData;
  24047. jointData.nativeParams = jointData.nativeParams || {};
  24048. }
  24049. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  24050. get: function () {
  24051. return this._physicsJoint;
  24052. },
  24053. set: function (newJoint) {
  24054. if (this._physicsJoint) {
  24055. }
  24056. this._physicsJoint = newJoint;
  24057. },
  24058. enumerable: true,
  24059. configurable: true
  24060. });
  24061. //TODO check if the native joints are the same
  24062. //Joint Types
  24063. PhysicsJoint.DistanceJoint = 0;
  24064. PhysicsJoint.HingeJoint = 1;
  24065. PhysicsJoint.BallAndSocketJoint = 2;
  24066. PhysicsJoint.WheelJoint = 3;
  24067. PhysicsJoint.SliderJoint = 4;
  24068. //OIMO
  24069. PhysicsJoint.PrismaticJoint = 5;
  24070. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  24071. PhysicsJoint.UniversalJoint = 6;
  24072. PhysicsJoint.Hinge2Joint = 7;
  24073. //Cannon
  24074. //Similar to a Ball-Joint. Different in params
  24075. //TODO check!!
  24076. PhysicsJoint.PointToPointJoint = 8;
  24077. //Cannon only at the moment
  24078. PhysicsJoint.SpringJoint = 9;
  24079. return PhysicsJoint;
  24080. })();
  24081. BABYLON.PhysicsJoint = PhysicsJoint;
  24082. })(BABYLON || (BABYLON = {}));
  24083. var BABYLON;
  24084. (function (BABYLON) {
  24085. var PhysicsImpostor = (function () {
  24086. function PhysicsImpostor(_mesh, type, _options) {
  24087. var _this = this;
  24088. if (_options === void 0) { _options = { mass: 0 }; }
  24089. this._mesh = _mesh;
  24090. this.type = type;
  24091. this._options = _options;
  24092. this._bodyUpdateRequired = false;
  24093. this._onBeforePhysicsStepCallbacks = new Array();
  24094. this._onAfterPhysicsStepCallbacks = new Array();
  24095. this._onPhysicsCollideCallbacks = [];
  24096. this._deltaPosition = BABYLON.Vector3.Zero();
  24097. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  24098. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  24099. /**
  24100. * this function is executed by the physics engine.
  24101. */
  24102. this.beforeStep = function () {
  24103. _this.mesh.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  24104. //conjugate deltaRotation
  24105. if (_this._deltaRotationConjugated) {
  24106. _this.mesh.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  24107. }
  24108. else {
  24109. _this._tmpRotationWithDelta.copyFrom(_this.mesh.rotationQuaternion);
  24110. }
  24111. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  24112. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  24113. func(_this);
  24114. });
  24115. };
  24116. /**
  24117. * this function is executed by the physics engine.
  24118. */
  24119. this.afterStep = function () {
  24120. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  24121. func(_this);
  24122. });
  24123. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  24124. _this.mesh.position.addInPlace(_this._deltaPosition);
  24125. if (_this._deltaRotation) {
  24126. _this.mesh.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  24127. }
  24128. };
  24129. //event and body object due to cannon's event-based architecture.
  24130. this.onCollide = function (e) {
  24131. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  24132. if (otherImpostor) {
  24133. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  24134. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  24135. }).forEach(function (obj) {
  24136. obj.callback(_this, otherImpostor);
  24137. });
  24138. }
  24139. };
  24140. //default options params
  24141. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  24142. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  24143. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  24144. this._physicsEngine = this._mesh.getScene().getPhysicsEngine();
  24145. this._joints = [];
  24146. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  24147. if (!this._mesh.parent) {
  24148. this._init();
  24149. }
  24150. }
  24151. /**
  24152. * This function will completly initialize this impostor.
  24153. * It will create a new body - but only if this mesh has no parent.
  24154. * If it has, this impostor will not be used other than to define the impostor
  24155. * of the child mesh.
  24156. */
  24157. PhysicsImpostor.prototype._init = function () {
  24158. this._physicsEngine.removeImpostor(this);
  24159. this.physicsBody = null;
  24160. this._parent = this._parent || this._getPhysicsParent();
  24161. if (!this.parent) {
  24162. this._physicsEngine.addImpostor(this);
  24163. }
  24164. };
  24165. PhysicsImpostor.prototype._getPhysicsParent = function () {
  24166. if (this.mesh.parent instanceof BABYLON.AbstractMesh) {
  24167. var parentMesh = this.mesh.parent;
  24168. return parentMesh.getPhysicsImpostor();
  24169. }
  24170. return;
  24171. };
  24172. /**
  24173. * Should a new body be generated.
  24174. */
  24175. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  24176. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  24177. };
  24178. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  24179. this.forceUpdate();
  24180. };
  24181. /**
  24182. * Force a regeneration of this or the parent's impostor's body.
  24183. * Use under cautious - This will remove all joints already implemented.
  24184. */
  24185. PhysicsImpostor.prototype.forceUpdate = function () {
  24186. this._init();
  24187. if (this.parent) {
  24188. this.parent.forceUpdate();
  24189. }
  24190. };
  24191. Object.defineProperty(PhysicsImpostor.prototype, "mesh", {
  24192. get: function () {
  24193. return this._mesh;
  24194. },
  24195. enumerable: true,
  24196. configurable: true
  24197. });
  24198. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  24199. /**
  24200. * Gets the body that holds this impostor. Either its own, or its parent.
  24201. */
  24202. get: function () {
  24203. return this._parent ? this._parent.physicsBody : this._physicsBody;
  24204. },
  24205. /**
  24206. * Set the physics body. Used mainly by the physics engine/plugin
  24207. */
  24208. set: function (physicsBody) {
  24209. if (this._physicsBody) {
  24210. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  24211. }
  24212. this._physicsBody = physicsBody;
  24213. this.resetUpdateFlags();
  24214. },
  24215. enumerable: true,
  24216. configurable: true
  24217. });
  24218. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  24219. get: function () {
  24220. return this._parent;
  24221. },
  24222. enumerable: true,
  24223. configurable: true
  24224. });
  24225. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  24226. this._bodyUpdateRequired = false;
  24227. };
  24228. /**
  24229. * Get a specific parametes from the options parameter.
  24230. */
  24231. PhysicsImpostor.prototype.getParam = function (paramName) {
  24232. return this._options[paramName];
  24233. };
  24234. /**
  24235. * Sets a specific parameter in the options given to the physics plugin
  24236. */
  24237. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  24238. this._options[paramName] = value;
  24239. this._bodyUpdateRequired = true;
  24240. };
  24241. /**
  24242. * Specifically change the body's mass option. Won't recreate the physics body object
  24243. */
  24244. PhysicsImpostor.prototype.setMass = function (mass) {
  24245. if (this.getParam("mass") !== mass) {
  24246. this.setParam("mass", mass);
  24247. }
  24248. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  24249. };
  24250. /**
  24251. * Set the body's linear velocity.
  24252. */
  24253. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  24254. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  24255. };
  24256. /**
  24257. * Set the body's linear velocity.
  24258. */
  24259. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  24260. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  24261. };
  24262. /**
  24263. * Execute a function with the physics plugin native code.
  24264. * Provide a function the will have two variables - the world object and the physics body object.
  24265. */
  24266. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  24267. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  24268. };
  24269. /**
  24270. * Register a function that will be executed before the physics world is stepping forward.
  24271. */
  24272. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  24273. this._onBeforePhysicsStepCallbacks.push(func);
  24274. };
  24275. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  24276. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  24277. if (index > -1) {
  24278. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  24279. }
  24280. else {
  24281. BABYLON.Tools.Warn("Function to remove was not found");
  24282. }
  24283. };
  24284. /**
  24285. * Register a function that will be executed after the physics step
  24286. */
  24287. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  24288. this._onAfterPhysicsStepCallbacks.push(func);
  24289. };
  24290. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  24291. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  24292. if (index > -1) {
  24293. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  24294. }
  24295. else {
  24296. BABYLON.Tools.Warn("Function to remove was not found");
  24297. }
  24298. };
  24299. /**
  24300. * register a function that will be executed when this impostor collides against a different body.
  24301. */
  24302. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  24303. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  24304. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  24305. };
  24306. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  24307. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  24308. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  24309. if (index > -1) {
  24310. this._onPhysicsCollideCallbacks.splice(index, 1);
  24311. }
  24312. else {
  24313. BABYLON.Tools.Warn("Function to remove was not found");
  24314. }
  24315. };
  24316. /**
  24317. * Apply a force
  24318. */
  24319. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  24320. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  24321. };
  24322. /**
  24323. * Apply an impulse
  24324. */
  24325. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  24326. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  24327. };
  24328. /**
  24329. * A help function to create a joint.
  24330. */
  24331. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  24332. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  24333. this.addJoint(otherImpostor, joint);
  24334. };
  24335. /**
  24336. * Add a joint to this impostor with a different impostor.
  24337. */
  24338. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  24339. this._joints.push({
  24340. otherImpostor: otherImpostor,
  24341. joint: joint
  24342. });
  24343. this._physicsEngine.addJoint(this, otherImpostor, joint);
  24344. };
  24345. /**
  24346. * Will keep this body still, in a sleep mode.
  24347. */
  24348. PhysicsImpostor.prototype.sleep = function () {
  24349. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  24350. };
  24351. /**
  24352. * Wake the body up.
  24353. */
  24354. PhysicsImpostor.prototype.wakeUp = function () {
  24355. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  24356. };
  24357. PhysicsImpostor.prototype.dispose = function (disposeChildren) {
  24358. if (disposeChildren === void 0) { disposeChildren = true; }
  24359. this.physicsBody = null;
  24360. if (this.parent) {
  24361. this.parent.forceUpdate();
  24362. }
  24363. else {
  24364. this.mesh.getChildMeshes().forEach(function (mesh) {
  24365. if (mesh.physicsImpostor) {
  24366. if (disposeChildren) {
  24367. mesh.physicsImpostor.dispose();
  24368. mesh.physicsImpostor = null;
  24369. }
  24370. }
  24371. });
  24372. }
  24373. };
  24374. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  24375. this._deltaPosition.copyFrom(position);
  24376. };
  24377. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  24378. if (!this._deltaRotation) {
  24379. this._deltaRotation = new BABYLON.Quaternion();
  24380. }
  24381. this._deltaRotation.copyFrom(rotation);
  24382. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  24383. };
  24384. //Impostor types
  24385. PhysicsImpostor.NoImpostor = 0;
  24386. PhysicsImpostor.SphereImpostor = 1;
  24387. PhysicsImpostor.BoxImpostor = 2;
  24388. PhysicsImpostor.PlaneImpostor = 3;
  24389. PhysicsImpostor.MeshImpostor = 4;
  24390. PhysicsImpostor.CapsuleImpostor = 5;
  24391. PhysicsImpostor.ConeImpostor = 6;
  24392. PhysicsImpostor.CylinderImpostor = 7;
  24393. PhysicsImpostor.ConvexHullImpostor = 8;
  24394. PhysicsImpostor.HeightmapImpostor = 9;
  24395. return PhysicsImpostor;
  24396. })();
  24397. BABYLON.PhysicsImpostor = PhysicsImpostor;
  24398. })(BABYLON || (BABYLON = {}));
  24399. var BABYLON;
  24400. (function (BABYLON) {
  24401. var PhysicsEngine = (function () {
  24402. function PhysicsEngine(gravity, _physicsPlugin) {
  24403. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  24404. this._physicsPlugin = _physicsPlugin;
  24405. //new methods and parameters
  24406. this._impostors = [];
  24407. this._joints = [];
  24408. if (!this._physicsPlugin.isSupported()) {
  24409. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  24410. + "Please make sure it is included.");
  24411. }
  24412. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  24413. this.setGravity(gravity);
  24414. this.setTimeStep();
  24415. }
  24416. PhysicsEngine.prototype.setGravity = function (gravity) {
  24417. this.gravity = gravity;
  24418. this._physicsPlugin.setGravity(this.gravity);
  24419. };
  24420. /**
  24421. * Set the time step of the physics engine.
  24422. * default is 1/60.
  24423. * To slow it down, enter 1/600 for example.
  24424. * To speed it up, 1/30
  24425. */
  24426. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  24427. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  24428. this._physicsPlugin.setTimeStep(newTimeStep);
  24429. };
  24430. PhysicsEngine.prototype.dispose = function () {
  24431. this._impostors.forEach(function (impostor) {
  24432. impostor.dispose();
  24433. });
  24434. this._physicsPlugin.dispose();
  24435. };
  24436. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  24437. return this._physicsPlugin.name;
  24438. };
  24439. PhysicsEngine.prototype.addImpostor = function (impostor) {
  24440. this._impostors.push(impostor);
  24441. //if no parent, generate the body
  24442. if (!impostor.parent) {
  24443. this._physicsPlugin.generatePhysicsBody(impostor);
  24444. }
  24445. };
  24446. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  24447. var index = this._impostors.indexOf(impostor);
  24448. if (index > -1) {
  24449. var removed = this._impostors.splice(index, 1);
  24450. //Is it needed?
  24451. if (removed.length) {
  24452. //this will also remove it from the world.
  24453. removed[0].physicsBody = null;
  24454. }
  24455. }
  24456. };
  24457. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  24458. var impostorJoint = {
  24459. mainImpostor: mainImpostor,
  24460. connectedImpostor: connectedImpostor,
  24461. joint: joint
  24462. };
  24463. this._joints.push(impostorJoint);
  24464. this._physicsPlugin.generateJoint(impostorJoint);
  24465. };
  24466. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  24467. var matchingJoints = this._joints.filter(function (impostorJoint) {
  24468. return (impostorJoint.connectedImpostor === connectedImpostor
  24469. && impostorJoint.joint === joint
  24470. && impostorJoint.mainImpostor === mainImpostor);
  24471. });
  24472. if (matchingJoints.length) {
  24473. this._physicsPlugin.removeJoint(matchingJoints[0]);
  24474. }
  24475. };
  24476. /**
  24477. * Called by the scene. no need to call it.
  24478. */
  24479. PhysicsEngine.prototype._step = function (delta) {
  24480. var _this = this;
  24481. //check if any mesh has no body / requires an update
  24482. this._impostors.forEach(function (impostor) {
  24483. if (impostor.isBodyInitRequired()) {
  24484. _this._physicsPlugin.generatePhysicsBody(impostor);
  24485. }
  24486. });
  24487. if (delta > 0.1) {
  24488. delta = 0.1;
  24489. }
  24490. else if (delta <= 0) {
  24491. delta = 1.0 / 60.0;
  24492. }
  24493. this._physicsPlugin.executeStep(delta, this._impostors);
  24494. };
  24495. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  24496. return this._physicsPlugin;
  24497. };
  24498. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  24499. for (var i = 0; i < this._impostors.length; ++i) {
  24500. if (this._impostors[i].physicsBody === body) {
  24501. return this._impostors[i];
  24502. }
  24503. }
  24504. };
  24505. // Statics, Legacy support.
  24506. /**
  24507. * @Deprecated
  24508. *
  24509. */
  24510. PhysicsEngine.NoImpostor = BABYLON.PhysicsImpostor.NoImpostor;
  24511. PhysicsEngine.SphereImpostor = BABYLON.PhysicsImpostor.SphereImpostor;
  24512. PhysicsEngine.BoxImpostor = BABYLON.PhysicsImpostor.BoxImpostor;
  24513. PhysicsEngine.PlaneImpostor = BABYLON.PhysicsImpostor.PlaneImpostor;
  24514. PhysicsEngine.MeshImpostor = BABYLON.PhysicsImpostor.MeshImpostor;
  24515. PhysicsEngine.CapsuleImpostor = BABYLON.PhysicsImpostor.CapsuleImpostor;
  24516. PhysicsEngine.ConeImpostor = BABYLON.PhysicsImpostor.ConeImpostor;
  24517. PhysicsEngine.CylinderImpostor = BABYLON.PhysicsImpostor.CylinderImpostor;
  24518. PhysicsEngine.ConvexHullImpostor = BABYLON.PhysicsImpostor.ConvexHullImpostor;
  24519. PhysicsEngine.HeightmapImpostor = BABYLON.PhysicsImpostor.HeightmapImpostor;
  24520. PhysicsEngine.Epsilon = 0.001;
  24521. return PhysicsEngine;
  24522. })();
  24523. BABYLON.PhysicsEngine = PhysicsEngine;
  24524. })(BABYLON || (BABYLON = {}));
  24525. var BABYLON;
  24526. (function (BABYLON) {
  24527. var VertexData = (function () {
  24528. function VertexData() {
  24529. }
  24530. VertexData.prototype.set = function (data, kind) {
  24531. switch (kind) {
  24532. case BABYLON.VertexBuffer.PositionKind:
  24533. this.positions = data;
  24534. break;
  24535. case BABYLON.VertexBuffer.NormalKind:
  24536. this.normals = data;
  24537. break;
  24538. case BABYLON.VertexBuffer.UVKind:
  24539. this.uvs = data;
  24540. break;
  24541. case BABYLON.VertexBuffer.UV2Kind:
  24542. this.uvs2 = data;
  24543. break;
  24544. case BABYLON.VertexBuffer.UV3Kind:
  24545. this.uvs3 = data;
  24546. break;
  24547. case BABYLON.VertexBuffer.UV4Kind:
  24548. this.uvs4 = data;
  24549. break;
  24550. case BABYLON.VertexBuffer.UV5Kind:
  24551. this.uvs5 = data;
  24552. break;
  24553. case BABYLON.VertexBuffer.UV6Kind:
  24554. this.uvs6 = data;
  24555. break;
  24556. case BABYLON.VertexBuffer.ColorKind:
  24557. this.colors = data;
  24558. break;
  24559. case BABYLON.VertexBuffer.MatricesIndicesKind:
  24560. this.matricesIndices = data;
  24561. break;
  24562. case BABYLON.VertexBuffer.MatricesWeightsKind:
  24563. this.matricesWeights = data;
  24564. break;
  24565. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  24566. this.matricesIndicesExtra = data;
  24567. break;
  24568. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  24569. this.matricesWeightsExtra = data;
  24570. break;
  24571. }
  24572. };
  24573. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  24574. this._applyTo(mesh, updatable);
  24575. };
  24576. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  24577. this._applyTo(geometry, updatable);
  24578. };
  24579. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  24580. this._update(mesh);
  24581. };
  24582. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  24583. this._update(geometry);
  24584. };
  24585. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  24586. if (this.positions) {
  24587. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  24588. }
  24589. if (this.normals) {
  24590. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  24591. }
  24592. if (this.uvs) {
  24593. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  24594. }
  24595. if (this.uvs2) {
  24596. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  24597. }
  24598. if (this.uvs3) {
  24599. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  24600. }
  24601. if (this.uvs4) {
  24602. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  24603. }
  24604. if (this.uvs5) {
  24605. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  24606. }
  24607. if (this.uvs6) {
  24608. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  24609. }
  24610. if (this.colors) {
  24611. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  24612. }
  24613. if (this.matricesIndices) {
  24614. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  24615. }
  24616. if (this.matricesWeights) {
  24617. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  24618. }
  24619. if (this.matricesIndicesExtra) {
  24620. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  24621. }
  24622. if (this.matricesWeightsExtra) {
  24623. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  24624. }
  24625. if (this.indices) {
  24626. meshOrGeometry.setIndices(this.indices);
  24627. }
  24628. };
  24629. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  24630. if (this.positions) {
  24631. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  24632. }
  24633. if (this.normals) {
  24634. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  24635. }
  24636. if (this.uvs) {
  24637. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  24638. }
  24639. if (this.uvs2) {
  24640. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  24641. }
  24642. if (this.uvs3) {
  24643. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  24644. }
  24645. if (this.uvs4) {
  24646. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  24647. }
  24648. if (this.uvs5) {
  24649. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  24650. }
  24651. if (this.uvs6) {
  24652. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  24653. }
  24654. if (this.colors) {
  24655. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  24656. }
  24657. if (this.matricesIndices) {
  24658. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  24659. }
  24660. if (this.matricesWeights) {
  24661. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  24662. }
  24663. if (this.matricesIndicesExtra) {
  24664. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  24665. }
  24666. if (this.matricesWeightsExtra) {
  24667. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  24668. }
  24669. if (this.indices) {
  24670. meshOrGeometry.setIndices(this.indices);
  24671. }
  24672. };
  24673. VertexData.prototype.transform = function (matrix) {
  24674. var transformed = BABYLON.Vector3.Zero();
  24675. var index;
  24676. if (this.positions) {
  24677. var position = BABYLON.Vector3.Zero();
  24678. for (index = 0; index < this.positions.length; index += 3) {
  24679. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  24680. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  24681. this.positions[index] = transformed.x;
  24682. this.positions[index + 1] = transformed.y;
  24683. this.positions[index + 2] = transformed.z;
  24684. }
  24685. }
  24686. if (this.normals) {
  24687. var normal = BABYLON.Vector3.Zero();
  24688. for (index = 0; index < this.normals.length; index += 3) {
  24689. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  24690. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  24691. this.normals[index] = transformed.x;
  24692. this.normals[index + 1] = transformed.y;
  24693. this.normals[index + 2] = transformed.z;
  24694. }
  24695. }
  24696. };
  24697. VertexData.prototype.merge = function (other) {
  24698. if (other.indices) {
  24699. if (!this.indices) {
  24700. this.indices = [];
  24701. }
  24702. var offset = this.positions ? this.positions.length / 3 : 0;
  24703. for (var index = 0; index < other.indices.length; index++) {
  24704. //TODO check type - if Int32Array!
  24705. this.indices.push(other.indices[index] + offset);
  24706. }
  24707. }
  24708. this.positions = this._mergeElement(this.positions, other.positions);
  24709. this.normals = this._mergeElement(this.normals, other.normals);
  24710. this.uvs = this._mergeElement(this.uvs, other.uvs);
  24711. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  24712. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  24713. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  24714. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  24715. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  24716. this.colors = this._mergeElement(this.colors, other.colors);
  24717. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  24718. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  24719. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  24720. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  24721. };
  24722. VertexData.prototype._mergeElement = function (source, other) {
  24723. if (!other)
  24724. return source;
  24725. if (!source)
  24726. return other;
  24727. var len = other.length + source.length;
  24728. var isSrcTypedArray = source instanceof Float32Array;
  24729. var isOthTypedArray = other instanceof Float32Array;
  24730. // use non-loop method when the source is Float32Array
  24731. if (isSrcTypedArray) {
  24732. var ret32 = new Float32Array(len);
  24733. ret32.set(source);
  24734. ret32.set(other, source.length);
  24735. return ret32;
  24736. }
  24737. else if (!isOthTypedArray) {
  24738. return source.concat(other);
  24739. }
  24740. else {
  24741. var ret = source.slice(0); // copy source to a separate array
  24742. for (var i = 0, len = other.length; i < len; i++) {
  24743. ret.push(other[i]);
  24744. }
  24745. return ret;
  24746. }
  24747. };
  24748. VertexData.prototype.serialize = function () {
  24749. var serializationObject = this.serialize();
  24750. if (this.positions) {
  24751. serializationObject.positions = this.positions;
  24752. }
  24753. if (this.normals) {
  24754. serializationObject.normals = this.normals;
  24755. }
  24756. if (this.uvs) {
  24757. serializationObject.uvs = this.uvs;
  24758. }
  24759. if (this.uvs2) {
  24760. serializationObject.uvs2 = this.uvs2;
  24761. }
  24762. if (this.uvs3) {
  24763. serializationObject.uvs3 = this.uvs3;
  24764. }
  24765. if (this.uvs4) {
  24766. serializationObject.uvs4 = this.uvs4;
  24767. }
  24768. if (this.uvs5) {
  24769. serializationObject.uvs5 = this.uvs5;
  24770. }
  24771. if (this.uvs6) {
  24772. serializationObject.uvs6 = this.uvs6;
  24773. }
  24774. if (this.colors) {
  24775. serializationObject.colors = this.colors;
  24776. }
  24777. if (this.matricesIndices) {
  24778. serializationObject.matricesIndices = this.matricesIndices;
  24779. serializationObject.matricesIndices._isExpanded = true;
  24780. }
  24781. if (this.matricesWeights) {
  24782. serializationObject.matricesWeights = this.matricesWeights;
  24783. }
  24784. if (this.matricesIndicesExtra) {
  24785. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  24786. serializationObject.matricesIndicesExtra._isExpanded = true;
  24787. }
  24788. if (this.matricesWeightsExtra) {
  24789. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  24790. }
  24791. serializationObject.indices = this.indices;
  24792. return serializationObject;
  24793. };
  24794. // Statics
  24795. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  24796. return VertexData._ExtractFrom(mesh, copyWhenShared);
  24797. };
  24798. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  24799. return VertexData._ExtractFrom(geometry, copyWhenShared);
  24800. };
  24801. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  24802. var result = new VertexData();
  24803. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  24804. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  24805. }
  24806. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  24807. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  24808. }
  24809. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  24810. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  24811. }
  24812. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  24813. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  24814. }
  24815. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  24816. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  24817. }
  24818. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  24819. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  24820. }
  24821. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  24822. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  24823. }
  24824. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  24825. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  24826. }
  24827. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  24828. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  24829. }
  24830. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  24831. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  24832. }
  24833. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  24834. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  24835. }
  24836. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  24837. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  24838. }
  24839. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  24840. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  24841. }
  24842. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  24843. return result;
  24844. };
  24845. VertexData.CreateRibbon = function (options) {
  24846. var pathArray = options.pathArray;
  24847. var closeArray = options.closeArray || false;
  24848. var closePath = options.closePath || false;
  24849. var defaultOffset = Math.floor(pathArray[0].length / 2);
  24850. var offset = options.offset || defaultOffset;
  24851. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  24852. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24853. var positions = [];
  24854. var indices = [];
  24855. var normals = [];
  24856. var uvs = [];
  24857. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  24858. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  24859. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  24860. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  24861. var minlg; // minimal length among all paths from pathArray
  24862. var lg = []; // array of path lengths : nb of vertex per path
  24863. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  24864. var p; // path iterator
  24865. var i; // point iterator
  24866. var j; // point iterator
  24867. // if single path in pathArray
  24868. if (pathArray.length < 2) {
  24869. var ar1 = [];
  24870. var ar2 = [];
  24871. for (i = 0; i < pathArray[0].length - offset; i++) {
  24872. ar1.push(pathArray[0][i]);
  24873. ar2.push(pathArray[0][i + offset]);
  24874. }
  24875. pathArray = [ar1, ar2];
  24876. }
  24877. // positions and horizontal distances (u)
  24878. var idc = 0;
  24879. var closePathCorr = (closePath) ? 1 : 0;
  24880. var path;
  24881. var l;
  24882. minlg = pathArray[0].length;
  24883. var vectlg;
  24884. var dist;
  24885. for (p = 0; p < pathArray.length; p++) {
  24886. uTotalDistance[p] = 0;
  24887. us[p] = [0];
  24888. path = pathArray[p];
  24889. l = path.length;
  24890. minlg = (minlg < l) ? minlg : l;
  24891. j = 0;
  24892. while (j < l) {
  24893. positions.push(path[j].x, path[j].y, path[j].z);
  24894. if (j > 0) {
  24895. vectlg = path[j].subtract(path[j - 1]).length();
  24896. dist = vectlg + uTotalDistance[p];
  24897. us[p].push(dist);
  24898. uTotalDistance[p] = dist;
  24899. }
  24900. j++;
  24901. }
  24902. if (closePath) {
  24903. j--;
  24904. positions.push(path[0].x, path[0].y, path[0].z);
  24905. vectlg = path[j].subtract(path[0]).length();
  24906. dist = vectlg + uTotalDistance[p];
  24907. us[p].push(dist);
  24908. uTotalDistance[p] = dist;
  24909. }
  24910. lg[p] = l + closePathCorr;
  24911. idx[p] = idc;
  24912. idc += (l + closePathCorr);
  24913. }
  24914. // vertical distances (v)
  24915. var path1;
  24916. var path2;
  24917. var vertex1;
  24918. var vertex2;
  24919. for (i = 0; i < minlg + closePathCorr; i++) {
  24920. vTotalDistance[i] = 0;
  24921. vs[i] = [0];
  24922. for (p = 0; p < pathArray.length - 1; p++) {
  24923. path1 = pathArray[p];
  24924. path2 = pathArray[p + 1];
  24925. if (i === minlg) {
  24926. vertex1 = path1[0];
  24927. vertex2 = path2[0];
  24928. }
  24929. else {
  24930. vertex1 = path1[i];
  24931. vertex2 = path2[i];
  24932. }
  24933. vectlg = vertex2.subtract(vertex1).length();
  24934. dist = vectlg + vTotalDistance[i];
  24935. vs[i].push(dist);
  24936. vTotalDistance[i] = dist;
  24937. }
  24938. if (closeArray) {
  24939. path1 = pathArray[p];
  24940. path2 = pathArray[0];
  24941. if (i === minlg) {
  24942. vertex2 = path2[0];
  24943. }
  24944. vectlg = vertex2.subtract(vertex1).length();
  24945. dist = vectlg + vTotalDistance[i];
  24946. vTotalDistance[i] = dist;
  24947. }
  24948. }
  24949. // uvs
  24950. var u;
  24951. var v;
  24952. for (p = 0; p < pathArray.length; p++) {
  24953. for (i = 0; i < minlg + closePathCorr; i++) {
  24954. u = us[p][i] / uTotalDistance[p];
  24955. v = vs[i][p] / vTotalDistance[i];
  24956. uvs.push(u, v);
  24957. }
  24958. }
  24959. // indices
  24960. p = 0; // path index
  24961. var pi = 0; // positions array index
  24962. var l1 = lg[p] - 1; // path1 length
  24963. var l2 = lg[p + 1] - 1; // path2 length
  24964. var min = (l1 < l2) ? l1 : l2; // current path stop index
  24965. var shft = idx[1] - idx[0]; // shift
  24966. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  24967. while (pi <= min && p < path1nb) {
  24968. // 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
  24969. indices.push(pi, pi + shft, pi + 1);
  24970. indices.push(pi + shft + 1, pi + 1, pi + shft);
  24971. pi += 1;
  24972. if (pi === min) {
  24973. p++;
  24974. if (p === lg.length - 1) {
  24975. shft = idx[0] - idx[p];
  24976. l1 = lg[p] - 1;
  24977. l2 = lg[0] - 1;
  24978. }
  24979. else {
  24980. shft = idx[p + 1] - idx[p];
  24981. l1 = lg[p] - 1;
  24982. l2 = lg[p + 1] - 1;
  24983. }
  24984. pi = idx[p];
  24985. min = (l1 < l2) ? l1 + pi : l2 + pi;
  24986. }
  24987. }
  24988. // normals
  24989. VertexData.ComputeNormals(positions, indices, normals);
  24990. if (closePath) {
  24991. var indexFirst = 0;
  24992. var indexLast = 0;
  24993. for (p = 0; p < pathArray.length; p++) {
  24994. indexFirst = idx[p] * 3;
  24995. if (p + 1 < pathArray.length) {
  24996. indexLast = (idx[p + 1] - 1) * 3;
  24997. }
  24998. else {
  24999. indexLast = normals.length - 3;
  25000. }
  25001. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  25002. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  25003. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  25004. normals[indexLast] = normals[indexFirst];
  25005. normals[indexLast + 1] = normals[indexFirst + 1];
  25006. normals[indexLast + 2] = normals[indexFirst + 2];
  25007. }
  25008. }
  25009. // sides
  25010. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25011. // Result
  25012. var vertexData = new VertexData();
  25013. vertexData.indices = indices;
  25014. vertexData.positions = positions;
  25015. vertexData.normals = normals;
  25016. vertexData.uvs = uvs;
  25017. if (closePath) {
  25018. vertexData._idx = idx;
  25019. }
  25020. return vertexData;
  25021. };
  25022. VertexData.CreateBox = function (options) {
  25023. var normalsSource = [
  25024. new BABYLON.Vector3(0, 0, 1),
  25025. new BABYLON.Vector3(0, 0, -1),
  25026. new BABYLON.Vector3(1, 0, 0),
  25027. new BABYLON.Vector3(-1, 0, 0),
  25028. new BABYLON.Vector3(0, 1, 0),
  25029. new BABYLON.Vector3(0, -1, 0)
  25030. ];
  25031. var indices = [];
  25032. var positions = [];
  25033. var normals = [];
  25034. var uvs = [];
  25035. var width = options.width || options.size || 1;
  25036. var height = options.height || options.size || 1;
  25037. var depth = options.depth || options.size || 1;
  25038. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25039. var faceUV = options.faceUV || new Array(6);
  25040. var faceColors = options.faceColors;
  25041. var colors = [];
  25042. // default face colors and UV if undefined
  25043. for (var f = 0; f < 6; f++) {
  25044. if (faceUV[f] === undefined) {
  25045. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  25046. }
  25047. if (faceColors && faceColors[f] === undefined) {
  25048. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  25049. }
  25050. }
  25051. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  25052. // Create each face in turn.
  25053. for (var index = 0; index < normalsSource.length; index++) {
  25054. var normal = normalsSource[index];
  25055. // Get two vectors perpendicular to the face normal and to each other.
  25056. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  25057. var side2 = BABYLON.Vector3.Cross(normal, side1);
  25058. // Six indices (two triangles) per face.
  25059. var verticesLength = positions.length / 3;
  25060. indices.push(verticesLength);
  25061. indices.push(verticesLength + 1);
  25062. indices.push(verticesLength + 2);
  25063. indices.push(verticesLength);
  25064. indices.push(verticesLength + 2);
  25065. indices.push(verticesLength + 3);
  25066. // Four vertices per face.
  25067. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  25068. positions.push(vertex.x, vertex.y, vertex.z);
  25069. normals.push(normal.x, normal.y, normal.z);
  25070. uvs.push(faceUV[index].z, faceUV[index].w);
  25071. if (faceColors) {
  25072. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25073. }
  25074. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  25075. positions.push(vertex.x, vertex.y, vertex.z);
  25076. normals.push(normal.x, normal.y, normal.z);
  25077. uvs.push(faceUV[index].x, faceUV[index].w);
  25078. if (faceColors) {
  25079. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25080. }
  25081. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  25082. positions.push(vertex.x, vertex.y, vertex.z);
  25083. normals.push(normal.x, normal.y, normal.z);
  25084. uvs.push(faceUV[index].x, faceUV[index].y);
  25085. if (faceColors) {
  25086. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25087. }
  25088. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  25089. positions.push(vertex.x, vertex.y, vertex.z);
  25090. normals.push(normal.x, normal.y, normal.z);
  25091. uvs.push(faceUV[index].z, faceUV[index].y);
  25092. if (faceColors) {
  25093. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25094. }
  25095. }
  25096. // sides
  25097. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25098. // Result
  25099. var vertexData = new VertexData();
  25100. vertexData.indices = indices;
  25101. vertexData.positions = positions;
  25102. vertexData.normals = normals;
  25103. vertexData.uvs = uvs;
  25104. if (faceColors) {
  25105. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  25106. vertexData.colors = totalColors;
  25107. }
  25108. return vertexData;
  25109. };
  25110. VertexData.CreateSphere = function (options) {
  25111. var segments = options.segments || 32;
  25112. var diameterX = options.diameterX || options.diameter || 1;
  25113. var diameterY = options.diameterY || options.diameter || 1;
  25114. var diameterZ = options.diameterZ || options.diameter || 1;
  25115. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  25116. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  25117. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25118. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  25119. var totalZRotationSteps = 2 + segments;
  25120. var totalYRotationSteps = 2 * totalZRotationSteps;
  25121. var indices = [];
  25122. var positions = [];
  25123. var normals = [];
  25124. var uvs = [];
  25125. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  25126. var normalizedZ = zRotationStep / totalZRotationSteps;
  25127. var angleZ = normalizedZ * Math.PI * slice;
  25128. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  25129. var normalizedY = yRotationStep / totalYRotationSteps;
  25130. var angleY = normalizedY * Math.PI * 2 * arc;
  25131. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  25132. var rotationY = BABYLON.Matrix.RotationY(angleY);
  25133. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  25134. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  25135. var vertex = complete.multiply(radius);
  25136. var normal = complete.divide(radius).normalize();
  25137. positions.push(vertex.x, vertex.y, vertex.z);
  25138. normals.push(normal.x, normal.y, normal.z);
  25139. uvs.push(normalizedY, normalizedZ);
  25140. }
  25141. if (zRotationStep > 0) {
  25142. var verticesCount = positions.length / 3;
  25143. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  25144. indices.push((firstIndex));
  25145. indices.push((firstIndex + 1));
  25146. indices.push(firstIndex + totalYRotationSteps + 1);
  25147. indices.push((firstIndex + totalYRotationSteps + 1));
  25148. indices.push((firstIndex + 1));
  25149. indices.push((firstIndex + totalYRotationSteps + 2));
  25150. }
  25151. }
  25152. }
  25153. // Sides
  25154. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25155. // Result
  25156. var vertexData = new VertexData();
  25157. vertexData.indices = indices;
  25158. vertexData.positions = positions;
  25159. vertexData.normals = normals;
  25160. vertexData.uvs = uvs;
  25161. return vertexData;
  25162. };
  25163. // Cylinder and cone
  25164. VertexData.CreateCylinder = function (options) {
  25165. var height = options.height || 2;
  25166. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  25167. var diameterBottom = options.diameterBottom || options.diameter || 1;
  25168. var tessellation = options.tessellation || 24;
  25169. var subdivisions = options.subdivisions || 1;
  25170. var hasRings = options.hasRings;
  25171. var enclose = options.enclose;
  25172. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  25173. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25174. var faceUV = options.faceUV || new Array(3);
  25175. var faceColors = options.faceColors;
  25176. // default face colors and UV if undefined
  25177. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  25178. var ringNb = (hasRings) ? subdivisions : 1;
  25179. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  25180. var f;
  25181. for (f = 0; f < surfaceNb; f++) {
  25182. if (faceColors && faceColors[f] === undefined) {
  25183. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  25184. }
  25185. }
  25186. for (f = 0; f < surfaceNb; f++) {
  25187. if (faceUV && faceUV[f] === undefined) {
  25188. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  25189. }
  25190. }
  25191. var indices = [];
  25192. var positions = [];
  25193. var normals = [];
  25194. var uvs = [];
  25195. var colors = [];
  25196. var angle_step = Math.PI * 2 * arc / tessellation;
  25197. var angle;
  25198. var h;
  25199. var radius;
  25200. var tan = (diameterBottom - diameterTop) / 2 / height;
  25201. var ringVertex = BABYLON.Vector3.Zero();
  25202. var ringNormal = BABYLON.Vector3.Zero();
  25203. var ringFirstVertex = BABYLON.Vector3.Zero();
  25204. var ringFirstNormal = BABYLON.Vector3.Zero();
  25205. var quadNormal = BABYLON.Vector3.Zero();
  25206. var Y = BABYLON.Axis.Y;
  25207. // positions, normals, uvs
  25208. var i;
  25209. var j;
  25210. var r;
  25211. var ringIdx = 1;
  25212. var s = 1; // surface index
  25213. var cs = 0;
  25214. var v = 0;
  25215. for (i = 0; i <= subdivisions; i++) {
  25216. h = i / subdivisions;
  25217. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  25218. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  25219. for (r = 0; r < ringIdx; r++) {
  25220. if (hasRings) {
  25221. s += r;
  25222. }
  25223. if (enclose) {
  25224. s += 2 * r;
  25225. }
  25226. for (j = 0; j <= tessellation; j++) {
  25227. angle = j * angle_step;
  25228. // position
  25229. ringVertex.x = Math.cos(-angle) * radius;
  25230. ringVertex.y = -height / 2 + h * height;
  25231. ringVertex.z = Math.sin(-angle) * radius;
  25232. // normal
  25233. if (diameterTop === 0 && i === subdivisions) {
  25234. // if no top cap, reuse former normals
  25235. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  25236. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  25237. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  25238. }
  25239. else {
  25240. ringNormal.x = ringVertex.x;
  25241. ringNormal.z = ringVertex.z;
  25242. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  25243. ringNormal.normalize();
  25244. }
  25245. // keep first ring vertex values for enclose
  25246. if (j === 0) {
  25247. ringFirstVertex.copyFrom(ringVertex);
  25248. ringFirstNormal.copyFrom(ringNormal);
  25249. }
  25250. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  25251. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  25252. if (hasRings) {
  25253. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  25254. }
  25255. else {
  25256. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  25257. }
  25258. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  25259. if (faceColors) {
  25260. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  25261. }
  25262. }
  25263. // if enclose, add four vertices and their dedicated normals
  25264. if (arc !== 1 && enclose) {
  25265. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  25266. positions.push(0, ringVertex.y, 0);
  25267. positions.push(0, ringVertex.y, 0);
  25268. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  25269. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  25270. quadNormal.normalize();
  25271. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  25272. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  25273. quadNormal.normalize();
  25274. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  25275. if (hasRings) {
  25276. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  25277. }
  25278. else {
  25279. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  25280. }
  25281. uvs.push(faceUV[s + 1].x, v);
  25282. uvs.push(faceUV[s + 1].z, v);
  25283. if (hasRings) {
  25284. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  25285. }
  25286. else {
  25287. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  25288. }
  25289. uvs.push(faceUV[s + 2].x, v);
  25290. uvs.push(faceUV[s + 2].z, v);
  25291. if (faceColors) {
  25292. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  25293. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  25294. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  25295. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  25296. }
  25297. }
  25298. if (cs !== s) {
  25299. cs = s;
  25300. }
  25301. }
  25302. }
  25303. // indices
  25304. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  25305. var s;
  25306. i = 0;
  25307. for (s = 0; s < subdivisions; s++) {
  25308. for (j = 0; j < tessellation; j++) {
  25309. var i0 = i * (e + 1) + j;
  25310. var i1 = (i + 1) * (e + 1) + j;
  25311. var i2 = i * (e + 1) + (j + 1);
  25312. var i3 = (i + 1) * (e + 1) + (j + 1);
  25313. indices.push(i0, i1, i2);
  25314. indices.push(i3, i2, i1);
  25315. }
  25316. if (arc !== 1 && enclose) {
  25317. indices.push(i0 + 2, i1 + 2, i2 + 2);
  25318. indices.push(i3 + 2, i2 + 2, i1 + 2);
  25319. indices.push(i0 + 4, i1 + 4, i2 + 4);
  25320. indices.push(i3 + 4, i2 + 4, i1 + 4);
  25321. }
  25322. i = (hasRings) ? (i + 2) : (i + 1);
  25323. }
  25324. // Caps
  25325. var createCylinderCap = function (isTop) {
  25326. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  25327. if (radius === 0) {
  25328. return;
  25329. }
  25330. // Cap positions, normals & uvs
  25331. var angle;
  25332. var circleVector;
  25333. var i;
  25334. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  25335. var c;
  25336. if (faceColors) {
  25337. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  25338. }
  25339. // cap center
  25340. var vbase = positions.length / 3;
  25341. var offset = isTop ? height / 2 : -height / 2;
  25342. var center = new BABYLON.Vector3(0, offset, 0);
  25343. positions.push(center.x, center.y, center.z);
  25344. normals.push(0, isTop ? 1 : -1, 0);
  25345. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  25346. if (faceColors) {
  25347. colors.push(c.r, c.g, c.b, c.a);
  25348. }
  25349. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  25350. for (i = 0; i <= tessellation; i++) {
  25351. angle = Math.PI * 2 * i * arc / tessellation;
  25352. var cos = Math.cos(-angle);
  25353. var sin = Math.sin(-angle);
  25354. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  25355. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  25356. positions.push(circleVector.x, circleVector.y, circleVector.z);
  25357. normals.push(0, isTop ? 1 : -1, 0);
  25358. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  25359. if (faceColors) {
  25360. colors.push(c.r, c.g, c.b, c.a);
  25361. }
  25362. }
  25363. // Cap indices
  25364. for (i = 0; i < tessellation; i++) {
  25365. if (!isTop) {
  25366. indices.push(vbase);
  25367. indices.push(vbase + (i + 1));
  25368. indices.push(vbase + (i + 2));
  25369. }
  25370. else {
  25371. indices.push(vbase);
  25372. indices.push(vbase + (i + 2));
  25373. indices.push(vbase + (i + 1));
  25374. }
  25375. }
  25376. };
  25377. // add caps to geometry
  25378. createCylinderCap(false);
  25379. createCylinderCap(true);
  25380. // Sides
  25381. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25382. var vertexData = new VertexData();
  25383. vertexData.indices = indices;
  25384. vertexData.positions = positions;
  25385. vertexData.normals = normals;
  25386. vertexData.uvs = uvs;
  25387. if (faceColors) {
  25388. vertexData.colors = colors;
  25389. }
  25390. return vertexData;
  25391. };
  25392. VertexData.CreateTorus = function (options) {
  25393. var indices = [];
  25394. var positions = [];
  25395. var normals = [];
  25396. var uvs = [];
  25397. var diameter = options.diameter || 1;
  25398. var thickness = options.thickness || 0.5;
  25399. var tessellation = options.tessellation || 16;
  25400. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25401. var stride = tessellation + 1;
  25402. for (var i = 0; i <= tessellation; i++) {
  25403. var u = i / tessellation;
  25404. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  25405. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  25406. for (var j = 0; j <= tessellation; j++) {
  25407. var v = 1 - j / tessellation;
  25408. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  25409. var dx = Math.cos(innerAngle);
  25410. var dy = Math.sin(innerAngle);
  25411. // Create a vertex.
  25412. var normal = new BABYLON.Vector3(dx, dy, 0);
  25413. var position = normal.scale(thickness / 2);
  25414. var textureCoordinate = new BABYLON.Vector2(u, v);
  25415. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  25416. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  25417. positions.push(position.x, position.y, position.z);
  25418. normals.push(normal.x, normal.y, normal.z);
  25419. uvs.push(textureCoordinate.x, textureCoordinate.y);
  25420. // And create indices for two triangles.
  25421. var nextI = (i + 1) % stride;
  25422. var nextJ = (j + 1) % stride;
  25423. indices.push(i * stride + j);
  25424. indices.push(i * stride + nextJ);
  25425. indices.push(nextI * stride + j);
  25426. indices.push(i * stride + nextJ);
  25427. indices.push(nextI * stride + nextJ);
  25428. indices.push(nextI * stride + j);
  25429. }
  25430. }
  25431. // Sides
  25432. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25433. // Result
  25434. var vertexData = new VertexData();
  25435. vertexData.indices = indices;
  25436. vertexData.positions = positions;
  25437. vertexData.normals = normals;
  25438. vertexData.uvs = uvs;
  25439. return vertexData;
  25440. };
  25441. VertexData.CreateLineSystem = function (options) {
  25442. var indices = [];
  25443. var positions = [];
  25444. var lines = options.lines;
  25445. var idx = 0;
  25446. for (var l = 0; l < lines.length; l++) {
  25447. var points = lines[l];
  25448. for (var index = 0; index < points.length; index++) {
  25449. positions.push(points[index].x, points[index].y, points[index].z);
  25450. if (index > 0) {
  25451. indices.push(idx - 1);
  25452. indices.push(idx);
  25453. }
  25454. idx++;
  25455. }
  25456. }
  25457. var vertexData = new VertexData();
  25458. vertexData.indices = indices;
  25459. vertexData.positions = positions;
  25460. return vertexData;
  25461. };
  25462. VertexData.CreateDashedLines = function (options) {
  25463. var dashSize = options.dashSize || 3;
  25464. var gapSize = options.gapSize || 1;
  25465. var dashNb = options.dashNb || 200;
  25466. var points = options.points;
  25467. var positions = new Array();
  25468. var indices = new Array();
  25469. var curvect = BABYLON.Vector3.Zero();
  25470. var lg = 0;
  25471. var nb = 0;
  25472. var shft = 0;
  25473. var dashshft = 0;
  25474. var curshft = 0;
  25475. var idx = 0;
  25476. var i = 0;
  25477. for (i = 0; i < points.length - 1; i++) {
  25478. points[i + 1].subtractToRef(points[i], curvect);
  25479. lg += curvect.length();
  25480. }
  25481. shft = lg / dashNb;
  25482. dashshft = dashSize * shft / (dashSize + gapSize);
  25483. for (i = 0; i < points.length - 1; i++) {
  25484. points[i + 1].subtractToRef(points[i], curvect);
  25485. nb = Math.floor(curvect.length() / shft);
  25486. curvect.normalize();
  25487. for (var j = 0; j < nb; j++) {
  25488. curshft = shft * j;
  25489. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  25490. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  25491. indices.push(idx, idx + 1);
  25492. idx += 2;
  25493. }
  25494. }
  25495. // Result
  25496. var vertexData = new VertexData();
  25497. vertexData.positions = positions;
  25498. vertexData.indices = indices;
  25499. return vertexData;
  25500. };
  25501. VertexData.CreateGround = function (options) {
  25502. var indices = [];
  25503. var positions = [];
  25504. var normals = [];
  25505. var uvs = [];
  25506. var row, col;
  25507. var width = options.width || 1;
  25508. var height = options.height || 1;
  25509. var subdivisions = options.subdivisions || 1;
  25510. for (row = 0; row <= subdivisions; row++) {
  25511. for (col = 0; col <= subdivisions; col++) {
  25512. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  25513. var normal = new BABYLON.Vector3(0, 1.0, 0);
  25514. positions.push(position.x, position.y, position.z);
  25515. normals.push(normal.x, normal.y, normal.z);
  25516. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  25517. }
  25518. }
  25519. for (row = 0; row < subdivisions; row++) {
  25520. for (col = 0; col < subdivisions; col++) {
  25521. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  25522. indices.push(col + 1 + row * (subdivisions + 1));
  25523. indices.push(col + row * (subdivisions + 1));
  25524. indices.push(col + (row + 1) * (subdivisions + 1));
  25525. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  25526. indices.push(col + row * (subdivisions + 1));
  25527. }
  25528. }
  25529. // Result
  25530. var vertexData = new VertexData();
  25531. vertexData.indices = indices;
  25532. vertexData.positions = positions;
  25533. vertexData.normals = normals;
  25534. vertexData.uvs = uvs;
  25535. return vertexData;
  25536. };
  25537. VertexData.CreateTiledGround = function (options) {
  25538. var xmin = options.xmin;
  25539. var zmin = options.zmin;
  25540. var xmax = options.xmax;
  25541. var zmax = options.zmax;
  25542. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  25543. var precision = options.precision || { w: 1, h: 1 };
  25544. var indices = [];
  25545. var positions = [];
  25546. var normals = [];
  25547. var uvs = [];
  25548. var row, col, tileRow, tileCol;
  25549. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  25550. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  25551. precision.w = (precision.w < 1) ? 1 : precision.w;
  25552. precision.h = (precision.h < 1) ? 1 : precision.h;
  25553. var tileSize = {
  25554. 'w': (xmax - xmin) / subdivisions.w,
  25555. 'h': (zmax - zmin) / subdivisions.h
  25556. };
  25557. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  25558. // Indices
  25559. var base = positions.length / 3;
  25560. var rowLength = precision.w + 1;
  25561. for (row = 0; row < precision.h; row++) {
  25562. for (col = 0; col < precision.w; col++) {
  25563. var square = [
  25564. base + col + row * rowLength,
  25565. base + (col + 1) + row * rowLength,
  25566. base + (col + 1) + (row + 1) * rowLength,
  25567. base + col + (row + 1) * rowLength
  25568. ];
  25569. indices.push(square[1]);
  25570. indices.push(square[2]);
  25571. indices.push(square[3]);
  25572. indices.push(square[0]);
  25573. indices.push(square[1]);
  25574. indices.push(square[3]);
  25575. }
  25576. }
  25577. // Position, normals and uvs
  25578. var position = BABYLON.Vector3.Zero();
  25579. var normal = new BABYLON.Vector3(0, 1.0, 0);
  25580. for (row = 0; row <= precision.h; row++) {
  25581. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  25582. for (col = 0; col <= precision.w; col++) {
  25583. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  25584. position.y = 0;
  25585. positions.push(position.x, position.y, position.z);
  25586. normals.push(normal.x, normal.y, normal.z);
  25587. uvs.push(col / precision.w, row / precision.h);
  25588. }
  25589. }
  25590. }
  25591. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  25592. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  25593. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  25594. }
  25595. }
  25596. // Result
  25597. var vertexData = new VertexData();
  25598. vertexData.indices = indices;
  25599. vertexData.positions = positions;
  25600. vertexData.normals = normals;
  25601. vertexData.uvs = uvs;
  25602. return vertexData;
  25603. };
  25604. VertexData.CreateGroundFromHeightMap = function (options) {
  25605. var indices = [];
  25606. var positions = [];
  25607. var normals = [];
  25608. var uvs = [];
  25609. var row, col;
  25610. // Vertices
  25611. for (row = 0; row <= options.subdivisions; row++) {
  25612. for (col = 0; col <= options.subdivisions; col++) {
  25613. 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));
  25614. // Compute height
  25615. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  25616. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  25617. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  25618. var r = options.buffer[pos] / 255.0;
  25619. var g = options.buffer[pos + 1] / 255.0;
  25620. var b = options.buffer[pos + 2] / 255.0;
  25621. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  25622. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  25623. // Add vertex
  25624. positions.push(position.x, position.y, position.z);
  25625. normals.push(0, 0, 0);
  25626. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  25627. }
  25628. }
  25629. // Indices
  25630. for (row = 0; row < options.subdivisions; row++) {
  25631. for (col = 0; col < options.subdivisions; col++) {
  25632. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  25633. indices.push(col + 1 + row * (options.subdivisions + 1));
  25634. indices.push(col + row * (options.subdivisions + 1));
  25635. indices.push(col + (row + 1) * (options.subdivisions + 1));
  25636. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  25637. indices.push(col + row * (options.subdivisions + 1));
  25638. }
  25639. }
  25640. // Normals
  25641. VertexData.ComputeNormals(positions, indices, normals);
  25642. // Result
  25643. var vertexData = new VertexData();
  25644. vertexData.indices = indices;
  25645. vertexData.positions = positions;
  25646. vertexData.normals = normals;
  25647. vertexData.uvs = uvs;
  25648. return vertexData;
  25649. };
  25650. VertexData.CreatePlane = function (options) {
  25651. var indices = [];
  25652. var positions = [];
  25653. var normals = [];
  25654. var uvs = [];
  25655. var width = options.width || options.size || 1;
  25656. var height = options.height || options.size || 1;
  25657. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25658. // Vertices
  25659. var halfWidth = width / 2.0;
  25660. var halfHeight = height / 2.0;
  25661. positions.push(-halfWidth, -halfHeight, 0);
  25662. normals.push(0, 0, -1.0);
  25663. uvs.push(0.0, 0.0);
  25664. positions.push(halfWidth, -halfHeight, 0);
  25665. normals.push(0, 0, -1.0);
  25666. uvs.push(1.0, 0.0);
  25667. positions.push(halfWidth, halfHeight, 0);
  25668. normals.push(0, 0, -1.0);
  25669. uvs.push(1.0, 1.0);
  25670. positions.push(-halfWidth, halfHeight, 0);
  25671. normals.push(0, 0, -1.0);
  25672. uvs.push(0.0, 1.0);
  25673. // Indices
  25674. indices.push(0);
  25675. indices.push(1);
  25676. indices.push(2);
  25677. indices.push(0);
  25678. indices.push(2);
  25679. indices.push(3);
  25680. // Sides
  25681. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25682. // Result
  25683. var vertexData = new VertexData();
  25684. vertexData.indices = indices;
  25685. vertexData.positions = positions;
  25686. vertexData.normals = normals;
  25687. vertexData.uvs = uvs;
  25688. return vertexData;
  25689. };
  25690. VertexData.CreateDisc = function (options) {
  25691. var positions = [];
  25692. var indices = [];
  25693. var normals = [];
  25694. var uvs = [];
  25695. var radius = options.radius || 0.5;
  25696. var tessellation = options.tessellation || 64;
  25697. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  25698. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25699. // positions and uvs
  25700. positions.push(0, 0, 0); // disc center first
  25701. uvs.push(0.5, 0.5);
  25702. var theta = Math.PI * 2 * arc;
  25703. var step = theta / tessellation;
  25704. for (var a = 0; a < theta; a += step) {
  25705. var x = Math.cos(a);
  25706. var y = Math.sin(a);
  25707. var u = (x + 1) / 2;
  25708. var v = (1 - y) / 2;
  25709. positions.push(radius * x, radius * y, 0);
  25710. uvs.push(u, v);
  25711. }
  25712. if (arc === 1) {
  25713. positions.push(positions[3], positions[4], positions[5]); // close the circle
  25714. uvs.push(uvs[2], uvs[3]);
  25715. }
  25716. //indices
  25717. var vertexNb = positions.length / 3;
  25718. for (var i = 1; i < vertexNb - 1; i++) {
  25719. indices.push(i + 1, 0, i);
  25720. }
  25721. // result
  25722. VertexData.ComputeNormals(positions, indices, normals);
  25723. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25724. var vertexData = new VertexData();
  25725. vertexData.indices = indices;
  25726. vertexData.positions = positions;
  25727. vertexData.normals = normals;
  25728. vertexData.uvs = uvs;
  25729. return vertexData;
  25730. };
  25731. VertexData.CreateIcoSphere = function (options) {
  25732. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25733. var radius = options.radius || 1;
  25734. var flat = (options.flat === undefined) ? true : options.flat;
  25735. var subdivisions = options.subdivisions || 4;
  25736. var radiusX = options.radiusX || radius;
  25737. var radiusY = options.radiusY || radius;
  25738. var radiusZ = options.radiusZ || radius;
  25739. var t = (1 + Math.sqrt(5)) / 2;
  25740. // 12 vertex x,y,z
  25741. var ico_vertices = [
  25742. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  25743. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  25744. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  25745. ];
  25746. // index of 3 vertex makes a face of icopshere
  25747. var ico_indices = [
  25748. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  25749. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  25750. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  25751. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  25752. ];
  25753. // vertex for uv have aliased position, not for UV
  25754. var vertices_unalias_id = [
  25755. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  25756. // vertex alias
  25757. 0,
  25758. 2,
  25759. 3,
  25760. 3,
  25761. 3,
  25762. 4,
  25763. 7,
  25764. 8,
  25765. 9,
  25766. 9,
  25767. 10,
  25768. 11 // 23: B + 12
  25769. ];
  25770. // uv as integer step (not pixels !)
  25771. var ico_vertexuv = [
  25772. 5, 1, 3, 1, 6, 4, 0, 0,
  25773. 5, 3, 4, 2, 2, 2, 4, 0,
  25774. 2, 0, 1, 1, 6, 0, 6, 2,
  25775. // vertex alias (for same vertex on different faces)
  25776. 0, 4,
  25777. 3, 3,
  25778. 4, 4,
  25779. 3, 1,
  25780. 4, 2,
  25781. 4, 4,
  25782. 0, 2,
  25783. 1, 1,
  25784. 2, 2,
  25785. 3, 3,
  25786. 1, 3,
  25787. 2, 4 // 23: B + 12
  25788. ];
  25789. // Vertices[0, 1, ...9, A, B] : position on UV plane
  25790. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  25791. // First island of uv mapping
  25792. // v = 4h 3+ 2
  25793. // v = 3h 9+ 4
  25794. // v = 2h 9+ 5 B
  25795. // v = 1h 9 1 0
  25796. // v = 0h 3 8 7 A
  25797. // u = 0 1 2 3 4 5 6 *a
  25798. // Second island of uv mapping
  25799. // v = 4h 0+ B+ 4+
  25800. // v = 3h A+ 2+
  25801. // v = 2h 7+ 6 3+
  25802. // v = 1h 8+ 3+
  25803. // v = 0h
  25804. // u = 0 1 2 3 4 5 6 *a
  25805. // Face layout on texture UV mapping
  25806. // ============
  25807. // \ 4 /\ 16 / ======
  25808. // \ / \ / /\ 11 /
  25809. // \/ 7 \/ / \ /
  25810. // ======= / 10 \/
  25811. // /\ 17 /\ =======
  25812. // / \ / \ \ 15 /\
  25813. // / 8 \/ 12 \ \ / \
  25814. // ============ \/ 6 \
  25815. // \ 18 /\ ============
  25816. // \ / \ \ 5 /\ 0 /
  25817. // \/ 13 \ \ / \ /
  25818. // ======= \/ 1 \/
  25819. // =============
  25820. // /\ 19 /\ 2 /\
  25821. // / \ / \ / \
  25822. // / 14 \/ 9 \/ 3 \
  25823. // ===================
  25824. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  25825. var ustep = 138 / 1024;
  25826. var vstep = 239 / 1024;
  25827. var uoffset = 60 / 1024;
  25828. var voffset = 26 / 1024;
  25829. // Second island should have margin, not to touch the first island
  25830. // avoid any borderline artefact in pixel rounding
  25831. var island_u_offset = -40 / 1024;
  25832. var island_v_offset = +20 / 1024;
  25833. // face is either island 0 or 1 :
  25834. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  25835. var island = [
  25836. 0, 0, 0, 0, 1,
  25837. 0, 0, 1, 1, 0,
  25838. 0, 0, 1, 1, 0,
  25839. 0, 1, 1, 1, 0 // 15 - 19
  25840. ];
  25841. var indices = [];
  25842. var positions = [];
  25843. var normals = [];
  25844. var uvs = [];
  25845. var current_indice = 0;
  25846. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  25847. var face_vertex_pos = new Array(3);
  25848. var face_vertex_uv = new Array(3);
  25849. var v012;
  25850. for (v012 = 0; v012 < 3; v012++) {
  25851. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  25852. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  25853. }
  25854. // create all with normals
  25855. for (var face = 0; face < 20; face++) {
  25856. // 3 vertex per face
  25857. for (v012 = 0; v012 < 3; v012++) {
  25858. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  25859. var v_id = ico_indices[3 * face + v012];
  25860. // vertex have 3D position (x,y,z)
  25861. 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]);
  25862. // Normalize to get normal, then scale to radius
  25863. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  25864. // uv Coordinates from vertex ID
  25865. 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);
  25866. }
  25867. // Subdivide the face (interpolate pos, norm, uv)
  25868. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  25869. // - norm is linear interpolation of vertex corner normal
  25870. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  25871. // - uv is linear interpolation
  25872. //
  25873. // Topology is as below for sub-divide by 2
  25874. // vertex shown as v0,v1,v2
  25875. // interp index is i1 to progress in range [v0,v1[
  25876. // interp index is i2 to progress in range [v0,v2[
  25877. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  25878. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  25879. //
  25880. //
  25881. // i2 v2
  25882. // ^ ^
  25883. // / / \
  25884. // / / \
  25885. // / / \
  25886. // / / (0,1) \
  25887. // / #---------\
  25888. // / / \ (0,0)'/ \
  25889. // / / \ / \
  25890. // / / \ / \
  25891. // / / (0,0) \ / (1,0) \
  25892. // / #---------#---------\
  25893. // v0 v1
  25894. //
  25895. // --------------------> i1
  25896. //
  25897. // interp of (i1,i2):
  25898. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  25899. // along i1 : lerp(x0,x1, i1/(S-i2))
  25900. //
  25901. // centroid of triangle is needed to get help normal computation
  25902. // (c1,c2) are used for centroid location
  25903. var interp_vertex = function (i1, i2, c1, c2) {
  25904. // vertex is interpolated from
  25905. // - face_vertex_pos[0..2]
  25906. // - face_vertex_uv[0..2]
  25907. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  25908. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  25909. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  25910. pos_interp.normalize();
  25911. var vertex_normal;
  25912. if (flat) {
  25913. // in flat mode, recalculate normal as face centroid normal
  25914. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  25915. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  25916. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  25917. }
  25918. else {
  25919. // in smooth mode, recalculate normal from each single vertex position
  25920. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  25921. }
  25922. // Vertex normal need correction due to X,Y,Z radius scaling
  25923. vertex_normal.x /= radiusX;
  25924. vertex_normal.y /= radiusY;
  25925. vertex_normal.z /= radiusZ;
  25926. vertex_normal.normalize();
  25927. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  25928. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  25929. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  25930. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  25931. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  25932. uvs.push(uv_interp.x, uv_interp.y);
  25933. // push each vertex has member of a face
  25934. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  25935. indices.push(current_indice);
  25936. current_indice++;
  25937. };
  25938. for (var i2 = 0; i2 < subdivisions; i2++) {
  25939. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  25940. // face : (i1,i2) for /\ :
  25941. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  25942. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  25943. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  25944. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  25945. if (i1 + i2 + 1 < subdivisions) {
  25946. // face : (i1,i2)' for \/ :
  25947. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  25948. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  25949. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  25950. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  25951. }
  25952. }
  25953. }
  25954. }
  25955. // Sides
  25956. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25957. // Result
  25958. var vertexData = new VertexData();
  25959. vertexData.indices = indices;
  25960. vertexData.positions = positions;
  25961. vertexData.normals = normals;
  25962. vertexData.uvs = uvs;
  25963. return vertexData;
  25964. };
  25965. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  25966. VertexData.CreatePolyhedron = function (options) {
  25967. // provided polyhedron types :
  25968. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  25969. // 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)
  25970. var polyhedra = [];
  25971. 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]] };
  25972. 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]] };
  25973. polyhedra[2] = {
  25974. 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]],
  25975. 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]]
  25976. };
  25977. polyhedra[3] = {
  25978. 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]],
  25979. 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]]
  25980. };
  25981. polyhedra[4] = {
  25982. 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]],
  25983. 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]]
  25984. };
  25985. 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]] };
  25986. 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]] };
  25987. 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]] };
  25988. 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]] };
  25989. 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]] };
  25990. 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]] };
  25991. 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]] };
  25992. 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]] };
  25993. 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]] };
  25994. polyhedra[14] = {
  25995. 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]],
  25996. 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]]
  25997. };
  25998. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  25999. var size = options.size;
  26000. var sizeX = options.sizeX || size || 1;
  26001. var sizeY = options.sizeY || size || 1;
  26002. var sizeZ = options.sizeZ || size || 1;
  26003. var data = options.custom || polyhedra[type];
  26004. var nbfaces = data.face.length;
  26005. var faceUV = options.faceUV || new Array(nbfaces);
  26006. var faceColors = options.faceColors;
  26007. var flat = (options.flat === undefined) ? true : options.flat;
  26008. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26009. var positions = [];
  26010. var indices = [];
  26011. var normals = [];
  26012. var uvs = [];
  26013. var colors = [];
  26014. var index = 0;
  26015. var faceIdx = 0; // face cursor in the array "indexes"
  26016. var indexes = [];
  26017. var i = 0;
  26018. var f = 0;
  26019. var u, v, ang, x, y, tmp;
  26020. // default face colors and UV if undefined
  26021. if (flat) {
  26022. for (f = 0; f < nbfaces; f++) {
  26023. if (faceColors && faceColors[f] === undefined) {
  26024. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  26025. }
  26026. if (faceUV && faceUV[f] === undefined) {
  26027. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  26028. }
  26029. }
  26030. }
  26031. if (!flat) {
  26032. for (i = 0; i < data.vertex.length; i++) {
  26033. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  26034. uvs.push(0, 0);
  26035. }
  26036. for (f = 0; f < nbfaces; f++) {
  26037. for (i = 0; i < data.face[f].length - 2; i++) {
  26038. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  26039. }
  26040. }
  26041. }
  26042. else {
  26043. for (f = 0; f < nbfaces; f++) {
  26044. var fl = data.face[f].length; // number of vertices of the current face
  26045. ang = 2 * Math.PI / fl;
  26046. x = 0.5 * Math.tan(ang / 2);
  26047. y = 0.5;
  26048. // positions, uvs, colors
  26049. for (i = 0; i < fl; i++) {
  26050. // positions
  26051. 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);
  26052. indexes.push(index);
  26053. index++;
  26054. // uvs
  26055. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  26056. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  26057. uvs.push(u, v);
  26058. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  26059. y = x * Math.sin(ang) + y * Math.cos(ang);
  26060. x = tmp;
  26061. // colors
  26062. if (faceColors) {
  26063. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  26064. }
  26065. }
  26066. // indices from indexes
  26067. for (i = 0; i < fl - 2; i++) {
  26068. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  26069. }
  26070. faceIdx += fl;
  26071. }
  26072. }
  26073. VertexData.ComputeNormals(positions, indices, normals);
  26074. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26075. var vertexData = new VertexData();
  26076. vertexData.positions = positions;
  26077. vertexData.indices = indices;
  26078. vertexData.normals = normals;
  26079. vertexData.uvs = uvs;
  26080. if (faceColors && flat) {
  26081. vertexData.colors = colors;
  26082. }
  26083. return vertexData;
  26084. };
  26085. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  26086. VertexData.CreateTorusKnot = function (options) {
  26087. var indices = [];
  26088. var positions = [];
  26089. var normals = [];
  26090. var uvs = [];
  26091. var radius = options.radius || 2;
  26092. var tube = options.tube || 0.5;
  26093. var radialSegments = options.radialSegments || 32;
  26094. var tubularSegments = options.tubularSegments || 32;
  26095. var p = options.p || 2;
  26096. var q = options.q || 3;
  26097. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26098. // Helper
  26099. var getPos = function (angle) {
  26100. var cu = Math.cos(angle);
  26101. var su = Math.sin(angle);
  26102. var quOverP = q / p * angle;
  26103. var cs = Math.cos(quOverP);
  26104. var tx = radius * (2 + cs) * 0.5 * cu;
  26105. var ty = radius * (2 + cs) * su * 0.5;
  26106. var tz = radius * Math.sin(quOverP) * 0.5;
  26107. return new BABYLON.Vector3(tx, ty, tz);
  26108. };
  26109. // Vertices
  26110. var i;
  26111. var j;
  26112. for (i = 0; i <= radialSegments; i++) {
  26113. var modI = i % radialSegments;
  26114. var u = modI / radialSegments * 2 * p * Math.PI;
  26115. var p1 = getPos(u);
  26116. var p2 = getPos(u + 0.01);
  26117. var tang = p2.subtract(p1);
  26118. var n = p2.add(p1);
  26119. var bitan = BABYLON.Vector3.Cross(tang, n);
  26120. n = BABYLON.Vector3.Cross(bitan, tang);
  26121. bitan.normalize();
  26122. n.normalize();
  26123. for (j = 0; j < tubularSegments; j++) {
  26124. var modJ = j % tubularSegments;
  26125. var v = modJ / tubularSegments * 2 * Math.PI;
  26126. var cx = -tube * Math.cos(v);
  26127. var cy = tube * Math.sin(v);
  26128. positions.push(p1.x + cx * n.x + cy * bitan.x);
  26129. positions.push(p1.y + cx * n.y + cy * bitan.y);
  26130. positions.push(p1.z + cx * n.z + cy * bitan.z);
  26131. uvs.push(i / radialSegments);
  26132. uvs.push(j / tubularSegments);
  26133. }
  26134. }
  26135. for (i = 0; i < radialSegments; i++) {
  26136. for (j = 0; j < tubularSegments; j++) {
  26137. var jNext = (j + 1) % tubularSegments;
  26138. var a = i * tubularSegments + j;
  26139. var b = (i + 1) * tubularSegments + j;
  26140. var c = (i + 1) * tubularSegments + jNext;
  26141. var d = i * tubularSegments + jNext;
  26142. indices.push(d);
  26143. indices.push(b);
  26144. indices.push(a);
  26145. indices.push(d);
  26146. indices.push(c);
  26147. indices.push(b);
  26148. }
  26149. }
  26150. // Normals
  26151. VertexData.ComputeNormals(positions, indices, normals);
  26152. // Sides
  26153. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26154. // Result
  26155. var vertexData = new VertexData();
  26156. vertexData.indices = indices;
  26157. vertexData.positions = positions;
  26158. vertexData.normals = normals;
  26159. vertexData.uvs = uvs;
  26160. return vertexData;
  26161. };
  26162. // Tools
  26163. /**
  26164. * @param {any} - positions (number[] or Float32Array)
  26165. * @param {any} - indices (number[] or Uint16Array)
  26166. * @param {any} - normals (number[] or Float32Array)
  26167. */
  26168. VertexData.ComputeNormals = function (positions, indices, normals) {
  26169. var index = 0;
  26170. var p1p2x = 0.0;
  26171. var p1p2y = 0.0;
  26172. var p1p2z = 0.0;
  26173. var p3p2x = 0.0;
  26174. var p3p2y = 0.0;
  26175. var p3p2z = 0.0;
  26176. var faceNormalx = 0.0;
  26177. var faceNormaly = 0.0;
  26178. var faceNormalz = 0.0;
  26179. var length = 0.0;
  26180. var i1 = 0;
  26181. var i2 = 0;
  26182. var i3 = 0;
  26183. for (index = 0; index < positions.length; index++) {
  26184. normals[index] = 0.0;
  26185. }
  26186. // indice triplet = 1 face
  26187. var nbFaces = indices.length / 3;
  26188. for (index = 0; index < nbFaces; index++) {
  26189. i1 = indices[index * 3]; // get the indexes of each vertex of the face
  26190. i2 = indices[index * 3 + 1];
  26191. i3 = indices[index * 3 + 2];
  26192. p1p2x = positions[i1 * 3] - positions[i2 * 3]; // compute two vectors per face
  26193. p1p2y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  26194. p1p2z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  26195. p3p2x = positions[i3 * 3] - positions[i2 * 3];
  26196. p3p2y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  26197. p3p2z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  26198. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y; // compute the face normal with cross product
  26199. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  26200. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  26201. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  26202. length = (length === 0) ? 1.0 : length;
  26203. faceNormalx /= length; // normalize this normal
  26204. faceNormaly /= length;
  26205. faceNormalz /= length;
  26206. normals[i1 * 3] += faceNormalx; // accumulate all the normals per face
  26207. normals[i1 * 3 + 1] += faceNormaly;
  26208. normals[i1 * 3 + 2] += faceNormalz;
  26209. normals[i2 * 3] += faceNormalx;
  26210. normals[i2 * 3 + 1] += faceNormaly;
  26211. normals[i2 * 3 + 2] += faceNormalz;
  26212. normals[i3 * 3] += faceNormalx;
  26213. normals[i3 * 3 + 1] += faceNormaly;
  26214. normals[i3 * 3 + 2] += faceNormalz;
  26215. }
  26216. // last normalization of each normal
  26217. for (index = 0; index < normals.length / 3; index++) {
  26218. faceNormalx = normals[index * 3];
  26219. faceNormaly = normals[index * 3 + 1];
  26220. faceNormalz = normals[index * 3 + 2];
  26221. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  26222. length = (length === 0) ? 1.0 : length;
  26223. faceNormalx /= length;
  26224. faceNormaly /= length;
  26225. faceNormalz /= length;
  26226. normals[index * 3] = faceNormalx;
  26227. normals[index * 3 + 1] = faceNormaly;
  26228. normals[index * 3 + 2] = faceNormalz;
  26229. }
  26230. };
  26231. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  26232. var li = indices.length;
  26233. var ln = normals.length;
  26234. var i;
  26235. var n;
  26236. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26237. switch (sideOrientation) {
  26238. case BABYLON.Mesh.FRONTSIDE:
  26239. // nothing changed
  26240. break;
  26241. case BABYLON.Mesh.BACKSIDE:
  26242. var tmp;
  26243. // indices
  26244. for (i = 0; i < li; i += 3) {
  26245. tmp = indices[i];
  26246. indices[i] = indices[i + 2];
  26247. indices[i + 2] = tmp;
  26248. }
  26249. // normals
  26250. for (n = 0; n < ln; n++) {
  26251. normals[n] = -normals[n];
  26252. }
  26253. break;
  26254. case BABYLON.Mesh.DOUBLESIDE:
  26255. // positions
  26256. var lp = positions.length;
  26257. var l = lp / 3;
  26258. for (var p = 0; p < lp; p++) {
  26259. positions[lp + p] = positions[p];
  26260. }
  26261. // indices
  26262. for (i = 0; i < li; i += 3) {
  26263. indices[i + li] = indices[i + 2] + l;
  26264. indices[i + 1 + li] = indices[i + 1] + l;
  26265. indices[i + 2 + li] = indices[i] + l;
  26266. }
  26267. // normals
  26268. for (n = 0; n < ln; n++) {
  26269. normals[ln + n] = -normals[n];
  26270. }
  26271. // uvs
  26272. var lu = uvs.length;
  26273. for (var u = 0; u < lu; u++) {
  26274. uvs[u + lu] = uvs[u];
  26275. }
  26276. break;
  26277. }
  26278. };
  26279. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  26280. var vertexData = new VertexData();
  26281. // positions
  26282. var positions = parsedVertexData.positions;
  26283. if (positions) {
  26284. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  26285. }
  26286. // normals
  26287. var normals = parsedVertexData.normals;
  26288. if (normals) {
  26289. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  26290. }
  26291. // uvs
  26292. var uvs = parsedVertexData.uvs;
  26293. if (uvs) {
  26294. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  26295. }
  26296. // uv2s
  26297. var uv2s = parsedVertexData.uv2s;
  26298. if (uv2s) {
  26299. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  26300. }
  26301. // uv3s
  26302. var uv3s = parsedVertexData.uv3s;
  26303. if (uv3s) {
  26304. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  26305. }
  26306. // uv4s
  26307. var uv4s = parsedVertexData.uv4s;
  26308. if (uv4s) {
  26309. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  26310. }
  26311. // uv5s
  26312. var uv5s = parsedVertexData.uv5s;
  26313. if (uv5s) {
  26314. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  26315. }
  26316. // uv6s
  26317. var uv6s = parsedVertexData.uv6s;
  26318. if (uv6s) {
  26319. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  26320. }
  26321. // colors
  26322. var colors = parsedVertexData.colors;
  26323. if (colors) {
  26324. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  26325. }
  26326. // matricesIndices
  26327. var matricesIndices = parsedVertexData.matricesIndices;
  26328. if (matricesIndices) {
  26329. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  26330. }
  26331. // matricesWeights
  26332. var matricesWeights = parsedVertexData.matricesWeights;
  26333. if (matricesWeights) {
  26334. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  26335. }
  26336. // indices
  26337. var indices = parsedVertexData.indices;
  26338. if (indices) {
  26339. vertexData.indices = indices;
  26340. }
  26341. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  26342. };
  26343. return VertexData;
  26344. })();
  26345. BABYLON.VertexData = VertexData;
  26346. })(BABYLON || (BABYLON = {}));
  26347. var BABYLON;
  26348. (function (BABYLON) {
  26349. var Tags = (function () {
  26350. function Tags() {
  26351. }
  26352. Tags.EnableFor = function (obj) {
  26353. obj._tags = obj._tags || {};
  26354. obj.hasTags = function () {
  26355. return Tags.HasTags(obj);
  26356. };
  26357. obj.addTags = function (tagsString) {
  26358. return Tags.AddTagsTo(obj, tagsString);
  26359. };
  26360. obj.removeTags = function (tagsString) {
  26361. return Tags.RemoveTagsFrom(obj, tagsString);
  26362. };
  26363. obj.matchesTagsQuery = function (tagsQuery) {
  26364. return Tags.MatchesQuery(obj, tagsQuery);
  26365. };
  26366. };
  26367. Tags.DisableFor = function (obj) {
  26368. delete obj._tags;
  26369. delete obj.hasTags;
  26370. delete obj.addTags;
  26371. delete obj.removeTags;
  26372. delete obj.matchesTagsQuery;
  26373. };
  26374. Tags.HasTags = function (obj) {
  26375. if (!obj._tags) {
  26376. return false;
  26377. }
  26378. return !BABYLON.Tools.IsEmpty(obj._tags);
  26379. };
  26380. Tags.GetTags = function (obj, asString) {
  26381. if (asString === void 0) { asString = true; }
  26382. if (!obj._tags) {
  26383. return null;
  26384. }
  26385. if (asString) {
  26386. var tagsArray = [];
  26387. for (var tag in obj._tags) {
  26388. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  26389. tagsArray.push(tag);
  26390. }
  26391. }
  26392. return tagsArray.join(" ");
  26393. }
  26394. else {
  26395. return obj._tags;
  26396. }
  26397. };
  26398. // the tags 'true' and 'false' are reserved and cannot be used as tags
  26399. // a tag cannot start with '||', '&&', and '!'
  26400. // it cannot contain whitespaces
  26401. Tags.AddTagsTo = function (obj, tagsString) {
  26402. if (!tagsString) {
  26403. return;
  26404. }
  26405. if (typeof tagsString !== "string") {
  26406. return;
  26407. }
  26408. var tags = tagsString.split(" ");
  26409. for (var t in tags) {
  26410. Tags._AddTagTo(obj, tags[t]);
  26411. }
  26412. };
  26413. Tags._AddTagTo = function (obj, tag) {
  26414. tag = tag.trim();
  26415. if (tag === "" || tag === "true" || tag === "false") {
  26416. return;
  26417. }
  26418. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  26419. return;
  26420. }
  26421. Tags.EnableFor(obj);
  26422. obj._tags[tag] = true;
  26423. };
  26424. Tags.RemoveTagsFrom = function (obj, tagsString) {
  26425. if (!Tags.HasTags(obj)) {
  26426. return;
  26427. }
  26428. var tags = tagsString.split(" ");
  26429. for (var t in tags) {
  26430. Tags._RemoveTagFrom(obj, tags[t]);
  26431. }
  26432. };
  26433. Tags._RemoveTagFrom = function (obj, tag) {
  26434. delete obj._tags[tag];
  26435. };
  26436. Tags.MatchesQuery = function (obj, tagsQuery) {
  26437. if (tagsQuery === undefined) {
  26438. return true;
  26439. }
  26440. if (tagsQuery === "") {
  26441. return Tags.HasTags(obj);
  26442. }
  26443. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  26444. };
  26445. return Tags;
  26446. })();
  26447. BABYLON.Tags = Tags;
  26448. })(BABYLON || (BABYLON = {}));
  26449. var BABYLON;
  26450. (function (BABYLON) {
  26451. var Internals;
  26452. (function (Internals) {
  26453. var AndOrNotEvaluator = (function () {
  26454. function AndOrNotEvaluator() {
  26455. }
  26456. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  26457. if (!query.match(/\([^\(\)]*\)/g)) {
  26458. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  26459. }
  26460. else {
  26461. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  26462. // remove parenthesis
  26463. r = r.slice(1, r.length - 1);
  26464. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  26465. });
  26466. }
  26467. if (query === "true") {
  26468. return true;
  26469. }
  26470. if (query === "false") {
  26471. return false;
  26472. }
  26473. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  26474. };
  26475. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  26476. evaluateCallback = evaluateCallback || (function (r) {
  26477. return r === "true" ? true : false;
  26478. });
  26479. var result;
  26480. var or = parenthesisContent.split("||");
  26481. for (var i in or) {
  26482. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  26483. var and = ori.split("&&");
  26484. if (and.length > 1) {
  26485. for (var j = 0; j < and.length; ++j) {
  26486. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  26487. if (andj !== "true" && andj !== "false") {
  26488. if (andj[0] === "!") {
  26489. result = !evaluateCallback(andj.substring(1));
  26490. }
  26491. else {
  26492. result = evaluateCallback(andj);
  26493. }
  26494. }
  26495. else {
  26496. result = andj === "true" ? true : false;
  26497. }
  26498. if (!result) {
  26499. ori = "false";
  26500. break;
  26501. }
  26502. }
  26503. }
  26504. if (result || ori === "true") {
  26505. result = true;
  26506. break;
  26507. }
  26508. // result equals false (or undefined)
  26509. if (ori !== "true" && ori !== "false") {
  26510. if (ori[0] === "!") {
  26511. result = !evaluateCallback(ori.substring(1));
  26512. }
  26513. else {
  26514. result = evaluateCallback(ori);
  26515. }
  26516. }
  26517. else {
  26518. result = ori === "true" ? true : false;
  26519. }
  26520. }
  26521. // the whole parenthesis scope is replaced by 'true' or 'false'
  26522. return result ? "true" : "false";
  26523. };
  26524. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  26525. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  26526. // remove whitespaces
  26527. r = r.replace(/[\s]/g, function () { return ""; });
  26528. return r.length % 2 ? "!" : "";
  26529. });
  26530. booleanString = booleanString.trim();
  26531. if (booleanString === "!true") {
  26532. booleanString = "false";
  26533. }
  26534. else if (booleanString === "!false") {
  26535. booleanString = "true";
  26536. }
  26537. return booleanString;
  26538. };
  26539. return AndOrNotEvaluator;
  26540. })();
  26541. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  26542. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  26543. })(BABYLON || (BABYLON = {}));
  26544. var BABYLON;
  26545. (function (BABYLON) {
  26546. var PostProcessRenderPass = (function () {
  26547. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  26548. this._enabled = true;
  26549. this._refCount = 0;
  26550. this._name = name;
  26551. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  26552. this.setRenderList(renderList);
  26553. this._renderTexture.onBeforeRender = beforeRender;
  26554. this._renderTexture.onAfterRender = afterRender;
  26555. this._scene = scene;
  26556. this._renderList = renderList;
  26557. }
  26558. // private
  26559. PostProcessRenderPass.prototype._incRefCount = function () {
  26560. if (this._refCount === 0) {
  26561. this._scene.customRenderTargets.push(this._renderTexture);
  26562. }
  26563. return ++this._refCount;
  26564. };
  26565. PostProcessRenderPass.prototype._decRefCount = function () {
  26566. this._refCount--;
  26567. if (this._refCount <= 0) {
  26568. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  26569. }
  26570. return this._refCount;
  26571. };
  26572. PostProcessRenderPass.prototype._update = function () {
  26573. this.setRenderList(this._renderList);
  26574. };
  26575. // public
  26576. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  26577. this._renderTexture.renderList = renderList;
  26578. };
  26579. PostProcessRenderPass.prototype.getRenderTexture = function () {
  26580. return this._renderTexture;
  26581. };
  26582. return PostProcessRenderPass;
  26583. })();
  26584. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  26585. })(BABYLON || (BABYLON = {}));
  26586. var BABYLON;
  26587. (function (BABYLON) {
  26588. var PostProcessRenderEffect = (function () {
  26589. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  26590. this._engine = engine;
  26591. this._name = name;
  26592. this._singleInstance = singleInstance || true;
  26593. this._getPostProcess = getPostProcess;
  26594. this._cameras = [];
  26595. this._indicesForCamera = [];
  26596. this._postProcesses = {};
  26597. this._renderPasses = {};
  26598. this._renderEffectAsPasses = {};
  26599. }
  26600. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  26601. get: function () {
  26602. for (var index in this._postProcesses) {
  26603. if (!this._postProcesses[index].isSupported) {
  26604. return false;
  26605. }
  26606. }
  26607. return true;
  26608. },
  26609. enumerable: true,
  26610. configurable: true
  26611. });
  26612. PostProcessRenderEffect.prototype._update = function () {
  26613. for (var renderPassName in this._renderPasses) {
  26614. this._renderPasses[renderPassName]._update();
  26615. }
  26616. };
  26617. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  26618. this._renderPasses[renderPass._name] = renderPass;
  26619. this._linkParameters();
  26620. };
  26621. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  26622. delete this._renderPasses[renderPass._name];
  26623. this._linkParameters();
  26624. };
  26625. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  26626. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  26627. this._linkParameters();
  26628. };
  26629. PostProcessRenderEffect.prototype.getPass = function (passName) {
  26630. for (var renderPassName in this._renderPasses) {
  26631. if (renderPassName === passName) {
  26632. return this._renderPasses[passName];
  26633. }
  26634. }
  26635. };
  26636. PostProcessRenderEffect.prototype.emptyPasses = function () {
  26637. this._renderPasses = {};
  26638. this._linkParameters();
  26639. };
  26640. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  26641. var cameraKey;
  26642. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26643. for (var i = 0; i < _cam.length; i++) {
  26644. var camera = _cam[i];
  26645. var cameraName = camera.name;
  26646. if (this._singleInstance) {
  26647. cameraKey = 0;
  26648. }
  26649. else {
  26650. cameraKey = cameraName;
  26651. }
  26652. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  26653. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  26654. if (!this._indicesForCamera[cameraName]) {
  26655. this._indicesForCamera[cameraName] = [];
  26656. }
  26657. this._indicesForCamera[cameraName].push(index);
  26658. if (this._cameras.indexOf(camera) === -1) {
  26659. this._cameras[cameraName] = camera;
  26660. }
  26661. for (var passName in this._renderPasses) {
  26662. this._renderPasses[passName]._incRefCount();
  26663. }
  26664. }
  26665. this._linkParameters();
  26666. };
  26667. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  26668. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26669. for (var i = 0; i < _cam.length; i++) {
  26670. var camera = _cam[i];
  26671. var cameraName = camera.name;
  26672. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  26673. var index = this._cameras.indexOf(cameraName);
  26674. this._indicesForCamera.splice(index, 1);
  26675. this._cameras.splice(index, 1);
  26676. for (var passName in this._renderPasses) {
  26677. this._renderPasses[passName]._decRefCount();
  26678. }
  26679. }
  26680. };
  26681. PostProcessRenderEffect.prototype._enable = function (cameras) {
  26682. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26683. for (var i = 0; i < _cam.length; i++) {
  26684. var camera = _cam[i];
  26685. var cameraName = camera.name;
  26686. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  26687. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  26688. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  26689. }
  26690. }
  26691. for (var passName in this._renderPasses) {
  26692. this._renderPasses[passName]._incRefCount();
  26693. }
  26694. }
  26695. };
  26696. PostProcessRenderEffect.prototype._disable = function (cameras) {
  26697. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26698. for (var i = 0; i < _cam.length; i++) {
  26699. var camera = _cam[i];
  26700. var cameraName = camera.Name;
  26701. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  26702. for (var passName in this._renderPasses) {
  26703. this._renderPasses[passName]._decRefCount();
  26704. }
  26705. }
  26706. };
  26707. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  26708. if (this._singleInstance) {
  26709. return this._postProcesses[0];
  26710. }
  26711. else {
  26712. return this._postProcesses[camera.name];
  26713. }
  26714. };
  26715. PostProcessRenderEffect.prototype._linkParameters = function () {
  26716. var _this = this;
  26717. for (var index in this._postProcesses) {
  26718. if (this.applyParameters) {
  26719. this.applyParameters(this._postProcesses[index]);
  26720. }
  26721. this._postProcesses[index].onBeforeRender = function (effect) {
  26722. _this._linkTextures(effect);
  26723. };
  26724. }
  26725. };
  26726. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  26727. for (var renderPassName in this._renderPasses) {
  26728. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  26729. }
  26730. for (var renderEffectName in this._renderEffectAsPasses) {
  26731. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  26732. }
  26733. };
  26734. return PostProcessRenderEffect;
  26735. })();
  26736. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  26737. })(BABYLON || (BABYLON = {}));
  26738. var BABYLON;
  26739. (function (BABYLON) {
  26740. var PostProcessRenderPipeline = (function () {
  26741. function PostProcessRenderPipeline(engine, name) {
  26742. this._engine = engine;
  26743. this._name = name;
  26744. this._renderEffects = {};
  26745. this._renderEffectsForIsolatedPass = {};
  26746. this._cameras = [];
  26747. }
  26748. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  26749. get: function () {
  26750. for (var renderEffectName in this._renderEffects) {
  26751. if (!this._renderEffects[renderEffectName].isSupported) {
  26752. return false;
  26753. }
  26754. }
  26755. return true;
  26756. },
  26757. enumerable: true,
  26758. configurable: true
  26759. });
  26760. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  26761. this._renderEffects[renderEffect._name] = renderEffect;
  26762. };
  26763. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  26764. var renderEffects = this._renderEffects[renderEffectName];
  26765. if (!renderEffects) {
  26766. return;
  26767. }
  26768. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  26769. };
  26770. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  26771. var renderEffects = this._renderEffects[renderEffectName];
  26772. if (!renderEffects) {
  26773. return;
  26774. }
  26775. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  26776. };
  26777. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  26778. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26779. var indicesToDelete = [];
  26780. var i;
  26781. for (i = 0; i < _cam.length; i++) {
  26782. var camera = _cam[i];
  26783. var cameraName = camera.name;
  26784. if (this._cameras.indexOf(camera) === -1) {
  26785. this._cameras[cameraName] = camera;
  26786. }
  26787. else if (unique) {
  26788. indicesToDelete.push(i);
  26789. }
  26790. }
  26791. for (i = 0; i < indicesToDelete.length; i++) {
  26792. cameras.splice(indicesToDelete[i], 1);
  26793. }
  26794. for (var renderEffectName in this._renderEffects) {
  26795. this._renderEffects[renderEffectName]._attachCameras(_cam);
  26796. }
  26797. };
  26798. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  26799. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26800. for (var renderEffectName in this._renderEffects) {
  26801. this._renderEffects[renderEffectName]._detachCameras(_cam);
  26802. }
  26803. for (var i = 0; i < _cam.length; i++) {
  26804. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  26805. }
  26806. };
  26807. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  26808. var _this = this;
  26809. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26810. var pass = null;
  26811. var renderEffectName;
  26812. for (renderEffectName in this._renderEffects) {
  26813. pass = this._renderEffects[renderEffectName].getPass(passName);
  26814. if (pass != null) {
  26815. break;
  26816. }
  26817. }
  26818. if (pass === null) {
  26819. return;
  26820. }
  26821. for (renderEffectName in this._renderEffects) {
  26822. this._renderEffects[renderEffectName]._disable(_cam);
  26823. }
  26824. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  26825. for (var i = 0; i < _cam.length; i++) {
  26826. var camera = _cam[i];
  26827. var cameraName = camera.name;
  26828. 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); });
  26829. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  26830. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  26831. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  26832. }
  26833. };
  26834. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  26835. var _this = this;
  26836. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26837. for (var i = 0; i < _cam.length; i++) {
  26838. var camera = _cam[i];
  26839. var cameraName = camera.name;
  26840. 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); });
  26841. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  26842. }
  26843. for (var renderEffectName in this._renderEffects) {
  26844. this._renderEffects[renderEffectName]._enable(_cam);
  26845. }
  26846. };
  26847. PostProcessRenderPipeline.prototype._update = function () {
  26848. for (var renderEffectName in this._renderEffects) {
  26849. this._renderEffects[renderEffectName]._update();
  26850. }
  26851. for (var i = 0; i < this._cameras.length; i++) {
  26852. var cameraName = this._cameras[i].name;
  26853. if (this._renderEffectsForIsolatedPass[cameraName]) {
  26854. this._renderEffectsForIsolatedPass[cameraName]._update();
  26855. }
  26856. }
  26857. };
  26858. PostProcessRenderPipeline.prototype.dispose = function () {
  26859. // Must be implemented by children
  26860. };
  26861. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  26862. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  26863. return PostProcessRenderPipeline;
  26864. })();
  26865. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  26866. })(BABYLON || (BABYLON = {}));
  26867. var BABYLON;
  26868. (function (BABYLON) {
  26869. var PostProcessRenderPipelineManager = (function () {
  26870. function PostProcessRenderPipelineManager() {
  26871. this._renderPipelines = {};
  26872. }
  26873. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  26874. this._renderPipelines[renderPipeline._name] = renderPipeline;
  26875. };
  26876. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  26877. var renderPipeline = this._renderPipelines[renderPipelineName];
  26878. if (!renderPipeline) {
  26879. return;
  26880. }
  26881. renderPipeline._attachCameras(cameras, unique);
  26882. };
  26883. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  26884. var renderPipeline = this._renderPipelines[renderPipelineName];
  26885. if (!renderPipeline) {
  26886. return;
  26887. }
  26888. renderPipeline._detachCameras(cameras);
  26889. };
  26890. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  26891. var renderPipeline = this._renderPipelines[renderPipelineName];
  26892. if (!renderPipeline) {
  26893. return;
  26894. }
  26895. renderPipeline._enableEffect(renderEffectName, cameras);
  26896. };
  26897. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  26898. var renderPipeline = this._renderPipelines[renderPipelineName];
  26899. if (!renderPipeline) {
  26900. return;
  26901. }
  26902. renderPipeline._disableEffect(renderEffectName, cameras);
  26903. };
  26904. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  26905. var renderPipeline = this._renderPipelines[renderPipelineName];
  26906. if (!renderPipeline) {
  26907. return;
  26908. }
  26909. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  26910. };
  26911. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  26912. var renderPipeline = this._renderPipelines[renderPipelineName];
  26913. if (!renderPipeline) {
  26914. return;
  26915. }
  26916. renderPipeline._disableDisplayOnlyPass(cameras);
  26917. };
  26918. PostProcessRenderPipelineManager.prototype.update = function () {
  26919. for (var renderPipelineName in this._renderPipelines) {
  26920. var pipeline = this._renderPipelines[renderPipelineName];
  26921. if (!pipeline.isSupported) {
  26922. pipeline.dispose();
  26923. delete this._renderPipelines[renderPipelineName];
  26924. }
  26925. else {
  26926. pipeline._update();
  26927. }
  26928. }
  26929. };
  26930. return PostProcessRenderPipelineManager;
  26931. })();
  26932. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  26933. })(BABYLON || (BABYLON = {}));
  26934. var BABYLON;
  26935. (function (BABYLON) {
  26936. var BoundingBoxRenderer = (function () {
  26937. function BoundingBoxRenderer(scene) {
  26938. this.frontColor = new BABYLON.Color3(1, 1, 1);
  26939. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  26940. this.showBackLines = true;
  26941. this.renderList = new BABYLON.SmartArray(32);
  26942. this._scene = scene;
  26943. }
  26944. BoundingBoxRenderer.prototype._prepareRessources = function () {
  26945. if (this._colorShader) {
  26946. return;
  26947. }
  26948. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  26949. attributes: ["position"],
  26950. uniforms: ["worldViewProjection", "color"]
  26951. });
  26952. var engine = this._scene.getEngine();
  26953. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  26954. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  26955. 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]);
  26956. };
  26957. BoundingBoxRenderer.prototype.reset = function () {
  26958. this.renderList.reset();
  26959. };
  26960. BoundingBoxRenderer.prototype.render = function () {
  26961. if (this.renderList.length === 0) {
  26962. return;
  26963. }
  26964. this._prepareRessources();
  26965. if (!this._colorShader.isReady()) {
  26966. return;
  26967. }
  26968. var engine = this._scene.getEngine();
  26969. engine.setDepthWrite(false);
  26970. this._colorShader._preBind();
  26971. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  26972. var boundingBox = this.renderList.data[boundingBoxIndex];
  26973. var min = boundingBox.minimum;
  26974. var max = boundingBox.maximum;
  26975. var diff = max.subtract(min);
  26976. var median = min.add(diff.scale(0.5));
  26977. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  26978. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  26979. .multiply(boundingBox.getWorldMatrix());
  26980. // VBOs
  26981. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  26982. if (this.showBackLines) {
  26983. // Back
  26984. engine.setDepthFunctionToGreaterOrEqual();
  26985. this._scene.resetCachedMaterial();
  26986. this._colorShader.setColor4("color", this.backColor.toColor4());
  26987. this._colorShader.bind(worldMatrix);
  26988. // Draw order
  26989. engine.draw(false, 0, 24);
  26990. }
  26991. // Front
  26992. engine.setDepthFunctionToLess();
  26993. this._scene.resetCachedMaterial();
  26994. this._colorShader.setColor4("color", this.frontColor.toColor4());
  26995. this._colorShader.bind(worldMatrix);
  26996. // Draw order
  26997. engine.draw(false, 0, 24);
  26998. }
  26999. this._colorShader.unbind();
  27000. engine.setDepthFunctionToLessOrEqual();
  27001. engine.setDepthWrite(true);
  27002. };
  27003. BoundingBoxRenderer.prototype.dispose = function () {
  27004. if (!this._colorShader) {
  27005. return;
  27006. }
  27007. this._colorShader.dispose();
  27008. this._vb.dispose();
  27009. this._scene.getEngine()._releaseBuffer(this._ib);
  27010. };
  27011. return BoundingBoxRenderer;
  27012. })();
  27013. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  27014. })(BABYLON || (BABYLON = {}));
  27015. var BABYLON;
  27016. (function (BABYLON) {
  27017. var Condition = (function () {
  27018. function Condition(actionManager) {
  27019. this._actionManager = actionManager;
  27020. }
  27021. Condition.prototype.isValid = function () {
  27022. return true;
  27023. };
  27024. Condition.prototype._getProperty = function (propertyPath) {
  27025. return this._actionManager._getProperty(propertyPath);
  27026. };
  27027. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  27028. return this._actionManager._getEffectiveTarget(target, propertyPath);
  27029. };
  27030. return Condition;
  27031. })();
  27032. BABYLON.Condition = Condition;
  27033. var ValueCondition = (function (_super) {
  27034. __extends(ValueCondition, _super);
  27035. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  27036. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  27037. _super.call(this, actionManager);
  27038. this.propertyPath = propertyPath;
  27039. this.value = value;
  27040. this.operator = operator;
  27041. this._target = this._getEffectiveTarget(target, this.propertyPath);
  27042. this._property = this._getProperty(this.propertyPath);
  27043. }
  27044. Object.defineProperty(ValueCondition, "IsEqual", {
  27045. get: function () {
  27046. return ValueCondition._IsEqual;
  27047. },
  27048. enumerable: true,
  27049. configurable: true
  27050. });
  27051. Object.defineProperty(ValueCondition, "IsDifferent", {
  27052. get: function () {
  27053. return ValueCondition._IsDifferent;
  27054. },
  27055. enumerable: true,
  27056. configurable: true
  27057. });
  27058. Object.defineProperty(ValueCondition, "IsGreater", {
  27059. get: function () {
  27060. return ValueCondition._IsGreater;
  27061. },
  27062. enumerable: true,
  27063. configurable: true
  27064. });
  27065. Object.defineProperty(ValueCondition, "IsLesser", {
  27066. get: function () {
  27067. return ValueCondition._IsLesser;
  27068. },
  27069. enumerable: true,
  27070. configurable: true
  27071. });
  27072. // Methods
  27073. ValueCondition.prototype.isValid = function () {
  27074. switch (this.operator) {
  27075. case ValueCondition.IsGreater:
  27076. return this._target[this._property] > this.value;
  27077. case ValueCondition.IsLesser:
  27078. return this._target[this._property] < this.value;
  27079. case ValueCondition.IsEqual:
  27080. case ValueCondition.IsDifferent:
  27081. var check;
  27082. if (this.value.equals) {
  27083. check = this.value.equals(this._target[this._property]);
  27084. }
  27085. else {
  27086. check = this.value === this._target[this._property];
  27087. }
  27088. return this.operator === ValueCondition.IsEqual ? check : !check;
  27089. }
  27090. return false;
  27091. };
  27092. // Statics
  27093. ValueCondition._IsEqual = 0;
  27094. ValueCondition._IsDifferent = 1;
  27095. ValueCondition._IsGreater = 2;
  27096. ValueCondition._IsLesser = 3;
  27097. return ValueCondition;
  27098. })(Condition);
  27099. BABYLON.ValueCondition = ValueCondition;
  27100. var PredicateCondition = (function (_super) {
  27101. __extends(PredicateCondition, _super);
  27102. function PredicateCondition(actionManager, predicate) {
  27103. _super.call(this, actionManager);
  27104. this.predicate = predicate;
  27105. }
  27106. PredicateCondition.prototype.isValid = function () {
  27107. return this.predicate();
  27108. };
  27109. return PredicateCondition;
  27110. })(Condition);
  27111. BABYLON.PredicateCondition = PredicateCondition;
  27112. var StateCondition = (function (_super) {
  27113. __extends(StateCondition, _super);
  27114. function StateCondition(actionManager, target, value) {
  27115. _super.call(this, actionManager);
  27116. this.value = value;
  27117. this._target = target;
  27118. }
  27119. // Methods
  27120. StateCondition.prototype.isValid = function () {
  27121. return this._target.state === this.value;
  27122. };
  27123. return StateCondition;
  27124. })(Condition);
  27125. BABYLON.StateCondition = StateCondition;
  27126. })(BABYLON || (BABYLON = {}));
  27127. var BABYLON;
  27128. (function (BABYLON) {
  27129. var Action = (function () {
  27130. function Action(triggerOptions, condition) {
  27131. this.triggerOptions = triggerOptions;
  27132. if (triggerOptions.parameter) {
  27133. this.trigger = triggerOptions.trigger;
  27134. this._triggerParameter = triggerOptions.parameter;
  27135. }
  27136. else {
  27137. this.trigger = triggerOptions;
  27138. }
  27139. this._nextActiveAction = this;
  27140. this._condition = condition;
  27141. }
  27142. // Methods
  27143. Action.prototype._prepare = function () {
  27144. };
  27145. Action.prototype.getTriggerParameter = function () {
  27146. return this._triggerParameter;
  27147. };
  27148. Action.prototype._executeCurrent = function (evt) {
  27149. if (this._nextActiveAction._condition) {
  27150. var condition = this._nextActiveAction._condition;
  27151. var currentRenderId = this._actionManager.getScene().getRenderId();
  27152. // We cache the current evaluation for the current frame
  27153. if (condition._evaluationId === currentRenderId) {
  27154. if (!condition._currentResult) {
  27155. return;
  27156. }
  27157. }
  27158. else {
  27159. condition._evaluationId = currentRenderId;
  27160. if (!condition.isValid()) {
  27161. condition._currentResult = false;
  27162. return;
  27163. }
  27164. condition._currentResult = true;
  27165. }
  27166. }
  27167. this._nextActiveAction.execute(evt);
  27168. this.skipToNextActiveAction();
  27169. };
  27170. Action.prototype.execute = function (evt) {
  27171. };
  27172. Action.prototype.skipToNextActiveAction = function () {
  27173. if (this._nextActiveAction._child) {
  27174. if (!this._nextActiveAction._child._actionManager) {
  27175. this._nextActiveAction._child._actionManager = this._actionManager;
  27176. }
  27177. this._nextActiveAction = this._nextActiveAction._child;
  27178. }
  27179. else {
  27180. this._nextActiveAction = this;
  27181. }
  27182. };
  27183. Action.prototype.then = function (action) {
  27184. this._child = action;
  27185. action._actionManager = this._actionManager;
  27186. action._prepare();
  27187. return action;
  27188. };
  27189. Action.prototype._getProperty = function (propertyPath) {
  27190. return this._actionManager._getProperty(propertyPath);
  27191. };
  27192. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  27193. return this._actionManager._getEffectiveTarget(target, propertyPath);
  27194. };
  27195. return Action;
  27196. })();
  27197. BABYLON.Action = Action;
  27198. })(BABYLON || (BABYLON = {}));
  27199. var BABYLON;
  27200. (function (BABYLON) {
  27201. /**
  27202. * ActionEvent is the event beint sent when an action is triggered.
  27203. */
  27204. var ActionEvent = (function () {
  27205. /**
  27206. * @constructor
  27207. * @param source The mesh or sprite that triggered the action.
  27208. * @param pointerX The X mouse cursor position at the time of the event
  27209. * @param pointerY The Y mouse cursor position at the time of the event
  27210. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  27211. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  27212. */
  27213. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  27214. this.source = source;
  27215. this.pointerX = pointerX;
  27216. this.pointerY = pointerY;
  27217. this.meshUnderPointer = meshUnderPointer;
  27218. this.sourceEvent = sourceEvent;
  27219. this.additionalData = additionalData;
  27220. }
  27221. /**
  27222. * Helper function to auto-create an ActionEvent from a source mesh.
  27223. * @param source The source mesh that triggered the event
  27224. * @param evt {Event} The original (browser) event
  27225. */
  27226. ActionEvent.CreateNew = function (source, evt, additionalData) {
  27227. var scene = source.getScene();
  27228. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  27229. };
  27230. /**
  27231. * Helper function to auto-create an ActionEvent from a source mesh.
  27232. * @param source The source sprite that triggered the event
  27233. * @param scene Scene associated with the sprite
  27234. * @param evt {Event} The original (browser) event
  27235. */
  27236. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  27237. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  27238. };
  27239. /**
  27240. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  27241. * @param scene the scene where the event occurred
  27242. * @param evt {Event} The original (browser) event
  27243. */
  27244. ActionEvent.CreateNewFromScene = function (scene, evt) {
  27245. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  27246. };
  27247. return ActionEvent;
  27248. })();
  27249. BABYLON.ActionEvent = ActionEvent;
  27250. /**
  27251. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  27252. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  27253. */
  27254. var ActionManager = (function () {
  27255. function ActionManager(scene) {
  27256. // Members
  27257. this.actions = new Array();
  27258. this._scene = scene;
  27259. scene._actionManagers.push(this);
  27260. }
  27261. Object.defineProperty(ActionManager, "NothingTrigger", {
  27262. get: function () {
  27263. return ActionManager._NothingTrigger;
  27264. },
  27265. enumerable: true,
  27266. configurable: true
  27267. });
  27268. Object.defineProperty(ActionManager, "OnPickTrigger", {
  27269. get: function () {
  27270. return ActionManager._OnPickTrigger;
  27271. },
  27272. enumerable: true,
  27273. configurable: true
  27274. });
  27275. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  27276. get: function () {
  27277. return ActionManager._OnLeftPickTrigger;
  27278. },
  27279. enumerable: true,
  27280. configurable: true
  27281. });
  27282. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  27283. get: function () {
  27284. return ActionManager._OnRightPickTrigger;
  27285. },
  27286. enumerable: true,
  27287. configurable: true
  27288. });
  27289. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  27290. get: function () {
  27291. return ActionManager._OnCenterPickTrigger;
  27292. },
  27293. enumerable: true,
  27294. configurable: true
  27295. });
  27296. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  27297. get: function () {
  27298. return ActionManager._OnPickDownTrigger;
  27299. },
  27300. enumerable: true,
  27301. configurable: true
  27302. });
  27303. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  27304. get: function () {
  27305. return ActionManager._OnPickUpTrigger;
  27306. },
  27307. enumerable: true,
  27308. configurable: true
  27309. });
  27310. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  27311. /// This trigger will only be raised if you also declared a OnPickDown
  27312. get: function () {
  27313. return ActionManager._OnPickOutTrigger;
  27314. },
  27315. enumerable: true,
  27316. configurable: true
  27317. });
  27318. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  27319. get: function () {
  27320. return ActionManager._OnLongPressTrigger;
  27321. },
  27322. enumerable: true,
  27323. configurable: true
  27324. });
  27325. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  27326. get: function () {
  27327. return ActionManager._OnPointerOverTrigger;
  27328. },
  27329. enumerable: true,
  27330. configurable: true
  27331. });
  27332. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  27333. get: function () {
  27334. return ActionManager._OnPointerOutTrigger;
  27335. },
  27336. enumerable: true,
  27337. configurable: true
  27338. });
  27339. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  27340. get: function () {
  27341. return ActionManager._OnEveryFrameTrigger;
  27342. },
  27343. enumerable: true,
  27344. configurable: true
  27345. });
  27346. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  27347. get: function () {
  27348. return ActionManager._OnIntersectionEnterTrigger;
  27349. },
  27350. enumerable: true,
  27351. configurable: true
  27352. });
  27353. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  27354. get: function () {
  27355. return ActionManager._OnIntersectionExitTrigger;
  27356. },
  27357. enumerable: true,
  27358. configurable: true
  27359. });
  27360. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  27361. get: function () {
  27362. return ActionManager._OnKeyDownTrigger;
  27363. },
  27364. enumerable: true,
  27365. configurable: true
  27366. });
  27367. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  27368. get: function () {
  27369. return ActionManager._OnKeyUpTrigger;
  27370. },
  27371. enumerable: true,
  27372. configurable: true
  27373. });
  27374. // Methods
  27375. ActionManager.prototype.dispose = function () {
  27376. var index = this._scene._actionManagers.indexOf(this);
  27377. if (index > -1) {
  27378. this._scene._actionManagers.splice(index, 1);
  27379. }
  27380. };
  27381. ActionManager.prototype.getScene = function () {
  27382. return this._scene;
  27383. };
  27384. /**
  27385. * Does this action manager handles actions of any of the given triggers
  27386. * @param {number[]} triggers - the triggers to be tested
  27387. * @return {boolean} whether one (or more) of the triggers is handeled
  27388. */
  27389. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  27390. for (var index = 0; index < this.actions.length; index++) {
  27391. var action = this.actions[index];
  27392. if (triggers.indexOf(action.trigger) > -1) {
  27393. return true;
  27394. }
  27395. }
  27396. return false;
  27397. };
  27398. /**
  27399. * Does this action manager handles actions of a given trigger
  27400. * @param {number} trigger - the trigger to be tested
  27401. * @return {boolean} whether the trigger is handeled
  27402. */
  27403. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  27404. for (var index = 0; index < this.actions.length; index++) {
  27405. var action = this.actions[index];
  27406. if (action.trigger === trigger) {
  27407. return true;
  27408. }
  27409. }
  27410. return false;
  27411. };
  27412. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  27413. /**
  27414. * Does this action manager has pointer triggers
  27415. * @return {boolean} whether or not it has pointer triggers
  27416. */
  27417. get: function () {
  27418. for (var index = 0; index < this.actions.length; index++) {
  27419. var action = this.actions[index];
  27420. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  27421. return true;
  27422. }
  27423. }
  27424. return false;
  27425. },
  27426. enumerable: true,
  27427. configurable: true
  27428. });
  27429. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  27430. /**
  27431. * Does this action manager has pick triggers
  27432. * @return {boolean} whether or not it has pick triggers
  27433. */
  27434. get: function () {
  27435. for (var index = 0; index < this.actions.length; index++) {
  27436. var action = this.actions[index];
  27437. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  27438. return true;
  27439. }
  27440. }
  27441. return false;
  27442. },
  27443. enumerable: true,
  27444. configurable: true
  27445. });
  27446. /**
  27447. * Registers an action to this action manager
  27448. * @param {BABYLON.Action} action - the action to be registered
  27449. * @return {BABYLON.Action} the action amended (prepared) after registration
  27450. */
  27451. ActionManager.prototype.registerAction = function (action) {
  27452. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  27453. if (this.getScene().actionManager !== this) {
  27454. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  27455. return null;
  27456. }
  27457. }
  27458. this.actions.push(action);
  27459. action._actionManager = this;
  27460. action._prepare();
  27461. return action;
  27462. };
  27463. /**
  27464. * Process a specific trigger
  27465. * @param {number} trigger - the trigger to process
  27466. * @param evt {BABYLON.ActionEvent} the event details to be processed
  27467. */
  27468. ActionManager.prototype.processTrigger = function (trigger, evt) {
  27469. for (var index = 0; index < this.actions.length; index++) {
  27470. var action = this.actions[index];
  27471. if (action.trigger === trigger) {
  27472. if (trigger === ActionManager.OnKeyUpTrigger
  27473. || trigger === ActionManager.OnKeyDownTrigger) {
  27474. var parameter = action.getTriggerParameter();
  27475. if (parameter) {
  27476. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  27477. var actualkey = String.fromCharCode(unicode).toLowerCase();
  27478. if (actualkey !== parameter.toLowerCase()) {
  27479. continue;
  27480. }
  27481. }
  27482. }
  27483. action._executeCurrent(evt);
  27484. }
  27485. }
  27486. };
  27487. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  27488. var properties = propertyPath.split(".");
  27489. for (var index = 0; index < properties.length - 1; index++) {
  27490. target = target[properties[index]];
  27491. }
  27492. return target;
  27493. };
  27494. ActionManager.prototype._getProperty = function (propertyPath) {
  27495. var properties = propertyPath.split(".");
  27496. return properties[properties.length - 1];
  27497. };
  27498. ActionManager.Parse = function (parsedActions, object, scene) {
  27499. var actionManager = new BABYLON.ActionManager(scene);
  27500. if (object === null)
  27501. scene.actionManager = actionManager;
  27502. else
  27503. object.actionManager = actionManager;
  27504. // instanciate a new object
  27505. var instanciate = function (name, params) {
  27506. var newInstance = Object.create(BABYLON[name].prototype);
  27507. newInstance.constructor.apply(newInstance, params);
  27508. return newInstance;
  27509. };
  27510. var parseParameter = function (name, value, target, propertyPath) {
  27511. if (propertyPath === null) {
  27512. // String, boolean or float
  27513. var floatValue = parseFloat(value);
  27514. if (value === "true" || value === "false")
  27515. return value === "true";
  27516. else
  27517. return isNaN(floatValue) ? value : floatValue;
  27518. }
  27519. var effectiveTarget = propertyPath.split(".");
  27520. var values = value.split(",");
  27521. // Get effective Target
  27522. for (var i = 0; i < effectiveTarget.length; i++) {
  27523. target = target[effectiveTarget[i]];
  27524. }
  27525. // Return appropriate value with its type
  27526. if (typeof (target) === "boolean")
  27527. return values[0] === "true";
  27528. if (typeof (target) === "string")
  27529. return values[0];
  27530. // Parameters with multiple values such as Vector3 etc.
  27531. var split = new Array();
  27532. for (var i = 0; i < values.length; i++)
  27533. split.push(parseFloat(values[i]));
  27534. if (target instanceof BABYLON.Vector3)
  27535. return BABYLON.Vector3.FromArray(split);
  27536. if (target instanceof BABYLON.Vector4)
  27537. return BABYLON.Vector4.FromArray(split);
  27538. if (target instanceof BABYLON.Color3)
  27539. return BABYLON.Color3.FromArray(split);
  27540. if (target instanceof BABYLON.Color4)
  27541. return BABYLON.Color4.FromArray(split);
  27542. return parseFloat(values[0]);
  27543. };
  27544. // traverse graph per trigger
  27545. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  27546. if (combineArray === void 0) { combineArray = null; }
  27547. if (parsedAction.detached)
  27548. return;
  27549. var parameters = new Array();
  27550. var target = null;
  27551. var propertyPath = null;
  27552. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  27553. // Parameters
  27554. if (parsedAction.type === 2)
  27555. parameters.push(actionManager);
  27556. else
  27557. parameters.push(trigger);
  27558. if (combine) {
  27559. var actions = new Array();
  27560. for (var j = 0; j < parsedAction.combine.length; j++) {
  27561. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  27562. }
  27563. parameters.push(actions);
  27564. }
  27565. else {
  27566. for (var i = 0; i < parsedAction.properties.length; i++) {
  27567. var value = parsedAction.properties[i].value;
  27568. var name = parsedAction.properties[i].name;
  27569. var targetType = parsedAction.properties[i].targetType;
  27570. if (name === "target")
  27571. if (targetType !== null && targetType === "SceneProperties")
  27572. value = target = scene;
  27573. else
  27574. value = target = scene.getNodeByName(value);
  27575. else if (name === "parent")
  27576. value = scene.getNodeByName(value);
  27577. else if (name === "sound")
  27578. value = scene.getSoundByName(value);
  27579. else if (name !== "propertyPath") {
  27580. if (parsedAction.type === 2 && name === "operator")
  27581. value = BABYLON.ValueCondition[value];
  27582. else
  27583. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  27584. }
  27585. else {
  27586. propertyPath = value;
  27587. }
  27588. parameters.push(value);
  27589. }
  27590. }
  27591. if (combineArray === null) {
  27592. parameters.push(condition);
  27593. }
  27594. else {
  27595. parameters.push(null);
  27596. }
  27597. // If interpolate value action
  27598. if (parsedAction.name === "InterpolateValueAction") {
  27599. var param = parameters[parameters.length - 2];
  27600. parameters[parameters.length - 1] = param;
  27601. parameters[parameters.length - 2] = condition;
  27602. }
  27603. // Action or condition(s) and not CombineAction
  27604. var newAction = instanciate(parsedAction.name, parameters);
  27605. if (newAction instanceof BABYLON.Condition && condition !== null) {
  27606. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  27607. if (action)
  27608. action.then(nothing);
  27609. else
  27610. actionManager.registerAction(nothing);
  27611. action = nothing;
  27612. }
  27613. if (combineArray === null) {
  27614. if (newAction instanceof BABYLON.Condition) {
  27615. condition = newAction;
  27616. newAction = action;
  27617. }
  27618. else {
  27619. condition = null;
  27620. if (action)
  27621. action.then(newAction);
  27622. else
  27623. actionManager.registerAction(newAction);
  27624. }
  27625. }
  27626. else {
  27627. combineArray.push(newAction);
  27628. }
  27629. for (var i = 0; i < parsedAction.children.length; i++)
  27630. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  27631. };
  27632. // triggers
  27633. for (var i = 0; i < parsedActions.children.length; i++) {
  27634. var triggerParams;
  27635. var trigger = parsedActions.children[i];
  27636. if (trigger.properties.length > 0) {
  27637. var param = trigger.properties[0].value;
  27638. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  27639. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  27640. }
  27641. else
  27642. triggerParams = BABYLON.ActionManager[trigger.name];
  27643. for (var j = 0; j < trigger.children.length; j++) {
  27644. if (!trigger.detached)
  27645. traverse(trigger.children[j], triggerParams, null, null);
  27646. }
  27647. }
  27648. };
  27649. // Statics
  27650. ActionManager._NothingTrigger = 0;
  27651. ActionManager._OnPickTrigger = 1;
  27652. ActionManager._OnLeftPickTrigger = 2;
  27653. ActionManager._OnRightPickTrigger = 3;
  27654. ActionManager._OnCenterPickTrigger = 4;
  27655. ActionManager._OnPickDownTrigger = 5;
  27656. ActionManager._OnPickUpTrigger = 6;
  27657. ActionManager._OnLongPressTrigger = 7;
  27658. ActionManager._OnPointerOverTrigger = 8;
  27659. ActionManager._OnPointerOutTrigger = 9;
  27660. ActionManager._OnEveryFrameTrigger = 10;
  27661. ActionManager._OnIntersectionEnterTrigger = 11;
  27662. ActionManager._OnIntersectionExitTrigger = 12;
  27663. ActionManager._OnKeyDownTrigger = 13;
  27664. ActionManager._OnKeyUpTrigger = 14;
  27665. ActionManager._OnPickOutTrigger = 15;
  27666. ActionManager.DragMovementThreshold = 10; // in pixels
  27667. ActionManager.LongPressDelay = 500; // in milliseconds
  27668. return ActionManager;
  27669. })();
  27670. BABYLON.ActionManager = ActionManager;
  27671. })(BABYLON || (BABYLON = {}));
  27672. var BABYLON;
  27673. (function (BABYLON) {
  27674. var InterpolateValueAction = (function (_super) {
  27675. __extends(InterpolateValueAction, _super);
  27676. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  27677. if (duration === void 0) { duration = 1000; }
  27678. _super.call(this, triggerOptions, condition);
  27679. this.propertyPath = propertyPath;
  27680. this.value = value;
  27681. this.duration = duration;
  27682. this.stopOtherAnimations = stopOtherAnimations;
  27683. this.onInterpolationDone = onInterpolationDone;
  27684. this._target = target;
  27685. }
  27686. InterpolateValueAction.prototype._prepare = function () {
  27687. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  27688. this._property = this._getProperty(this.propertyPath);
  27689. };
  27690. InterpolateValueAction.prototype.execute = function () {
  27691. var scene = this._actionManager.getScene();
  27692. var keys = [
  27693. {
  27694. frame: 0,
  27695. value: this._target[this._property]
  27696. }, {
  27697. frame: 100,
  27698. value: this.value
  27699. }
  27700. ];
  27701. var dataType;
  27702. if (typeof this.value === "number") {
  27703. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  27704. }
  27705. else if (this.value instanceof BABYLON.Color3) {
  27706. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  27707. }
  27708. else if (this.value instanceof BABYLON.Vector3) {
  27709. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  27710. }
  27711. else if (this.value instanceof BABYLON.Matrix) {
  27712. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  27713. }
  27714. else if (this.value instanceof BABYLON.Quaternion) {
  27715. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  27716. }
  27717. else {
  27718. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  27719. return;
  27720. }
  27721. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  27722. animation.setKeys(keys);
  27723. if (this.stopOtherAnimations) {
  27724. scene.stopAnimation(this._target);
  27725. }
  27726. scene.beginDirectAnimation(this._target, [animation], 0, 100, false, 1, this.onInterpolationDone);
  27727. };
  27728. return InterpolateValueAction;
  27729. })(BABYLON.Action);
  27730. BABYLON.InterpolateValueAction = InterpolateValueAction;
  27731. })(BABYLON || (BABYLON = {}));
  27732. var BABYLON;
  27733. (function (BABYLON) {
  27734. var SwitchBooleanAction = (function (_super) {
  27735. __extends(SwitchBooleanAction, _super);
  27736. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  27737. _super.call(this, triggerOptions, condition);
  27738. this.propertyPath = propertyPath;
  27739. this._target = target;
  27740. }
  27741. SwitchBooleanAction.prototype._prepare = function () {
  27742. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  27743. this._property = this._getProperty(this.propertyPath);
  27744. };
  27745. SwitchBooleanAction.prototype.execute = function () {
  27746. this._target[this._property] = !this._target[this._property];
  27747. };
  27748. return SwitchBooleanAction;
  27749. })(BABYLON.Action);
  27750. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  27751. var SetStateAction = (function (_super) {
  27752. __extends(SetStateAction, _super);
  27753. function SetStateAction(triggerOptions, target, value, condition) {
  27754. _super.call(this, triggerOptions, condition);
  27755. this.value = value;
  27756. this._target = target;
  27757. }
  27758. SetStateAction.prototype.execute = function () {
  27759. this._target.state = this.value;
  27760. };
  27761. return SetStateAction;
  27762. })(BABYLON.Action);
  27763. BABYLON.SetStateAction = SetStateAction;
  27764. var SetValueAction = (function (_super) {
  27765. __extends(SetValueAction, _super);
  27766. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  27767. _super.call(this, triggerOptions, condition);
  27768. this.propertyPath = propertyPath;
  27769. this.value = value;
  27770. this._target = target;
  27771. }
  27772. SetValueAction.prototype._prepare = function () {
  27773. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  27774. this._property = this._getProperty(this.propertyPath);
  27775. };
  27776. SetValueAction.prototype.execute = function () {
  27777. this._target[this._property] = this.value;
  27778. };
  27779. return SetValueAction;
  27780. })(BABYLON.Action);
  27781. BABYLON.SetValueAction = SetValueAction;
  27782. var IncrementValueAction = (function (_super) {
  27783. __extends(IncrementValueAction, _super);
  27784. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  27785. _super.call(this, triggerOptions, condition);
  27786. this.propertyPath = propertyPath;
  27787. this.value = value;
  27788. this._target = target;
  27789. }
  27790. IncrementValueAction.prototype._prepare = function () {
  27791. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  27792. this._property = this._getProperty(this.propertyPath);
  27793. if (typeof this._target[this._property] !== "number") {
  27794. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  27795. }
  27796. };
  27797. IncrementValueAction.prototype.execute = function () {
  27798. this._target[this._property] += this.value;
  27799. };
  27800. return IncrementValueAction;
  27801. })(BABYLON.Action);
  27802. BABYLON.IncrementValueAction = IncrementValueAction;
  27803. var PlayAnimationAction = (function (_super) {
  27804. __extends(PlayAnimationAction, _super);
  27805. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  27806. _super.call(this, triggerOptions, condition);
  27807. this.from = from;
  27808. this.to = to;
  27809. this.loop = loop;
  27810. this._target = target;
  27811. }
  27812. PlayAnimationAction.prototype._prepare = function () {
  27813. };
  27814. PlayAnimationAction.prototype.execute = function () {
  27815. var scene = this._actionManager.getScene();
  27816. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  27817. };
  27818. return PlayAnimationAction;
  27819. })(BABYLON.Action);
  27820. BABYLON.PlayAnimationAction = PlayAnimationAction;
  27821. var StopAnimationAction = (function (_super) {
  27822. __extends(StopAnimationAction, _super);
  27823. function StopAnimationAction(triggerOptions, target, condition) {
  27824. _super.call(this, triggerOptions, condition);
  27825. this._target = target;
  27826. }
  27827. StopAnimationAction.prototype._prepare = function () {
  27828. };
  27829. StopAnimationAction.prototype.execute = function () {
  27830. var scene = this._actionManager.getScene();
  27831. scene.stopAnimation(this._target);
  27832. };
  27833. return StopAnimationAction;
  27834. })(BABYLON.Action);
  27835. BABYLON.StopAnimationAction = StopAnimationAction;
  27836. var DoNothingAction = (function (_super) {
  27837. __extends(DoNothingAction, _super);
  27838. function DoNothingAction(triggerOptions, condition) {
  27839. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  27840. _super.call(this, triggerOptions, condition);
  27841. }
  27842. DoNothingAction.prototype.execute = function () {
  27843. };
  27844. return DoNothingAction;
  27845. })(BABYLON.Action);
  27846. BABYLON.DoNothingAction = DoNothingAction;
  27847. var CombineAction = (function (_super) {
  27848. __extends(CombineAction, _super);
  27849. function CombineAction(triggerOptions, children, condition) {
  27850. _super.call(this, triggerOptions, condition);
  27851. this.children = children;
  27852. }
  27853. CombineAction.prototype._prepare = function () {
  27854. for (var index = 0; index < this.children.length; index++) {
  27855. this.children[index]._actionManager = this._actionManager;
  27856. this.children[index]._prepare();
  27857. }
  27858. };
  27859. CombineAction.prototype.execute = function (evt) {
  27860. for (var index = 0; index < this.children.length; index++) {
  27861. this.children[index].execute(evt);
  27862. }
  27863. };
  27864. return CombineAction;
  27865. })(BABYLON.Action);
  27866. BABYLON.CombineAction = CombineAction;
  27867. var ExecuteCodeAction = (function (_super) {
  27868. __extends(ExecuteCodeAction, _super);
  27869. function ExecuteCodeAction(triggerOptions, func, condition) {
  27870. _super.call(this, triggerOptions, condition);
  27871. this.func = func;
  27872. }
  27873. ExecuteCodeAction.prototype.execute = function (evt) {
  27874. this.func(evt);
  27875. };
  27876. return ExecuteCodeAction;
  27877. })(BABYLON.Action);
  27878. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  27879. var SetParentAction = (function (_super) {
  27880. __extends(SetParentAction, _super);
  27881. function SetParentAction(triggerOptions, target, parent, condition) {
  27882. _super.call(this, triggerOptions, condition);
  27883. this._target = target;
  27884. this._parent = parent;
  27885. }
  27886. SetParentAction.prototype._prepare = function () {
  27887. };
  27888. SetParentAction.prototype.execute = function () {
  27889. if (this._target.parent === this._parent) {
  27890. return;
  27891. }
  27892. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  27893. invertParentWorldMatrix.invert();
  27894. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  27895. this._target.parent = this._parent;
  27896. };
  27897. return SetParentAction;
  27898. })(BABYLON.Action);
  27899. BABYLON.SetParentAction = SetParentAction;
  27900. var PlaySoundAction = (function (_super) {
  27901. __extends(PlaySoundAction, _super);
  27902. function PlaySoundAction(triggerOptions, sound, condition) {
  27903. _super.call(this, triggerOptions, condition);
  27904. this._sound = sound;
  27905. }
  27906. PlaySoundAction.prototype._prepare = function () {
  27907. };
  27908. PlaySoundAction.prototype.execute = function () {
  27909. if (this._sound !== undefined)
  27910. this._sound.play();
  27911. };
  27912. return PlaySoundAction;
  27913. })(BABYLON.Action);
  27914. BABYLON.PlaySoundAction = PlaySoundAction;
  27915. var StopSoundAction = (function (_super) {
  27916. __extends(StopSoundAction, _super);
  27917. function StopSoundAction(triggerOptions, sound, condition) {
  27918. _super.call(this, triggerOptions, condition);
  27919. this._sound = sound;
  27920. }
  27921. StopSoundAction.prototype._prepare = function () {
  27922. };
  27923. StopSoundAction.prototype.execute = function () {
  27924. if (this._sound !== undefined)
  27925. this._sound.stop();
  27926. };
  27927. return StopSoundAction;
  27928. })(BABYLON.Action);
  27929. BABYLON.StopSoundAction = StopSoundAction;
  27930. })(BABYLON || (BABYLON = {}));
  27931. var BABYLON;
  27932. (function (BABYLON) {
  27933. var Geometry = (function () {
  27934. function Geometry(id, scene, vertexData, updatable, mesh) {
  27935. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27936. this._totalVertices = 0;
  27937. this._isDisposed = false;
  27938. this.id = id;
  27939. this._engine = scene.getEngine();
  27940. this._meshes = [];
  27941. this._scene = scene;
  27942. //Init vertex buffer cache
  27943. this._vertexBuffers = {};
  27944. this._indices = [];
  27945. // vertexData
  27946. if (vertexData) {
  27947. this.setAllVerticesData(vertexData, updatable);
  27948. }
  27949. else {
  27950. this._totalVertices = 0;
  27951. this._indices = [];
  27952. }
  27953. // applyToMesh
  27954. if (mesh) {
  27955. this.applyToMesh(mesh);
  27956. mesh.computeWorldMatrix(true);
  27957. }
  27958. }
  27959. Object.defineProperty(Geometry.prototype, "extend", {
  27960. get: function () {
  27961. return this._extend;
  27962. },
  27963. enumerable: true,
  27964. configurable: true
  27965. });
  27966. Geometry.prototype.getScene = function () {
  27967. return this._scene;
  27968. };
  27969. Geometry.prototype.getEngine = function () {
  27970. return this._engine;
  27971. };
  27972. Geometry.prototype.isReady = function () {
  27973. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  27974. };
  27975. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  27976. vertexData.applyToGeometry(this, updatable);
  27977. this.notifyUpdate();
  27978. };
  27979. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  27980. if (this._vertexBuffers[kind]) {
  27981. this._vertexBuffers[kind].dispose();
  27982. }
  27983. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  27984. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27985. stride = this._vertexBuffers[kind].getStrideSize();
  27986. this._totalVertices = data.length / stride;
  27987. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  27988. var meshes = this._meshes;
  27989. var numOfMeshes = meshes.length;
  27990. for (var index = 0; index < numOfMeshes; index++) {
  27991. var mesh = meshes[index];
  27992. mesh._resetPointsArrayCache();
  27993. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27994. mesh._createGlobalSubMesh();
  27995. mesh.computeWorldMatrix(true);
  27996. }
  27997. }
  27998. this.notifyUpdate(kind);
  27999. };
  28000. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  28001. var vertexBuffer = this.getVertexBuffer(kind);
  28002. if (!vertexBuffer) {
  28003. return;
  28004. }
  28005. vertexBuffer.updateDirectly(data, offset);
  28006. this.notifyUpdate(kind);
  28007. };
  28008. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  28009. var vertexBuffer = this.getVertexBuffer(kind);
  28010. if (!vertexBuffer) {
  28011. return;
  28012. }
  28013. vertexBuffer.update(data);
  28014. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28015. var stride = vertexBuffer.getStrideSize();
  28016. this._totalVertices = data.length / stride;
  28017. if (updateExtends) {
  28018. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  28019. }
  28020. var meshes = this._meshes;
  28021. var numOfMeshes = meshes.length;
  28022. for (var index = 0; index < numOfMeshes; index++) {
  28023. var mesh = meshes[index];
  28024. mesh._resetPointsArrayCache();
  28025. if (updateExtends) {
  28026. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  28027. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  28028. var subMesh = mesh.subMeshes[subIndex];
  28029. subMesh.refreshBoundingInfo();
  28030. }
  28031. }
  28032. }
  28033. }
  28034. this.notifyUpdate(kind);
  28035. };
  28036. Geometry.prototype.getTotalVertices = function () {
  28037. if (!this.isReady()) {
  28038. return 0;
  28039. }
  28040. return this._totalVertices;
  28041. };
  28042. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  28043. var vertexBuffer = this.getVertexBuffer(kind);
  28044. if (!vertexBuffer) {
  28045. return null;
  28046. }
  28047. var orig = vertexBuffer.getData();
  28048. if (!copyWhenShared || this._meshes.length === 1) {
  28049. return orig;
  28050. }
  28051. else {
  28052. var len = orig.length;
  28053. var copy = [];
  28054. for (var i = 0; i < len; i++) {
  28055. copy.push(orig[i]);
  28056. }
  28057. return copy;
  28058. }
  28059. };
  28060. Geometry.prototype.getVertexBuffer = function (kind) {
  28061. if (!this.isReady()) {
  28062. return null;
  28063. }
  28064. return this._vertexBuffers[kind];
  28065. };
  28066. Geometry.prototype.getVertexBuffers = function () {
  28067. if (!this.isReady()) {
  28068. return null;
  28069. }
  28070. return this._vertexBuffers;
  28071. };
  28072. Geometry.prototype.isVerticesDataPresent = function (kind) {
  28073. if (!this._vertexBuffers) {
  28074. if (this._delayInfo) {
  28075. return this._delayInfo.indexOf(kind) !== -1;
  28076. }
  28077. return false;
  28078. }
  28079. return this._vertexBuffers[kind] !== undefined;
  28080. };
  28081. Geometry.prototype.getVerticesDataKinds = function () {
  28082. var result = [];
  28083. var kind;
  28084. if (!this._vertexBuffers && this._delayInfo) {
  28085. for (kind in this._delayInfo) {
  28086. result.push(kind);
  28087. }
  28088. }
  28089. else {
  28090. for (kind in this._vertexBuffers) {
  28091. result.push(kind);
  28092. }
  28093. }
  28094. return result;
  28095. };
  28096. Geometry.prototype.setIndices = function (indices, totalVertices) {
  28097. if (this._indexBuffer) {
  28098. this._engine._releaseBuffer(this._indexBuffer);
  28099. }
  28100. this._indices = indices;
  28101. if (this._meshes.length !== 0 && this._indices) {
  28102. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  28103. }
  28104. if (totalVertices !== undefined) {
  28105. this._totalVertices = totalVertices;
  28106. }
  28107. var meshes = this._meshes;
  28108. var numOfMeshes = meshes.length;
  28109. for (var index = 0; index < numOfMeshes; index++) {
  28110. meshes[index]._createGlobalSubMesh();
  28111. }
  28112. this.notifyUpdate();
  28113. };
  28114. Geometry.prototype.getTotalIndices = function () {
  28115. if (!this.isReady()) {
  28116. return 0;
  28117. }
  28118. return this._indices.length;
  28119. };
  28120. Geometry.prototype.getIndices = function (copyWhenShared) {
  28121. if (!this.isReady()) {
  28122. return null;
  28123. }
  28124. var orig = this._indices;
  28125. if (!copyWhenShared || this._meshes.length === 1) {
  28126. return orig;
  28127. }
  28128. else {
  28129. var len = orig.length;
  28130. var copy = [];
  28131. for (var i = 0; i < len; i++) {
  28132. copy.push(orig[i]);
  28133. }
  28134. return copy;
  28135. }
  28136. };
  28137. Geometry.prototype.getIndexBuffer = function () {
  28138. if (!this.isReady()) {
  28139. return null;
  28140. }
  28141. return this._indexBuffer;
  28142. };
  28143. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  28144. var meshes = this._meshes;
  28145. var index = meshes.indexOf(mesh);
  28146. if (index === -1) {
  28147. return;
  28148. }
  28149. for (var kind in this._vertexBuffers) {
  28150. this._vertexBuffers[kind].dispose();
  28151. }
  28152. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  28153. this._indexBuffer = null;
  28154. }
  28155. meshes.splice(index, 1);
  28156. mesh._geometry = null;
  28157. if (meshes.length === 0 && shouldDispose) {
  28158. this.dispose();
  28159. }
  28160. };
  28161. Geometry.prototype.applyToMesh = function (mesh) {
  28162. if (mesh._geometry === this) {
  28163. return;
  28164. }
  28165. var previousGeometry = mesh._geometry;
  28166. if (previousGeometry) {
  28167. previousGeometry.releaseForMesh(mesh);
  28168. }
  28169. var meshes = this._meshes;
  28170. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  28171. mesh._geometry = this;
  28172. this._scene.pushGeometry(this);
  28173. meshes.push(mesh);
  28174. if (this.isReady()) {
  28175. this._applyToMesh(mesh);
  28176. }
  28177. else {
  28178. mesh._boundingInfo = this._boundingInfo;
  28179. }
  28180. };
  28181. Geometry.prototype._applyToMesh = function (mesh) {
  28182. var numOfMeshes = this._meshes.length;
  28183. // vertexBuffers
  28184. for (var kind in this._vertexBuffers) {
  28185. if (numOfMeshes === 1) {
  28186. this._vertexBuffers[kind].create();
  28187. }
  28188. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  28189. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28190. mesh._resetPointsArrayCache();
  28191. if (!this._extend) {
  28192. this._extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  28193. }
  28194. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  28195. mesh._createGlobalSubMesh();
  28196. //bounding info was just created again, world matrix should be applied again.
  28197. mesh._updateBoundingInfo();
  28198. }
  28199. }
  28200. // indexBuffer
  28201. if (numOfMeshes === 1 && this._indices) {
  28202. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  28203. }
  28204. if (this._indexBuffer) {
  28205. this._indexBuffer.references = numOfMeshes;
  28206. }
  28207. };
  28208. Geometry.prototype.notifyUpdate = function (kind) {
  28209. if (this.onGeometryUpdated) {
  28210. this.onGeometryUpdated(this, kind);
  28211. }
  28212. };
  28213. Geometry.prototype.load = function (scene, onLoaded) {
  28214. var _this = this;
  28215. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  28216. return;
  28217. }
  28218. if (this.isReady()) {
  28219. if (onLoaded) {
  28220. onLoaded();
  28221. }
  28222. return;
  28223. }
  28224. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  28225. scene._addPendingData(this);
  28226. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  28227. _this._delayLoadingFunction(JSON.parse(data), _this);
  28228. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  28229. _this._delayInfo = [];
  28230. scene._removePendingData(_this);
  28231. var meshes = _this._meshes;
  28232. var numOfMeshes = meshes.length;
  28233. for (var index = 0; index < numOfMeshes; index++) {
  28234. _this._applyToMesh(meshes[index]);
  28235. }
  28236. if (onLoaded) {
  28237. onLoaded();
  28238. }
  28239. }, function () { }, scene.database);
  28240. };
  28241. Geometry.prototype.isDisposed = function () {
  28242. return this._isDisposed;
  28243. };
  28244. Geometry.prototype.dispose = function () {
  28245. var meshes = this._meshes;
  28246. var numOfMeshes = meshes.length;
  28247. var index;
  28248. for (index = 0; index < numOfMeshes; index++) {
  28249. this.releaseForMesh(meshes[index]);
  28250. }
  28251. this._meshes = [];
  28252. for (var kind in this._vertexBuffers) {
  28253. this._vertexBuffers[kind].dispose();
  28254. }
  28255. this._vertexBuffers = [];
  28256. this._totalVertices = 0;
  28257. if (this._indexBuffer) {
  28258. this._engine._releaseBuffer(this._indexBuffer);
  28259. }
  28260. this._indexBuffer = null;
  28261. this._indices = [];
  28262. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  28263. this.delayLoadingFile = null;
  28264. this._delayLoadingFunction = null;
  28265. this._delayInfo = [];
  28266. this._boundingInfo = null;
  28267. this._scene.removeGeometry(this);
  28268. this._isDisposed = true;
  28269. };
  28270. Geometry.prototype.copy = function (id) {
  28271. var vertexData = new BABYLON.VertexData();
  28272. vertexData.indices = [];
  28273. var indices = this.getIndices();
  28274. for (var index = 0; index < indices.length; index++) {
  28275. vertexData.indices.push(indices[index]);
  28276. }
  28277. var updatable = false;
  28278. var stopChecking = false;
  28279. var kind;
  28280. for (kind in this._vertexBuffers) {
  28281. // using slice() to make a copy of the array and not just reference it
  28282. var data = this.getVerticesData(kind);
  28283. if (data instanceof Float32Array) {
  28284. vertexData.set(new Float32Array(data), kind);
  28285. }
  28286. else {
  28287. vertexData.set(data.slice(0), kind);
  28288. }
  28289. if (!stopChecking) {
  28290. updatable = this.getVertexBuffer(kind).isUpdatable();
  28291. stopChecking = !updatable;
  28292. }
  28293. }
  28294. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  28295. geometry.delayLoadState = this.delayLoadState;
  28296. geometry.delayLoadingFile = this.delayLoadingFile;
  28297. geometry._delayLoadingFunction = this._delayLoadingFunction;
  28298. for (kind in this._delayInfo) {
  28299. geometry._delayInfo = geometry._delayInfo || [];
  28300. geometry._delayInfo.push(kind);
  28301. }
  28302. // Bounding info
  28303. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  28304. return geometry;
  28305. };
  28306. Geometry.prototype.serialize = function () {
  28307. var serializationObject = {};
  28308. serializationObject.id = this.id;
  28309. if (BABYLON.Tags.HasTags(this)) {
  28310. serializationObject.tags = BABYLON.Tags.GetTags(this);
  28311. }
  28312. return serializationObject;
  28313. };
  28314. Geometry.prototype.serializeVerticeData = function () {
  28315. var serializationObject = this.serialize();
  28316. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  28317. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28318. }
  28319. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28320. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28321. }
  28322. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28323. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  28324. }
  28325. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  28326. serializationObject.uvs2 = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  28327. }
  28328. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  28329. serializationObject.uvs3 = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  28330. }
  28331. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  28332. serializationObject.uvs4 = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  28333. }
  28334. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  28335. serializationObject.uvs5 = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  28336. }
  28337. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  28338. serializationObject.uvs6 = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  28339. }
  28340. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  28341. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  28342. }
  28343. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  28344. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  28345. serializationObject.matricesIndices._isExpanded = true;
  28346. }
  28347. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  28348. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  28349. }
  28350. serializationObject.indices = this.getIndices();
  28351. return serializationObject;
  28352. };
  28353. // Statics
  28354. Geometry.ExtractFromMesh = function (mesh, id) {
  28355. var geometry = mesh._geometry;
  28356. if (!geometry) {
  28357. return null;
  28358. }
  28359. return geometry.copy(id);
  28360. };
  28361. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  28362. // be aware Math.random() could cause collisions
  28363. Geometry.RandomId = function () {
  28364. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  28365. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  28366. return v.toString(16);
  28367. });
  28368. };
  28369. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  28370. var scene = mesh.getScene();
  28371. // Geometry
  28372. var geometryId = parsedGeometry.geometryId;
  28373. if (geometryId) {
  28374. var geometry = scene.getGeometryByID(geometryId);
  28375. if (geometry) {
  28376. geometry.applyToMesh(mesh);
  28377. }
  28378. }
  28379. else if (parsedGeometry instanceof ArrayBuffer) {
  28380. var binaryInfo = mesh._binaryInfo;
  28381. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  28382. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  28383. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  28384. }
  28385. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  28386. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  28387. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  28388. }
  28389. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  28390. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  28391. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  28392. }
  28393. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  28394. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  28395. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  28396. }
  28397. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  28398. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  28399. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  28400. }
  28401. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  28402. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  28403. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  28404. }
  28405. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  28406. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  28407. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  28408. }
  28409. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  28410. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  28411. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  28412. }
  28413. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  28414. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  28415. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  28416. }
  28417. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  28418. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  28419. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  28420. }
  28421. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  28422. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  28423. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  28424. }
  28425. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  28426. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  28427. mesh.setIndices(indicesData);
  28428. }
  28429. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  28430. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  28431. mesh.subMeshes = [];
  28432. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  28433. var materialIndex = subMeshesData[(i * 5) + 0];
  28434. var verticesStart = subMeshesData[(i * 5) + 1];
  28435. var verticesCount = subMeshesData[(i * 5) + 2];
  28436. var indexStart = subMeshesData[(i * 5) + 3];
  28437. var indexCount = subMeshesData[(i * 5) + 4];
  28438. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  28439. }
  28440. }
  28441. }
  28442. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  28443. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  28444. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  28445. if (parsedGeometry.uvs) {
  28446. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  28447. }
  28448. if (parsedGeometry.uvs2) {
  28449. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  28450. }
  28451. if (parsedGeometry.uvs3) {
  28452. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  28453. }
  28454. if (parsedGeometry.uvs4) {
  28455. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  28456. }
  28457. if (parsedGeometry.uvs5) {
  28458. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  28459. }
  28460. if (parsedGeometry.uvs6) {
  28461. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  28462. }
  28463. if (parsedGeometry.colors) {
  28464. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  28465. }
  28466. if (parsedGeometry.matricesIndices) {
  28467. if (!parsedGeometry.matricesIndices._isExpanded) {
  28468. var floatIndices = [];
  28469. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  28470. var matricesIndex = parsedGeometry.matricesIndices[i];
  28471. floatIndices.push(matricesIndex & 0x000000FF);
  28472. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  28473. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  28474. floatIndices.push(matricesIndex >> 24);
  28475. }
  28476. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  28477. }
  28478. else {
  28479. delete parsedGeometry.matricesIndices._isExpanded;
  28480. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  28481. }
  28482. }
  28483. if (parsedGeometry.matricesIndicesExtra) {
  28484. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  28485. var floatIndices = [];
  28486. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  28487. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  28488. floatIndices.push(matricesIndex & 0x000000FF);
  28489. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  28490. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  28491. floatIndices.push(matricesIndex >> 24);
  28492. }
  28493. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, false);
  28494. }
  28495. else {
  28496. delete parsedGeometry.matricesIndices._isExpanded;
  28497. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, false);
  28498. }
  28499. }
  28500. if (parsedGeometry.matricesWeights) {
  28501. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  28502. }
  28503. if (parsedGeometry.matricesWeightsExtra) {
  28504. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, false);
  28505. }
  28506. mesh.setIndices(parsedGeometry.indices);
  28507. }
  28508. // SubMeshes
  28509. if (parsedGeometry.subMeshes) {
  28510. mesh.subMeshes = [];
  28511. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  28512. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  28513. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  28514. }
  28515. }
  28516. // Flat shading
  28517. if (mesh._shouldGenerateFlatShading) {
  28518. mesh.convertToFlatShadedMesh();
  28519. delete mesh._shouldGenerateFlatShading;
  28520. }
  28521. // Update
  28522. mesh.computeWorldMatrix(true);
  28523. // Octree
  28524. if (scene['_selectionOctree']) {
  28525. scene['_selectionOctree'].addMesh(mesh);
  28526. }
  28527. };
  28528. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  28529. if (scene.getGeometryByID(parsedVertexData.id)) {
  28530. return null; // null since geometry could be something else than a box...
  28531. }
  28532. var geometry = new Geometry(parsedVertexData.id, scene);
  28533. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  28534. if (parsedVertexData.delayLoadingFile) {
  28535. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  28536. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  28537. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  28538. geometry._delayInfo = [];
  28539. if (parsedVertexData.hasUVs) {
  28540. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  28541. }
  28542. if (parsedVertexData.hasUVs2) {
  28543. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  28544. }
  28545. if (parsedVertexData.hasUVs3) {
  28546. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  28547. }
  28548. if (parsedVertexData.hasUVs4) {
  28549. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  28550. }
  28551. if (parsedVertexData.hasUVs5) {
  28552. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  28553. }
  28554. if (parsedVertexData.hasUVs6) {
  28555. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  28556. }
  28557. if (parsedVertexData.hasColors) {
  28558. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  28559. }
  28560. if (parsedVertexData.hasMatricesIndices) {
  28561. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  28562. }
  28563. if (parsedVertexData.hasMatricesWeights) {
  28564. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  28565. }
  28566. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  28567. }
  28568. else {
  28569. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  28570. }
  28571. scene.pushGeometry(geometry, true);
  28572. return geometry;
  28573. };
  28574. return Geometry;
  28575. })();
  28576. BABYLON.Geometry = Geometry;
  28577. /////// Primitives //////////////////////////////////////////////
  28578. var Geometry;
  28579. (function (Geometry) {
  28580. var Primitives;
  28581. (function (Primitives) {
  28582. /// Abstract class
  28583. var _Primitive = (function (_super) {
  28584. __extends(_Primitive, _super);
  28585. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  28586. _super.call(this, id, scene, null, false, mesh); // updatable = false to be sure not to update vertices
  28587. this._canBeRegenerated = _canBeRegenerated;
  28588. this._beingRegenerated = true;
  28589. this.regenerate();
  28590. this._beingRegenerated = false;
  28591. }
  28592. _Primitive.prototype.canBeRegenerated = function () {
  28593. return this._canBeRegenerated;
  28594. };
  28595. _Primitive.prototype.regenerate = function () {
  28596. if (!this._canBeRegenerated) {
  28597. return;
  28598. }
  28599. this._beingRegenerated = true;
  28600. this.setAllVerticesData(this._regenerateVertexData(), false);
  28601. this._beingRegenerated = false;
  28602. };
  28603. _Primitive.prototype.asNewGeometry = function (id) {
  28604. return _super.prototype.copy.call(this, id);
  28605. };
  28606. // overrides
  28607. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  28608. if (!this._beingRegenerated) {
  28609. return;
  28610. }
  28611. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  28612. };
  28613. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  28614. if (!this._beingRegenerated) {
  28615. return;
  28616. }
  28617. _super.prototype.setVerticesData.call(this, kind, data, false);
  28618. };
  28619. // to override
  28620. // protected
  28621. _Primitive.prototype._regenerateVertexData = function () {
  28622. throw new Error("Abstract method");
  28623. };
  28624. _Primitive.prototype.copy = function (id) {
  28625. throw new Error("Must be overriden in sub-classes.");
  28626. };
  28627. _Primitive.prototype.serialize = function () {
  28628. var serializationObject = _super.prototype.serialize.call(this);
  28629. serializationObject.canBeRegenerated = this.canBeRegenerated();
  28630. return serializationObject;
  28631. };
  28632. return _Primitive;
  28633. })(Geometry);
  28634. Primitives._Primitive = _Primitive;
  28635. var Ribbon = (function (_super) {
  28636. __extends(Ribbon, _super);
  28637. // Members
  28638. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  28639. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28640. _super.call(this, id, scene, canBeRegenerated, mesh);
  28641. this.pathArray = pathArray;
  28642. this.closeArray = closeArray;
  28643. this.closePath = closePath;
  28644. this.offset = offset;
  28645. this.side = side;
  28646. }
  28647. Ribbon.prototype._regenerateVertexData = function () {
  28648. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  28649. };
  28650. Ribbon.prototype.copy = function (id) {
  28651. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  28652. };
  28653. return Ribbon;
  28654. })(_Primitive);
  28655. Primitives.Ribbon = Ribbon;
  28656. var Box = (function (_super) {
  28657. __extends(Box, _super);
  28658. // Members
  28659. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  28660. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28661. _super.call(this, id, scene, canBeRegenerated, mesh);
  28662. this.size = size;
  28663. this.side = side;
  28664. }
  28665. Box.prototype._regenerateVertexData = function () {
  28666. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  28667. };
  28668. Box.prototype.copy = function (id) {
  28669. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  28670. };
  28671. Box.prototype.serialize = function () {
  28672. var serializationObject = _super.prototype.serialize.call(this);
  28673. serializationObject.size = this.size;
  28674. return serializationObject;
  28675. };
  28676. Box.Parse = function (parsedBox, scene) {
  28677. if (scene.getGeometryByID(parsedBox.id)) {
  28678. return null; // null since geometry could be something else than a box...
  28679. }
  28680. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  28681. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  28682. scene.pushGeometry(box, true);
  28683. return box;
  28684. };
  28685. return Box;
  28686. })(_Primitive);
  28687. Primitives.Box = Box;
  28688. var Sphere = (function (_super) {
  28689. __extends(Sphere, _super);
  28690. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  28691. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28692. _super.call(this, id, scene, canBeRegenerated, mesh);
  28693. this.segments = segments;
  28694. this.diameter = diameter;
  28695. this.side = side;
  28696. }
  28697. Sphere.prototype._regenerateVertexData = function () {
  28698. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  28699. };
  28700. Sphere.prototype.copy = function (id) {
  28701. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  28702. };
  28703. Sphere.prototype.serialize = function () {
  28704. var serializationObject = _super.prototype.serialize.call(this);
  28705. serializationObject.segments = this.segments;
  28706. serializationObject.diameter = this.diameter;
  28707. return serializationObject;
  28708. };
  28709. Sphere.Parse = function (parsedSphere, scene) {
  28710. if (scene.getGeometryByID(parsedSphere.id)) {
  28711. return null; // null since geometry could be something else than a sphere...
  28712. }
  28713. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  28714. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  28715. scene.pushGeometry(sphere, true);
  28716. return sphere;
  28717. };
  28718. return Sphere;
  28719. })(_Primitive);
  28720. Primitives.Sphere = Sphere;
  28721. var Disc = (function (_super) {
  28722. __extends(Disc, _super);
  28723. // Members
  28724. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  28725. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28726. _super.call(this, id, scene, canBeRegenerated, mesh);
  28727. this.radius = radius;
  28728. this.tessellation = tessellation;
  28729. this.side = side;
  28730. }
  28731. Disc.prototype._regenerateVertexData = function () {
  28732. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  28733. };
  28734. Disc.prototype.copy = function (id) {
  28735. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  28736. };
  28737. return Disc;
  28738. })(_Primitive);
  28739. Primitives.Disc = Disc;
  28740. var Cylinder = (function (_super) {
  28741. __extends(Cylinder, _super);
  28742. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  28743. if (subdivisions === void 0) { subdivisions = 1; }
  28744. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28745. _super.call(this, id, scene, canBeRegenerated, mesh);
  28746. this.height = height;
  28747. this.diameterTop = diameterTop;
  28748. this.diameterBottom = diameterBottom;
  28749. this.tessellation = tessellation;
  28750. this.subdivisions = subdivisions;
  28751. this.side = side;
  28752. }
  28753. Cylinder.prototype._regenerateVertexData = function () {
  28754. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  28755. };
  28756. Cylinder.prototype.copy = function (id) {
  28757. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  28758. };
  28759. Cylinder.prototype.serialize = function () {
  28760. var serializationObject = _super.prototype.serialize.call(this);
  28761. serializationObject.height = this.height;
  28762. serializationObject.diameterTop = this.diameterTop;
  28763. serializationObject.diameterBottom = this.diameterBottom;
  28764. serializationObject.tessellation = this.tessellation;
  28765. return serializationObject;
  28766. };
  28767. Cylinder.Parse = function (parsedCylinder, scene) {
  28768. if (scene.getGeometryByID(parsedCylinder.id)) {
  28769. return null; // null since geometry could be something else than a cylinder...
  28770. }
  28771. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  28772. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  28773. scene.pushGeometry(cylinder, true);
  28774. return cylinder;
  28775. };
  28776. return Cylinder;
  28777. })(_Primitive);
  28778. Primitives.Cylinder = Cylinder;
  28779. var Torus = (function (_super) {
  28780. __extends(Torus, _super);
  28781. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  28782. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28783. _super.call(this, id, scene, canBeRegenerated, mesh);
  28784. this.diameter = diameter;
  28785. this.thickness = thickness;
  28786. this.tessellation = tessellation;
  28787. this.side = side;
  28788. }
  28789. Torus.prototype._regenerateVertexData = function () {
  28790. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  28791. };
  28792. Torus.prototype.copy = function (id) {
  28793. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  28794. };
  28795. Torus.prototype.serialize = function () {
  28796. var serializationObject = _super.prototype.serialize.call(this);
  28797. serializationObject.diameter = this.diameter;
  28798. serializationObject.thickness = this.thickness;
  28799. serializationObject.tessellation = this.tessellation;
  28800. return serializationObject;
  28801. };
  28802. Torus.Parse = function (parsedTorus, scene) {
  28803. if (scene.getGeometryByID(parsedTorus.id)) {
  28804. return null; // null since geometry could be something else than a torus...
  28805. }
  28806. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  28807. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  28808. scene.pushGeometry(torus, true);
  28809. return torus;
  28810. };
  28811. return Torus;
  28812. })(_Primitive);
  28813. Primitives.Torus = Torus;
  28814. var Ground = (function (_super) {
  28815. __extends(Ground, _super);
  28816. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  28817. _super.call(this, id, scene, canBeRegenerated, mesh);
  28818. this.width = width;
  28819. this.height = height;
  28820. this.subdivisions = subdivisions;
  28821. }
  28822. Ground.prototype._regenerateVertexData = function () {
  28823. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  28824. };
  28825. Ground.prototype.copy = function (id) {
  28826. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  28827. };
  28828. Ground.prototype.serialize = function () {
  28829. var serializationObject = _super.prototype.serialize.call(this);
  28830. serializationObject.width = this.width;
  28831. serializationObject.height = this.height;
  28832. serializationObject.subdivisions = this.subdivisions;
  28833. return serializationObject;
  28834. };
  28835. Ground.Parse = function (parsedGround, scene) {
  28836. if (scene.getGeometryByID(parsedGround.id)) {
  28837. return null; // null since geometry could be something else than a ground...
  28838. }
  28839. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  28840. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  28841. scene.pushGeometry(ground, true);
  28842. return ground;
  28843. };
  28844. return Ground;
  28845. })(_Primitive);
  28846. Primitives.Ground = Ground;
  28847. var TiledGround = (function (_super) {
  28848. __extends(TiledGround, _super);
  28849. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  28850. _super.call(this, id, scene, canBeRegenerated, mesh);
  28851. this.xmin = xmin;
  28852. this.zmin = zmin;
  28853. this.xmax = xmax;
  28854. this.zmax = zmax;
  28855. this.subdivisions = subdivisions;
  28856. this.precision = precision;
  28857. }
  28858. TiledGround.prototype._regenerateVertexData = function () {
  28859. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  28860. };
  28861. TiledGround.prototype.copy = function (id) {
  28862. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  28863. };
  28864. return TiledGround;
  28865. })(_Primitive);
  28866. Primitives.TiledGround = TiledGround;
  28867. var Plane = (function (_super) {
  28868. __extends(Plane, _super);
  28869. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  28870. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28871. _super.call(this, id, scene, canBeRegenerated, mesh);
  28872. this.size = size;
  28873. this.side = side;
  28874. }
  28875. Plane.prototype._regenerateVertexData = function () {
  28876. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  28877. };
  28878. Plane.prototype.copy = function (id) {
  28879. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  28880. };
  28881. Plane.prototype.serialize = function () {
  28882. var serializationObject = _super.prototype.serialize.call(this);
  28883. serializationObject.size = this.size;
  28884. return serializationObject;
  28885. };
  28886. Plane.Parse = function (parsedPlane, scene) {
  28887. if (scene.getGeometryByID(parsedPlane.id)) {
  28888. return null; // null since geometry could be something else than a ground...
  28889. }
  28890. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  28891. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  28892. scene.pushGeometry(plane, true);
  28893. return plane;
  28894. };
  28895. return Plane;
  28896. })(_Primitive);
  28897. Primitives.Plane = Plane;
  28898. var TorusKnot = (function (_super) {
  28899. __extends(TorusKnot, _super);
  28900. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  28901. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28902. _super.call(this, id, scene, canBeRegenerated, mesh);
  28903. this.radius = radius;
  28904. this.tube = tube;
  28905. this.radialSegments = radialSegments;
  28906. this.tubularSegments = tubularSegments;
  28907. this.p = p;
  28908. this.q = q;
  28909. this.side = side;
  28910. }
  28911. TorusKnot.prototype._regenerateVertexData = function () {
  28912. 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 });
  28913. };
  28914. TorusKnot.prototype.copy = function (id) {
  28915. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  28916. };
  28917. TorusKnot.prototype.serialize = function () {
  28918. var serializationObject = _super.prototype.serialize.call(this);
  28919. serializationObject.radius = this.radius;
  28920. serializationObject.tube = this.tube;
  28921. serializationObject.radialSegments = this.radialSegments;
  28922. serializationObject.tubularSegments = this.tubularSegments;
  28923. serializationObject.p = this.p;
  28924. serializationObject.q = this.q;
  28925. return serializationObject;
  28926. };
  28927. ;
  28928. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  28929. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  28930. return null; // null since geometry could be something else than a ground...
  28931. }
  28932. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  28933. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  28934. scene.pushGeometry(torusKnot, true);
  28935. return torusKnot;
  28936. };
  28937. return TorusKnot;
  28938. })(_Primitive);
  28939. Primitives.TorusKnot = TorusKnot;
  28940. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  28941. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  28942. })(BABYLON || (BABYLON = {}));
  28943. var BABYLON;
  28944. (function (BABYLON) {
  28945. var GroundMesh = (function (_super) {
  28946. __extends(GroundMesh, _super);
  28947. function GroundMesh(name, scene) {
  28948. _super.call(this, name, scene);
  28949. this.generateOctree = false;
  28950. this._worldInverse = new BABYLON.Matrix();
  28951. }
  28952. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  28953. get: function () {
  28954. return this._subdivisions;
  28955. },
  28956. enumerable: true,
  28957. configurable: true
  28958. });
  28959. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  28960. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  28961. this._subdivisions = chunksCount;
  28962. this.subdivide(this._subdivisions);
  28963. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  28964. };
  28965. /**
  28966. * Returns a height (y) value in the Worl system :
  28967. * the ground altitude at the coordinates (x, z) expressed in the World system.
  28968. * Returns the ground y position if (x, z) are outside the ground surface.
  28969. * Not pertinent if the ground is rotated.
  28970. */
  28971. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  28972. // express x and y in the ground local system
  28973. x -= this.position.x;
  28974. z -= this.position.z;
  28975. x /= this.scaling.x;
  28976. z /= this.scaling.z;
  28977. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  28978. return this.position.y;
  28979. }
  28980. if (!this._heightQuads || this._heightQuads.length == 0) {
  28981. this._initHeightQuads();
  28982. this._computeHeightQuads();
  28983. }
  28984. var facet = this._getFacetAt(x, z);
  28985. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  28986. // return y in the World system
  28987. return y * this.scaling.y + this.position.y;
  28988. };
  28989. /**
  28990. * Returns a normalized vector (Vector3) orthogonal to the ground
  28991. * at the ground coordinates (x, z) expressed in the World system.
  28992. * Returns Vector3(0, 1, 0) if (x, z) are outside the ground surface.
  28993. * Not pertinent if the ground is rotated.
  28994. */
  28995. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  28996. var normal = new BABYLON.Vector3(0, 1, 0);
  28997. this.getNormalAtCoordinatesToRef(x, z, normal);
  28998. return normal;
  28999. };
  29000. /**
  29001. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  29002. * at the ground coordinates (x, z) expressed in the World system.
  29003. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  29004. * Not pertinent if the ground is rotated.
  29005. */
  29006. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  29007. // express x and y in the ground local system
  29008. x -= this.position.x;
  29009. z -= this.position.z;
  29010. x /= this.scaling.x;
  29011. z /= this.scaling.z;
  29012. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  29013. return;
  29014. }
  29015. if (!this._heightQuads || this._heightQuads.length == 0) {
  29016. this._initHeightQuads();
  29017. this._computeHeightQuads();
  29018. }
  29019. var facet = this._getFacetAt(x, z);
  29020. ref.x = facet.x;
  29021. ref.y = facet.y;
  29022. ref.z = facet.z;
  29023. };
  29024. /**
  29025. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  29026. * if the ground has been updated.
  29027. * This can be used in the render loop
  29028. */
  29029. GroundMesh.prototype.updateCoordinateHeights = function () {
  29030. if (!this._heightQuads || this._heightQuads.length == 0) {
  29031. this._initHeightQuads();
  29032. }
  29033. this._computeHeightQuads();
  29034. };
  29035. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  29036. GroundMesh.prototype._getFacetAt = function (x, z) {
  29037. // retrieve col and row from x, z coordinates in the ground local system
  29038. var col = Math.floor((x + this._maxX) * this._subdivisions / this._width);
  29039. var row = Math.floor(-(z + this._maxZ) * this._subdivisions / this._height + this._subdivisions);
  29040. var quad = this._heightQuads[row * this._subdivisions + col];
  29041. var facet;
  29042. if (z < quad.slope.x * x + quad.slope.y) {
  29043. facet = quad.facet1;
  29044. }
  29045. else {
  29046. facet = quad.facet2;
  29047. }
  29048. return facet;
  29049. };
  29050. // Creates and populates the heightMap array with "facet" elements :
  29051. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  29052. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  29053. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  29054. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  29055. GroundMesh.prototype._initHeightQuads = function () {
  29056. this._heightQuads = new Array();
  29057. for (var row = 0; row < this._subdivisions; row++) {
  29058. for (var col = 0; col < this._subdivisions; col++) {
  29059. var quad = { slope: BABYLON.Vector2.Zero(), facet1: new BABYLON.Vector4(0, 0, 0, 0), facet2: new BABYLON.Vector4(0, 0, 0, 0) };
  29060. this._heightQuads[row * this._subdivisions + col] = quad;
  29061. }
  29062. }
  29063. };
  29064. // Compute each quad element values and update the the heightMap array :
  29065. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  29066. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  29067. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  29068. GroundMesh.prototype._computeHeightQuads = function () {
  29069. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29070. var v1 = BABYLON.Tmp.Vector3[0];
  29071. var v2 = BABYLON.Tmp.Vector3[1];
  29072. var v3 = BABYLON.Tmp.Vector3[2];
  29073. var v4 = BABYLON.Tmp.Vector3[3];
  29074. var v1v2 = BABYLON.Tmp.Vector3[4];
  29075. var v1v3 = BABYLON.Tmp.Vector3[5];
  29076. var v1v4 = BABYLON.Tmp.Vector3[6];
  29077. var norm1 = BABYLON.Tmp.Vector3[7];
  29078. var norm2 = BABYLON.Tmp.Vector3[8];
  29079. var i = 0;
  29080. var j = 0;
  29081. var k = 0;
  29082. var cd = 0; // 2D slope coefficient : z = cd * x + h
  29083. var h = 0;
  29084. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  29085. var d2 = 0;
  29086. for (var row = 0; row < this._subdivisions; row++) {
  29087. for (var col = 0; col < this._subdivisions; col++) {
  29088. i = col * 3;
  29089. j = row * (this._subdivisions + 1) * 3;
  29090. k = (row + 1) * (this._subdivisions + 1) * 3;
  29091. v1.x = positions[j + i];
  29092. v1.y = positions[j + i + 1];
  29093. v1.z = positions[j + i + 2];
  29094. v2.x = positions[j + i + 3];
  29095. v2.y = positions[j + i + 4];
  29096. v2.z = positions[j + i + 5];
  29097. v3.x = positions[k + i];
  29098. v3.y = positions[k + i + 1];
  29099. v3.z = positions[k + i + 2];
  29100. v4.x = positions[k + i + 3];
  29101. v4.y = positions[k + i + 4];
  29102. v4.z = positions[k + i + 5];
  29103. // 2D slope V1V4
  29104. cd = (v4.z - v1.z) / (v4.x - v1.x);
  29105. h = v1.z - cd * v1.x; // v1 belongs to the slope
  29106. // facet equations :
  29107. // we compute each facet normal vector
  29108. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  29109. // we compute the value d by applying the equation to v1 which belongs to the plane
  29110. // then we store the facet equation in a Vector4
  29111. v2.subtractToRef(v1, v1v2);
  29112. v3.subtractToRef(v1, v1v3);
  29113. v4.subtractToRef(v1, v1v4);
  29114. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1);
  29115. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  29116. norm1.normalize();
  29117. norm2.normalize();
  29118. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  29119. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  29120. var quad = this._heightQuads[row * this._subdivisions + col];
  29121. quad.slope.copyFromFloats(cd, h);
  29122. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  29123. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  29124. }
  29125. }
  29126. };
  29127. return GroundMesh;
  29128. })(BABYLON.Mesh);
  29129. BABYLON.GroundMesh = GroundMesh;
  29130. })(BABYLON || (BABYLON = {}));
  29131. var BABYLON;
  29132. (function (BABYLON) {
  29133. var LinesMesh = (function (_super) {
  29134. __extends(LinesMesh, _super);
  29135. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  29136. if (parent === void 0) { parent = null; }
  29137. _super.call(this, name, scene, parent, source, doNotCloneChildren);
  29138. this.color = new BABYLON.Color3(1, 1, 1);
  29139. this.alpha = 1;
  29140. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  29141. attributes: ["position"],
  29142. uniforms: ["worldViewProjection", "color"],
  29143. needAlphaBlending: true
  29144. });
  29145. }
  29146. Object.defineProperty(LinesMesh.prototype, "material", {
  29147. get: function () {
  29148. return this._colorShader;
  29149. },
  29150. enumerable: true,
  29151. configurable: true
  29152. });
  29153. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  29154. get: function () {
  29155. return false;
  29156. },
  29157. enumerable: true,
  29158. configurable: true
  29159. });
  29160. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  29161. get: function () {
  29162. return false;
  29163. },
  29164. enumerable: true,
  29165. configurable: true
  29166. });
  29167. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  29168. var engine = this.getScene().getEngine();
  29169. var indexToBind = this._geometry.getIndexBuffer();
  29170. // VBOs
  29171. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  29172. // Color
  29173. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  29174. };
  29175. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  29176. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  29177. return;
  29178. }
  29179. var engine = this.getScene().getEngine();
  29180. // Draw order
  29181. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  29182. };
  29183. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  29184. return null;
  29185. };
  29186. LinesMesh.prototype.dispose = function (doNotRecurse) {
  29187. this._colorShader.dispose();
  29188. _super.prototype.dispose.call(this, doNotRecurse);
  29189. };
  29190. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  29191. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  29192. };
  29193. return LinesMesh;
  29194. })(BABYLON.Mesh);
  29195. BABYLON.LinesMesh = LinesMesh;
  29196. })(BABYLON || (BABYLON = {}));
  29197. var BABYLON;
  29198. (function (BABYLON) {
  29199. var DebugLayer = (function () {
  29200. function DebugLayer(scene) {
  29201. var _this = this;
  29202. this._transformationMatrix = BABYLON.Matrix.Identity();
  29203. this._enabled = false;
  29204. this._labelsEnabled = false;
  29205. this._displayStatistics = true;
  29206. this._displayTree = false;
  29207. this._displayLogs = false;
  29208. this._skeletonViewers = new Array();
  29209. this._identityMatrix = BABYLON.Matrix.Identity();
  29210. this.axisRatio = 0.02;
  29211. this.accentColor = "orange";
  29212. this._scene = scene;
  29213. this._syncPositions = function () {
  29214. var engine = _this._scene.getEngine();
  29215. var canvasRect = engine.getRenderingCanvasClientRect();
  29216. if (_this._showUI) {
  29217. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  29218. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  29219. _this._statsDiv.style.width = "400px";
  29220. _this._statsDiv.style.height = "auto";
  29221. _this._statsSubsetDiv.style.maxHeight = "240px";
  29222. _this._optionsDiv.style.left = "0px";
  29223. _this._optionsDiv.style.top = "10px";
  29224. _this._optionsDiv.style.width = "200px";
  29225. _this._optionsDiv.style.height = "auto";
  29226. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  29227. _this._logDiv.style.left = "0px";
  29228. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  29229. _this._logDiv.style.width = "600px";
  29230. _this._logDiv.style.height = "160px";
  29231. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  29232. _this._treeDiv.style.top = "10px";
  29233. _this._treeDiv.style.width = "300px";
  29234. _this._treeDiv.style.height = "auto";
  29235. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  29236. }
  29237. _this._globalDiv.style.left = canvasRect.left + "px";
  29238. _this._globalDiv.style.top = canvasRect.top + "px";
  29239. _this._drawingCanvas.style.left = "0px";
  29240. _this._drawingCanvas.style.top = "0px";
  29241. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  29242. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  29243. var devicePixelRatio = window.devicePixelRatio || 1;
  29244. var context = _this._drawingContext;
  29245. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  29246. context.mozBackingStorePixelRatio ||
  29247. context.msBackingStorePixelRatio ||
  29248. context.oBackingStorePixelRatio ||
  29249. context.backingStorePixelRatio || 1;
  29250. _this._ratio = devicePixelRatio / backingStoreRatio;
  29251. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  29252. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  29253. };
  29254. this._onCanvasClick = function (evt) {
  29255. _this._clickPosition = {
  29256. x: evt.clientX * _this._ratio,
  29257. y: evt.clientY * _this._ratio
  29258. };
  29259. };
  29260. this._syncUI = function () {
  29261. if (_this._showUI) {
  29262. if (_this._displayStatistics) {
  29263. _this._displayStats();
  29264. _this._statsDiv.style.display = "";
  29265. }
  29266. else {
  29267. _this._statsDiv.style.display = "none";
  29268. }
  29269. if (_this._displayLogs) {
  29270. _this._logDiv.style.display = "";
  29271. }
  29272. else {
  29273. _this._logDiv.style.display = "none";
  29274. }
  29275. if (_this._displayTree) {
  29276. _this._treeDiv.style.display = "";
  29277. if (_this._needToRefreshMeshesTree) {
  29278. _this._needToRefreshMeshesTree = false;
  29279. _this._refreshMeshesTreeContent();
  29280. }
  29281. }
  29282. else {
  29283. _this._treeDiv.style.display = "none";
  29284. }
  29285. }
  29286. };
  29287. this._syncData = function () {
  29288. if (_this._labelsEnabled || !_this._showUI) {
  29289. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  29290. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  29291. var engine = _this._scene.getEngine();
  29292. var viewport = _this._camera.viewport;
  29293. var globalViewport = viewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  29294. // Meshes
  29295. var meshes = _this._camera.getActiveMeshes();
  29296. var index;
  29297. var projectedPosition;
  29298. for (index = 0; index < meshes.length; index++) {
  29299. var mesh = meshes.data[index];
  29300. var position = mesh.getBoundingInfo().boundingSphere.center;
  29301. projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  29302. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  29303. _this._renderAxis(projectedPosition, mesh, globalViewport);
  29304. }
  29305. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  29306. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  29307. }
  29308. }
  29309. // Cameras
  29310. var cameras = _this._scene.cameras;
  29311. for (index = 0; index < cameras.length; index++) {
  29312. var camera = cameras[index];
  29313. if (camera === _this._camera) {
  29314. continue;
  29315. }
  29316. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  29317. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  29318. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  29319. _this._camera.detachControl(engine.getRenderingCanvas());
  29320. _this._camera = camera;
  29321. _this._camera.attachControl(engine.getRenderingCanvas());
  29322. }, function () { return "purple"; });
  29323. }
  29324. }
  29325. // Lights
  29326. var lights = _this._scene.lights;
  29327. for (index = 0; index < lights.length; index++) {
  29328. var light = lights[index];
  29329. if (light.position) {
  29330. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  29331. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  29332. _this._renderLabel(light.name, projectedPosition, -20, function () {
  29333. light.setEnabled(!light.isEnabled());
  29334. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  29335. }
  29336. }
  29337. }
  29338. }
  29339. _this._clickPosition = undefined;
  29340. };
  29341. }
  29342. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  29343. while (this._treeSubsetDiv.hasChildNodes()) {
  29344. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  29345. }
  29346. // Add meshes
  29347. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  29348. sortedArray.sort(function (a, b) {
  29349. if (a.name === b.name) {
  29350. return 0;
  29351. }
  29352. return (a.name > b.name) ? 1 : -1;
  29353. });
  29354. for (var index = 0; index < sortedArray.length; index++) {
  29355. var mesh = sortedArray[index];
  29356. if (!mesh.isEnabled()) {
  29357. continue;
  29358. }
  29359. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  29360. m.isVisible = element.checked;
  29361. }, mesh);
  29362. }
  29363. };
  29364. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  29365. this._drawingContext.beginPath();
  29366. this._drawingContext.moveTo(zero.x, zero.y);
  29367. this._drawingContext.lineTo(unit.x, unit.y);
  29368. this._drawingContext.strokeStyle = color;
  29369. this._drawingContext.lineWidth = 4;
  29370. this._drawingContext.stroke();
  29371. this._drawingContext.font = "normal 14px Segoe UI";
  29372. this._drawingContext.fillStyle = color;
  29373. this._drawingContext.fillText(label, unitText.x, unitText.y);
  29374. };
  29375. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  29376. var position = mesh.getBoundingInfo().boundingSphere.center;
  29377. var worldMatrix = mesh.getWorldMatrix();
  29378. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  29379. var unit = (unprojectedVector.subtract(position)).length();
  29380. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  29381. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  29382. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  29383. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  29384. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  29385. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  29386. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  29387. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  29388. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  29389. };
  29390. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  29391. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  29392. this._drawingContext.font = "normal 12px Segoe UI";
  29393. var textMetrics = this._drawingContext.measureText(text);
  29394. var centerX = projectedPosition.x - textMetrics.width / 2;
  29395. var centerY = projectedPosition.y;
  29396. var clientRect = this._drawingCanvas.getBoundingClientRect();
  29397. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  29398. onClick();
  29399. }
  29400. this._drawingContext.beginPath();
  29401. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  29402. this._drawingContext.fillStyle = getFillStyle();
  29403. this._drawingContext.globalAlpha = 0.5;
  29404. this._drawingContext.fill();
  29405. this._drawingContext.globalAlpha = 1.0;
  29406. this._drawingContext.strokeStyle = '#FFFFFF';
  29407. this._drawingContext.lineWidth = 1;
  29408. this._drawingContext.stroke();
  29409. this._drawingContext.fillStyle = "#FFFFFF";
  29410. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  29411. this._drawingContext.beginPath();
  29412. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  29413. this._drawingContext.fill();
  29414. }
  29415. };
  29416. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  29417. if (!this._clickPosition) {
  29418. return false;
  29419. }
  29420. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  29421. return false;
  29422. }
  29423. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  29424. return false;
  29425. }
  29426. return true;
  29427. };
  29428. DebugLayer.prototype.isVisible = function () {
  29429. return this._enabled;
  29430. };
  29431. DebugLayer.prototype.hide = function () {
  29432. if (!this._enabled) {
  29433. return;
  29434. }
  29435. this._enabled = false;
  29436. var engine = this._scene.getEngine();
  29437. this._scene.unregisterBeforeRender(this._syncData);
  29438. this._scene.unregisterAfterRender(this._syncUI);
  29439. this._rootElement.removeChild(this._globalDiv);
  29440. this._scene.forceShowBoundingBoxes = false;
  29441. this._scene.forceWireframe = false;
  29442. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  29443. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  29444. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  29445. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  29446. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  29447. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  29448. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  29449. BABYLON.StandardMaterial.LightmapTextureEnabled = true;
  29450. BABYLON.StandardMaterial.RefractionTextureEnabled = true;
  29451. this._scene.shadowsEnabled = true;
  29452. this._scene.particlesEnabled = true;
  29453. this._scene.postProcessesEnabled = true;
  29454. this._scene.collisionsEnabled = true;
  29455. this._scene.lightsEnabled = true;
  29456. this._scene.texturesEnabled = true;
  29457. this._scene.lensFlaresEnabled = true;
  29458. this._scene.proceduralTexturesEnabled = true;
  29459. this._scene.renderTargetsEnabled = true;
  29460. this._scene.probesEnabled = true;
  29461. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  29462. this._clearSkeletonViewers();
  29463. };
  29464. DebugLayer.prototype._clearSkeletonViewers = function () {
  29465. for (var index = 0; index < this._skeletonViewers.length; index++) {
  29466. this._skeletonViewers[index].dispose();
  29467. }
  29468. this._skeletonViewers = [];
  29469. };
  29470. DebugLayer.prototype.show = function (showUI, camera, rootElement) {
  29471. if (showUI === void 0) { showUI = true; }
  29472. if (camera === void 0) { camera = null; }
  29473. if (rootElement === void 0) { rootElement = null; }
  29474. if (this._enabled) {
  29475. return;
  29476. }
  29477. this._enabled = true;
  29478. if (camera) {
  29479. this._camera = camera;
  29480. }
  29481. else {
  29482. this._camera = this._scene.activeCamera;
  29483. }
  29484. this._showUI = showUI;
  29485. var engine = this._scene.getEngine();
  29486. this._globalDiv = document.createElement("div");
  29487. this._rootElement = rootElement || document.body;
  29488. this._rootElement.appendChild(this._globalDiv);
  29489. this._generateDOMelements();
  29490. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  29491. this._syncPositions();
  29492. this._scene.registerBeforeRender(this._syncData);
  29493. this._scene.registerAfterRender(this._syncUI);
  29494. };
  29495. DebugLayer.prototype._clearLabels = function () {
  29496. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  29497. for (var index = 0; index < this._scene.meshes.length; index++) {
  29498. var mesh = this._scene.meshes[index];
  29499. mesh.renderOverlay = false;
  29500. }
  29501. };
  29502. DebugLayer.prototype._generateheader = function (root, text) {
  29503. var header = document.createElement("div");
  29504. header.innerHTML = text + "&nbsp;";
  29505. header.style.textAlign = "right";
  29506. header.style.width = "100%";
  29507. header.style.color = "white";
  29508. header.style.backgroundColor = "Black";
  29509. header.style.padding = "5px 5px 4px 0px";
  29510. header.style.marginLeft = "-5px";
  29511. header.style.fontWeight = "bold";
  29512. root.appendChild(header);
  29513. };
  29514. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  29515. var label = document.createElement("label");
  29516. label.innerHTML = title;
  29517. label.style.color = color;
  29518. root.appendChild(label);
  29519. root.appendChild(document.createElement("br"));
  29520. };
  29521. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  29522. if (tag === void 0) { tag = null; }
  29523. var label = document.createElement("label");
  29524. var boundingBoxesCheckbox = document.createElement("input");
  29525. boundingBoxesCheckbox.type = "checkbox";
  29526. boundingBoxesCheckbox.checked = initialState;
  29527. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  29528. task(evt.target, tag);
  29529. });
  29530. label.appendChild(boundingBoxesCheckbox);
  29531. var container = document.createElement("span");
  29532. var leftPart = document.createElement("span");
  29533. var rightPart = document.createElement("span");
  29534. rightPart.style.cssFloat = "right";
  29535. leftPart.innerHTML = leftTitle;
  29536. rightPart.innerHTML = rightTitle;
  29537. rightPart.style.fontSize = "12px";
  29538. rightPart.style.maxWidth = "200px";
  29539. container.appendChild(leftPart);
  29540. container.appendChild(rightPart);
  29541. label.appendChild(container);
  29542. root.appendChild(label);
  29543. root.appendChild(document.createElement("br"));
  29544. };
  29545. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  29546. if (tag === void 0) { tag = null; }
  29547. var label = document.createElement("label");
  29548. var checkBox = document.createElement("input");
  29549. checkBox.type = "checkbox";
  29550. checkBox.checked = initialState;
  29551. checkBox.addEventListener("change", function (evt) {
  29552. task(evt.target, tag);
  29553. });
  29554. label.appendChild(checkBox);
  29555. label.appendChild(document.createTextNode(title));
  29556. root.appendChild(label);
  29557. root.appendChild(document.createElement("br"));
  29558. };
  29559. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  29560. if (tag === void 0) { tag = null; }
  29561. var button = document.createElement("button");
  29562. button.innerHTML = title;
  29563. button.style.height = "24px";
  29564. button.style.width = "150px";
  29565. button.style.marginBottom = "5px";
  29566. button.style.color = "#444444";
  29567. button.style.border = "1px solid white";
  29568. button.className = "debugLayerButton";
  29569. button.addEventListener("click", function (evt) {
  29570. task(evt.target, tag);
  29571. });
  29572. root.appendChild(button);
  29573. root.appendChild(document.createElement("br"));
  29574. };
  29575. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  29576. if (tag === void 0) { tag = null; }
  29577. var label = document.createElement("label");
  29578. var boundingBoxesRadio = document.createElement("input");
  29579. boundingBoxesRadio.type = "radio";
  29580. boundingBoxesRadio.name = name;
  29581. boundingBoxesRadio.checked = initialState;
  29582. boundingBoxesRadio.addEventListener("change", function (evt) {
  29583. task(evt.target, tag);
  29584. });
  29585. label.appendChild(boundingBoxesRadio);
  29586. label.appendChild(document.createTextNode(title));
  29587. root.appendChild(label);
  29588. root.appendChild(document.createElement("br"));
  29589. };
  29590. DebugLayer.prototype._generateDOMelements = function () {
  29591. var _this = this;
  29592. this._globalDiv.id = "DebugLayer";
  29593. this._globalDiv.style.position = "absolute";
  29594. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  29595. this._globalDiv.style.fontSize = "14px";
  29596. this._globalDiv.style.color = "white";
  29597. // Drawing canvas
  29598. this._drawingCanvas = document.createElement("canvas");
  29599. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  29600. this._drawingCanvas.style.position = "absolute";
  29601. this._drawingCanvas.style.pointerEvents = "none";
  29602. this._drawingCanvas.style.backgroundColor = "transparent";
  29603. this._drawingContext = this._drawingCanvas.getContext("2d");
  29604. this._globalDiv.appendChild(this._drawingCanvas);
  29605. if (this._showUI) {
  29606. var background = "rgba(128, 128, 128, 0.4)";
  29607. var border = "rgb(180, 180, 180) solid 1px";
  29608. // Stats
  29609. this._statsDiv = document.createElement("div");
  29610. this._statsDiv.id = "DebugLayerStats";
  29611. this._statsDiv.style.border = border;
  29612. this._statsDiv.style.position = "absolute";
  29613. this._statsDiv.style.background = background;
  29614. this._statsDiv.style.padding = "0px 0px 0px 5px";
  29615. this._generateheader(this._statsDiv, "STATISTICS");
  29616. this._statsSubsetDiv = document.createElement("div");
  29617. this._statsSubsetDiv.style.paddingTop = "5px";
  29618. this._statsSubsetDiv.style.paddingBottom = "5px";
  29619. this._statsSubsetDiv.style.overflowY = "auto";
  29620. this._statsDiv.appendChild(this._statsSubsetDiv);
  29621. // Tree
  29622. this._treeDiv = document.createElement("div");
  29623. this._treeDiv.id = "DebugLayerTree";
  29624. this._treeDiv.style.border = border;
  29625. this._treeDiv.style.position = "absolute";
  29626. this._treeDiv.style.background = background;
  29627. this._treeDiv.style.padding = "0px 0px 0px 5px";
  29628. this._treeDiv.style.display = "none";
  29629. this._generateheader(this._treeDiv, "MESHES TREE");
  29630. this._treeSubsetDiv = document.createElement("div");
  29631. this._treeSubsetDiv.style.paddingTop = "5px";
  29632. this._treeSubsetDiv.style.paddingRight = "5px";
  29633. this._treeSubsetDiv.style.overflowY = "auto";
  29634. this._treeSubsetDiv.style.maxHeight = "300px";
  29635. this._treeDiv.appendChild(this._treeSubsetDiv);
  29636. this._needToRefreshMeshesTree = true;
  29637. // Logs
  29638. this._logDiv = document.createElement("div");
  29639. this._logDiv.style.border = border;
  29640. this._logDiv.id = "DebugLayerLogs";
  29641. this._logDiv.style.position = "absolute";
  29642. this._logDiv.style.background = background;
  29643. this._logDiv.style.padding = "0px 0px 0px 5px";
  29644. this._logDiv.style.display = "none";
  29645. this._generateheader(this._logDiv, "LOGS");
  29646. this._logSubsetDiv = document.createElement("div");
  29647. this._logSubsetDiv.style.height = "127px";
  29648. this._logSubsetDiv.style.paddingTop = "5px";
  29649. this._logSubsetDiv.style.overflowY = "auto";
  29650. this._logSubsetDiv.style.fontSize = "12px";
  29651. this._logSubsetDiv.style.fontFamily = "consolas";
  29652. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  29653. this._logDiv.appendChild(this._logSubsetDiv);
  29654. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  29655. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  29656. };
  29657. // Options
  29658. this._optionsDiv = document.createElement("div");
  29659. this._optionsDiv.id = "DebugLayerOptions";
  29660. this._optionsDiv.style.border = border;
  29661. this._optionsDiv.style.position = "absolute";
  29662. this._optionsDiv.style.background = background;
  29663. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  29664. this._optionsDiv.style.overflowY = "auto";
  29665. this._generateheader(this._optionsDiv, "OPTIONS");
  29666. this._optionsSubsetDiv = document.createElement("div");
  29667. this._optionsSubsetDiv.style.paddingTop = "5px";
  29668. this._optionsSubsetDiv.style.paddingBottom = "5px";
  29669. this._optionsSubsetDiv.style.overflowY = "auto";
  29670. this._optionsSubsetDiv.style.maxHeight = "200px";
  29671. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  29672. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  29673. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  29674. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  29675. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  29676. _this._displayTree = element.checked;
  29677. _this._needToRefreshMeshesTree = true;
  29678. });
  29679. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29680. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  29681. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  29682. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  29683. _this._labelsEnabled = element.checked;
  29684. if (!_this._labelsEnabled) {
  29685. _this._clearLabels();
  29686. }
  29687. });
  29688. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  29689. if (element.checked) {
  29690. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  29691. }
  29692. else {
  29693. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  29694. }
  29695. });
  29696. ;
  29697. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29698. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  29699. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  29700. if (element.checked) {
  29701. _this._scene.forceWireframe = false;
  29702. _this._scene.forcePointsCloud = false;
  29703. }
  29704. });
  29705. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  29706. if (element.checked) {
  29707. _this._scene.forceWireframe = true;
  29708. _this._scene.forcePointsCloud = false;
  29709. }
  29710. });
  29711. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  29712. if (element.checked) {
  29713. _this._scene.forceWireframe = false;
  29714. _this._scene.forcePointsCloud = true;
  29715. }
  29716. });
  29717. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29718. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  29719. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  29720. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  29721. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  29722. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  29723. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  29724. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  29725. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  29726. this._generateCheckBox(this._optionsSubsetDiv, "Refraction", BABYLON.StandardMaterial.RefractionTextureEnabled, function (element) { BABYLON.StandardMaterial.RefractionTextureEnabled = element.checked; });
  29727. this._generateCheckBox(this._optionsSubsetDiv, "Lightmap", BABYLON.StandardMaterial.LightmapTextureEnabled, function (element) { BABYLON.StandardMaterial.LightmapTextureEnabled = element.checked; });
  29728. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  29729. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29730. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  29731. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  29732. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  29733. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  29734. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  29735. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  29736. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  29737. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  29738. this._generateCheckBox(this._optionsSubsetDiv, "Probes", this._scene.probesEnabled, function (element) { _this._scene.probesEnabled = element.checked; });
  29739. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  29740. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  29741. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  29742. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  29743. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  29744. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  29745. if (BABYLON.AudioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  29746. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29747. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  29748. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  29749. if (element.checked) {
  29750. _this._scene.headphone = true;
  29751. }
  29752. });
  29753. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  29754. if (element.checked) {
  29755. _this._scene.headphone = false;
  29756. }
  29757. });
  29758. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  29759. _this._scene.audioEnabled = !element.checked;
  29760. });
  29761. }
  29762. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29763. this._generateTexBox(this._optionsSubsetDiv, "<b>Viewers:</b>", this.accentColor);
  29764. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", false, function (element) {
  29765. if (!element.checked) {
  29766. _this._clearSkeletonViewers();
  29767. return;
  29768. }
  29769. for (var index = 0; index < _this._scene.meshes.length; index++) {
  29770. var mesh = _this._scene.meshes[index];
  29771. if (mesh.skeleton) {
  29772. var found = false;
  29773. for (var sIndex = 0; sIndex < _this._skeletonViewers.length; sIndex++) {
  29774. if (_this._skeletonViewers[sIndex].skeleton === mesh.skeleton) {
  29775. found = true;
  29776. break;
  29777. }
  29778. }
  29779. if (found) {
  29780. continue;
  29781. }
  29782. var viewer = new BABYLON.Debug.SkeletonViewer(mesh.skeleton, mesh, _this._scene);
  29783. viewer.isEnabled = true;
  29784. _this._skeletonViewers.push(viewer);
  29785. }
  29786. }
  29787. });
  29788. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29789. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  29790. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  29791. this._generateButton(this._optionsSubsetDiv, "Run SceneOptimizer", function (element) { BABYLON.SceneOptimizer.OptimizeAsync(_this._scene); });
  29792. this._generateButton(this._optionsSubsetDiv, "Log camera object", function (element) {
  29793. if (_this._camera) {
  29794. console.log(_this._camera);
  29795. }
  29796. else {
  29797. console.warn("No camera defined, or debug layer created before camera creation!");
  29798. }
  29799. });
  29800. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29801. this._globalDiv.appendChild(this._statsDiv);
  29802. this._globalDiv.appendChild(this._logDiv);
  29803. this._globalDiv.appendChild(this._optionsDiv);
  29804. this._globalDiv.appendChild(this._treeDiv);
  29805. }
  29806. };
  29807. DebugLayer.prototype._displayStats = function () {
  29808. var scene = this._scene;
  29809. var engine = scene.getEngine();
  29810. var glInfo = engine.getGlInfo();
  29811. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  29812. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  29813. + "<b>Count</b><br>"
  29814. + "Total meshes: " + scene.meshes.length + "<br>"
  29815. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  29816. + "Total materials: " + scene.materials.length + "<br>"
  29817. + "Total textures: " + scene.textures.length + "<br>"
  29818. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  29819. + "Active indices: " + scene.getActiveIndices() + "<br>"
  29820. + "Active bones: " + scene.getActiveBones() + "<br>"
  29821. + "Active particles: " + scene.getActiveParticles() + "<br>"
  29822. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br><br>"
  29823. + "<b>Duration</b><br>"
  29824. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  29825. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  29826. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  29827. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  29828. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  29829. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  29830. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br>"
  29831. + "Resolution: " + engine.getRenderWidth() + "x" + engine.getRenderHeight() + "<br>"
  29832. + "</div>"
  29833. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  29834. + "<b>Extensions</b><br>"
  29835. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  29836. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  29837. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  29838. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br><br>"
  29839. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  29840. + "Fragment depth: " + (engine.getCaps().fragmentDepthSupported ? "Yes" : "No") + "<br>"
  29841. + "High precision shaders: " + (engine.getCaps().highPrecisionShaderSupported ? "Yes" : "No") + "<br>"
  29842. + "Draw buffers: " + (engine.getCaps().drawBuffersExtension ? "Yes" : "No") + "<br>"
  29843. + "</div><br>"
  29844. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  29845. + "<b>Caps.</b><br>"
  29846. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  29847. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  29848. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br>"
  29849. + "<b>Info</b><br>"
  29850. + "WebGL feature level: " + engine.webGLVersion + "<br>"
  29851. + glInfo.version + "<br>"
  29852. + "</div><br>"
  29853. + glInfo.renderer + "<br>";
  29854. if (this.customStatsFunction) {
  29855. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  29856. }
  29857. };
  29858. return DebugLayer;
  29859. })();
  29860. BABYLON.DebugLayer = DebugLayer;
  29861. })(BABYLON || (BABYLON = {}));
  29862. var BABYLON;
  29863. (function (BABYLON) {
  29864. var DefaultLoadingScreen = (function () {
  29865. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  29866. var _this = this;
  29867. if (_loadingText === void 0) { _loadingText = ""; }
  29868. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  29869. this._renderingCanvas = _renderingCanvas;
  29870. this._loadingText = _loadingText;
  29871. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  29872. // Resize
  29873. this._resizeLoadingUI = function () {
  29874. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  29875. _this._loadingDiv.style.position = "absolute";
  29876. _this._loadingDiv.style.left = canvasRect.left + "px";
  29877. _this._loadingDiv.style.top = canvasRect.top + "px";
  29878. _this._loadingDiv.style.width = canvasRect.width + "px";
  29879. _this._loadingDiv.style.height = canvasRect.height + "px";
  29880. };
  29881. }
  29882. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  29883. var _this = this;
  29884. if (this._loadingDiv) {
  29885. // Do not add a loading screen if there is already one
  29886. return;
  29887. }
  29888. this._loadingDiv = document.createElement("div");
  29889. this._loadingDiv.id = "babylonjsLoadingDiv";
  29890. this._loadingDiv.style.opacity = "0";
  29891. this._loadingDiv.style.transition = "opacity 1.5s ease";
  29892. // Loading text
  29893. this._loadingTextDiv = document.createElement("div");
  29894. this._loadingTextDiv.style.position = "absolute";
  29895. this._loadingTextDiv.style.left = "0";
  29896. this._loadingTextDiv.style.top = "50%";
  29897. this._loadingTextDiv.style.marginTop = "80px";
  29898. this._loadingTextDiv.style.width = "100%";
  29899. this._loadingTextDiv.style.height = "20px";
  29900. this._loadingTextDiv.style.fontFamily = "Arial";
  29901. this._loadingTextDiv.style.fontSize = "14px";
  29902. this._loadingTextDiv.style.color = "white";
  29903. this._loadingTextDiv.style.textAlign = "center";
  29904. this._loadingTextDiv.innerHTML = "Loading";
  29905. this._loadingDiv.appendChild(this._loadingTextDiv);
  29906. //set the predefined text
  29907. this._loadingTextDiv.innerHTML = this._loadingText;
  29908. // Loading img
  29909. var imgBack = new Image();
  29910. 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==";
  29911. imgBack.style.position = "absolute";
  29912. imgBack.style.left = "50%";
  29913. imgBack.style.top = "50%";
  29914. imgBack.style.marginLeft = "-50px";
  29915. imgBack.style.marginTop = "-50px";
  29916. imgBack.style.transition = "transform 1.0s ease";
  29917. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  29918. var deg = 360;
  29919. var onTransitionEnd = function () {
  29920. deg += 360;
  29921. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  29922. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  29923. };
  29924. imgBack.addEventListener("transitionend", onTransitionEnd);
  29925. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  29926. this._loadingDiv.appendChild(imgBack);
  29927. // front image
  29928. var imgFront = new Image();
  29929. 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=";
  29930. imgFront.style.position = "absolute";
  29931. imgFront.style.left = "50%";
  29932. imgFront.style.top = "50%";
  29933. imgFront.style.marginLeft = "-50px";
  29934. imgFront.style.marginTop = "-50px";
  29935. this._loadingDiv.appendChild(imgFront);
  29936. this._resizeLoadingUI();
  29937. window.addEventListener("resize", this._resizeLoadingUI);
  29938. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  29939. document.body.appendChild(this._loadingDiv);
  29940. setTimeout(function () {
  29941. _this._loadingDiv.style.opacity = "1";
  29942. imgBack.style.transform = "rotateZ(360deg)";
  29943. imgBack.style.webkitTransform = "rotateZ(360deg)";
  29944. }, 0);
  29945. };
  29946. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  29947. var _this = this;
  29948. if (!this._loadingDiv) {
  29949. return;
  29950. }
  29951. var onTransitionEnd = function () {
  29952. if (!_this._loadingDiv) {
  29953. return;
  29954. }
  29955. document.body.removeChild(_this._loadingDiv);
  29956. window.removeEventListener("resize", _this._resizeLoadingUI);
  29957. _this._loadingDiv = null;
  29958. };
  29959. this._loadingDiv.style.opacity = "0";
  29960. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  29961. };
  29962. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  29963. set: function (text) {
  29964. this._loadingText = text;
  29965. if (this._loadingTextDiv) {
  29966. this._loadingTextDiv.innerHTML = this._loadingText;
  29967. }
  29968. },
  29969. enumerable: true,
  29970. configurable: true
  29971. });
  29972. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  29973. get: function () {
  29974. return this._loadingDivBackgroundColor;
  29975. },
  29976. set: function (color) {
  29977. this._loadingDivBackgroundColor = color;
  29978. if (!this._loadingDiv) {
  29979. return;
  29980. }
  29981. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  29982. },
  29983. enumerable: true,
  29984. configurable: true
  29985. });
  29986. return DefaultLoadingScreen;
  29987. })();
  29988. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  29989. })(BABYLON || (BABYLON = {}));
  29990. var BABYLON;
  29991. (function (BABYLON) {
  29992. var SIMDVector3 = (function () {
  29993. function SIMDVector3() {
  29994. }
  29995. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  29996. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  29997. var m0 = SIMD.float32x4.load(transformation.m, 0);
  29998. var m1 = SIMD.float32x4.load(transformation.m, 4);
  29999. var m2 = SIMD.float32x4.load(transformation.m, 8);
  30000. var m3 = SIMD.float32x4.load(transformation.m, 12);
  30001. 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));
  30002. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  30003. SIMD.float32x4.storeXYZ(result._data, 0, r);
  30004. };
  30005. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  30006. var v0 = SIMD.float32x4.splat(x);
  30007. var v1 = SIMD.float32x4.splat(y);
  30008. var v2 = SIMD.float32x4.splat(z);
  30009. var m0 = SIMD.float32x4.load(transformation.m, 0);
  30010. var m1 = SIMD.float32x4.load(transformation.m, 4);
  30011. var m2 = SIMD.float32x4.load(transformation.m, 8);
  30012. var m3 = SIMD.float32x4.load(transformation.m, 12);
  30013. 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));
  30014. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  30015. SIMD.float32x4.storeXYZ(result._data, 0, r);
  30016. };
  30017. return SIMDVector3;
  30018. })();
  30019. BABYLON.SIMDVector3 = SIMDVector3;
  30020. var SIMDMatrix = (function () {
  30021. function SIMDMatrix() {
  30022. }
  30023. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  30024. if (offset === void 0) { offset = 0; }
  30025. var tm = this.m;
  30026. var om = other.m;
  30027. var om0 = SIMD.float32x4.load(om, 0);
  30028. var om1 = SIMD.float32x4.load(om, 4);
  30029. var om2 = SIMD.float32x4.load(om, 8);
  30030. var om3 = SIMD.float32x4.load(om, 12);
  30031. var tm0 = SIMD.float32x4.load(tm, 0);
  30032. 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)))));
  30033. var tm1 = SIMD.float32x4.load(tm, 4);
  30034. 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)))));
  30035. var tm2 = SIMD.float32x4.load(tm, 8);
  30036. 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)))));
  30037. var tm3 = SIMD.float32x4.load(tm, 12);
  30038. 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)))));
  30039. };
  30040. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  30041. var src = this.m;
  30042. var dest = other.m;
  30043. var row0, row1, row2, row3;
  30044. var tmp1;
  30045. var minor0, minor1, minor2, minor3;
  30046. var det;
  30047. // Load the 4 rows
  30048. var src0 = SIMD.float32x4.load(src, 0);
  30049. var src1 = SIMD.float32x4.load(src, 4);
  30050. var src2 = SIMD.float32x4.load(src, 8);
  30051. var src3 = SIMD.float32x4.load(src, 12);
  30052. // Transpose the source matrix. Sort of. Not a true transpose operation
  30053. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  30054. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  30055. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  30056. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  30057. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  30058. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  30059. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  30060. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  30061. // This is a true transposition, but it will lead to an incorrect result
  30062. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  30063. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  30064. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  30065. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  30066. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  30067. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  30068. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  30069. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  30070. // ----
  30071. tmp1 = SIMD.float32x4.mul(row2, row3);
  30072. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  30073. minor0 = SIMD.float32x4.mul(row1, tmp1);
  30074. minor1 = SIMD.float32x4.mul(row0, tmp1);
  30075. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  30076. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  30077. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  30078. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  30079. // ----
  30080. tmp1 = SIMD.float32x4.mul(row1, row2);
  30081. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  30082. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  30083. minor3 = SIMD.float32x4.mul(row0, tmp1);
  30084. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  30085. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  30086. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  30087. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  30088. // ----
  30089. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  30090. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  30091. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  30092. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  30093. minor2 = SIMD.float32x4.mul(row0, tmp1);
  30094. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  30095. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  30096. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  30097. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  30098. // ----
  30099. tmp1 = SIMD.float32x4.mul(row0, row1);
  30100. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  30101. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  30102. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  30103. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  30104. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  30105. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  30106. // ----
  30107. tmp1 = SIMD.float32x4.mul(row0, row3);
  30108. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  30109. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  30110. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  30111. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  30112. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  30113. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  30114. // ----
  30115. tmp1 = SIMD.float32x4.mul(row0, row2);
  30116. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  30117. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  30118. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  30119. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  30120. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  30121. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  30122. // Compute determinant
  30123. det = SIMD.float32x4.mul(row0, minor0);
  30124. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  30125. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  30126. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  30127. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  30128. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  30129. // These shuffles aren't necessary if the faulty transposition is done
  30130. // up at the top of this function.
  30131. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  30132. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  30133. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  30134. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  30135. // Compute final values by multiplying with 1/det
  30136. minor0 = SIMD.float32x4.mul(det, minor0);
  30137. minor1 = SIMD.float32x4.mul(det, minor1);
  30138. minor2 = SIMD.float32x4.mul(det, minor2);
  30139. minor3 = SIMD.float32x4.mul(det, minor3);
  30140. SIMD.float32x4.store(dest, 0, minor0);
  30141. SIMD.float32x4.store(dest, 4, minor1);
  30142. SIMD.float32x4.store(dest, 8, minor2);
  30143. SIMD.float32x4.store(dest, 12, minor3);
  30144. return this;
  30145. };
  30146. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  30147. var out = result.m;
  30148. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  30149. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  30150. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  30151. // cc.kmVec3Subtract(f, pCenter, pEye);
  30152. var f = SIMD.float32x4.sub(center, eye);
  30153. // cc.kmVec3Normalize(f, f);
  30154. var tmp = SIMD.float32x4.mul(f, f);
  30155. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  30156. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  30157. // cc.kmVec3Assign(up, pUp);
  30158. // cc.kmVec3Normalize(up, up);
  30159. tmp = SIMD.float32x4.mul(up, up);
  30160. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  30161. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  30162. // cc.kmVec3Cross(s, f, up);
  30163. 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)));
  30164. // cc.kmVec3Normalize(s, s);
  30165. tmp = SIMD.float32x4.mul(s, s);
  30166. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  30167. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  30168. // cc.kmVec3Cross(u, s, f);
  30169. 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)));
  30170. // cc.kmVec3Normalize(s, s);
  30171. tmp = SIMD.float32x4.mul(s, s);
  30172. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  30173. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  30174. var zero = SIMD.float32x4.splat(0.0);
  30175. s = SIMD.float32x4.neg(s);
  30176. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  30177. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  30178. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  30179. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  30180. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  30181. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  30182. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  30183. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  30184. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  30185. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  30186. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  30187. var b3 = SIMD.float32x4.neg(eye);
  30188. b3 = SIMD.float32x4.withW(b3, 1.0);
  30189. 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)))));
  30190. 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)))));
  30191. 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)))));
  30192. 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)))));
  30193. };
  30194. return SIMDMatrix;
  30195. })();
  30196. BABYLON.SIMDMatrix = SIMDMatrix;
  30197. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  30198. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  30199. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  30200. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  30201. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  30202. var SIMDHelper = (function () {
  30203. function SIMDHelper() {
  30204. }
  30205. Object.defineProperty(SIMDHelper, "IsEnabled", {
  30206. get: function () {
  30207. return SIMDHelper._isEnabled;
  30208. },
  30209. enumerable: true,
  30210. configurable: true
  30211. });
  30212. SIMDHelper.DisableSIMD = function () {
  30213. // Replace functions
  30214. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  30215. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  30216. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  30217. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  30218. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  30219. SIMDHelper._isEnabled = false;
  30220. };
  30221. SIMDHelper.EnableSIMD = function () {
  30222. if (window.SIMD === undefined) {
  30223. return;
  30224. }
  30225. // Replace functions
  30226. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  30227. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  30228. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  30229. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  30230. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  30231. Object.defineProperty(BABYLON.Vector3.prototype, "x", {
  30232. get: function () { return this._data[0]; },
  30233. set: function (value) {
  30234. if (!this._data) {
  30235. this._data = new Float32Array(3);
  30236. }
  30237. this._data[0] = value;
  30238. }
  30239. });
  30240. Object.defineProperty(BABYLON.Vector3.prototype, "y", {
  30241. get: function () { return this._data[1]; },
  30242. set: function (value) {
  30243. this._data[1] = value;
  30244. }
  30245. });
  30246. Object.defineProperty(BABYLON.Vector3.prototype, "z", {
  30247. get: function () { return this._data[2]; },
  30248. set: function (value) {
  30249. this._data[2] = value;
  30250. }
  30251. });
  30252. SIMDHelper._isEnabled = true;
  30253. };
  30254. SIMDHelper._isEnabled = false;
  30255. return SIMDHelper;
  30256. })();
  30257. BABYLON.SIMDHelper = SIMDHelper;
  30258. })(BABYLON || (BABYLON = {}));
  30259. var BABYLON;
  30260. (function (BABYLON) {
  30261. var ShaderMaterial = (function (_super) {
  30262. __extends(ShaderMaterial, _super);
  30263. function ShaderMaterial(name, scene, shaderPath, options) {
  30264. _super.call(this, name, scene);
  30265. this._textures = {};
  30266. this._floats = {};
  30267. this._floatsArrays = {};
  30268. this._colors3 = {};
  30269. this._colors4 = {};
  30270. this._vectors2 = {};
  30271. this._vectors3 = {};
  30272. this._vectors4 = {};
  30273. this._matrices = {};
  30274. this._matrices3x3 = {};
  30275. this._matrices2x2 = {};
  30276. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  30277. this._shaderPath = shaderPath;
  30278. options.needAlphaBlending = options.needAlphaBlending || false;
  30279. options.needAlphaTesting = options.needAlphaTesting || false;
  30280. options.attributes = options.attributes || ["position", "normal", "uv"];
  30281. options.uniforms = options.uniforms || ["worldViewProjection"];
  30282. options.samplers = options.samplers || [];
  30283. options.defines = options.defines || [];
  30284. this._options = options;
  30285. }
  30286. ShaderMaterial.prototype.needAlphaBlending = function () {
  30287. return this._options.needAlphaBlending;
  30288. };
  30289. ShaderMaterial.prototype.needAlphaTesting = function () {
  30290. return this._options.needAlphaTesting;
  30291. };
  30292. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  30293. if (this._options.uniforms.indexOf(uniformName) === -1) {
  30294. this._options.uniforms.push(uniformName);
  30295. }
  30296. };
  30297. ShaderMaterial.prototype.setTexture = function (name, texture) {
  30298. if (this._options.samplers.indexOf(name) === -1) {
  30299. this._options.samplers.push(name);
  30300. }
  30301. this._textures[name] = texture;
  30302. return this;
  30303. };
  30304. ShaderMaterial.prototype.setFloat = function (name, value) {
  30305. this._checkUniform(name);
  30306. this._floats[name] = value;
  30307. return this;
  30308. };
  30309. ShaderMaterial.prototype.setFloats = function (name, value) {
  30310. this._checkUniform(name);
  30311. this._floatsArrays[name] = value;
  30312. return this;
  30313. };
  30314. ShaderMaterial.prototype.setColor3 = function (name, value) {
  30315. this._checkUniform(name);
  30316. this._colors3[name] = value;
  30317. return this;
  30318. };
  30319. ShaderMaterial.prototype.setColor4 = function (name, value) {
  30320. this._checkUniform(name);
  30321. this._colors4[name] = value;
  30322. return this;
  30323. };
  30324. ShaderMaterial.prototype.setVector2 = function (name, value) {
  30325. this._checkUniform(name);
  30326. this._vectors2[name] = value;
  30327. return this;
  30328. };
  30329. ShaderMaterial.prototype.setVector3 = function (name, value) {
  30330. this._checkUniform(name);
  30331. this._vectors3[name] = value;
  30332. return this;
  30333. };
  30334. ShaderMaterial.prototype.setVector4 = function (name, value) {
  30335. this._checkUniform(name);
  30336. this._vectors4[name] = value;
  30337. return this;
  30338. };
  30339. ShaderMaterial.prototype.setMatrix = function (name, value) {
  30340. this._checkUniform(name);
  30341. this._matrices[name] = value;
  30342. return this;
  30343. };
  30344. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  30345. this._checkUniform(name);
  30346. this._matrices3x3[name] = value;
  30347. return this;
  30348. };
  30349. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  30350. this._checkUniform(name);
  30351. this._matrices2x2[name] = value;
  30352. return this;
  30353. };
  30354. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  30355. var scene = this.getScene();
  30356. var engine = scene.getEngine();
  30357. if (!this.checkReadyOnEveryCall) {
  30358. if (this._renderId === scene.getRenderId()) {
  30359. return true;
  30360. }
  30361. }
  30362. // Instances
  30363. var defines = [];
  30364. var fallbacks = new BABYLON.EffectFallbacks();
  30365. if (useInstances) {
  30366. defines.push("#define INSTANCES");
  30367. }
  30368. for (var index = 0; index < this._options.defines.length; index++) {
  30369. defines.push(this._options.defines[index]);
  30370. }
  30371. // Bones
  30372. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  30373. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  30374. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  30375. fallbacks.addCPUSkinningFallback(0, mesh);
  30376. }
  30377. // Alpha test
  30378. if (engine.getAlphaTesting()) {
  30379. defines.push("#define ALPHATEST");
  30380. }
  30381. var previousEffect = this._effect;
  30382. var join = defines.join("\n");
  30383. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  30384. if (!this._effect.isReady()) {
  30385. return false;
  30386. }
  30387. if (previousEffect !== this._effect) {
  30388. scene.resetCachedMaterial();
  30389. }
  30390. this._renderId = scene.getRenderId();
  30391. return true;
  30392. };
  30393. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  30394. var scene = this.getScene();
  30395. if (this._options.uniforms.indexOf("world") !== -1) {
  30396. this._effect.setMatrix("world", world);
  30397. }
  30398. if (this._options.uniforms.indexOf("worldView") !== -1) {
  30399. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  30400. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  30401. }
  30402. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  30403. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  30404. }
  30405. };
  30406. ShaderMaterial.prototype.bind = function (world, mesh) {
  30407. // Std values
  30408. this.bindOnlyWorldMatrix(world);
  30409. if (this.getScene().getCachedMaterial() !== this) {
  30410. if (this._options.uniforms.indexOf("view") !== -1) {
  30411. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  30412. }
  30413. if (this._options.uniforms.indexOf("projection") !== -1) {
  30414. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  30415. }
  30416. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  30417. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  30418. }
  30419. // Bones
  30420. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  30421. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  30422. }
  30423. // Texture
  30424. for (var name in this._textures) {
  30425. this._effect.setTexture(name, this._textures[name]);
  30426. }
  30427. // Float
  30428. for (name in this._floats) {
  30429. this._effect.setFloat(name, this._floats[name]);
  30430. }
  30431. // Float s
  30432. for (name in this._floatsArrays) {
  30433. this._effect.setArray(name, this._floatsArrays[name]);
  30434. }
  30435. // Color3
  30436. for (name in this._colors3) {
  30437. this._effect.setColor3(name, this._colors3[name]);
  30438. }
  30439. // Color4
  30440. for (name in this._colors4) {
  30441. var color = this._colors4[name];
  30442. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  30443. }
  30444. // Vector2
  30445. for (name in this._vectors2) {
  30446. this._effect.setVector2(name, this._vectors2[name]);
  30447. }
  30448. // Vector3
  30449. for (name in this._vectors3) {
  30450. this._effect.setVector3(name, this._vectors3[name]);
  30451. }
  30452. // Vector4
  30453. for (name in this._vectors4) {
  30454. this._effect.setVector4(name, this._vectors4[name]);
  30455. }
  30456. // Matrix
  30457. for (name in this._matrices) {
  30458. this._effect.setMatrix(name, this._matrices[name]);
  30459. }
  30460. // Matrix 3x3
  30461. for (name in this._matrices3x3) {
  30462. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  30463. }
  30464. // Matrix 2x2
  30465. for (name in this._matrices2x2) {
  30466. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  30467. }
  30468. }
  30469. _super.prototype.bind.call(this, world, mesh);
  30470. };
  30471. ShaderMaterial.prototype.clone = function (name) {
  30472. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  30473. return newShaderMaterial;
  30474. };
  30475. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  30476. for (var name in this._textures) {
  30477. this._textures[name].dispose();
  30478. }
  30479. this._textures = {};
  30480. _super.prototype.dispose.call(this, forceDisposeEffect);
  30481. };
  30482. ShaderMaterial.prototype.serialize = function () {
  30483. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30484. serializationObject.customType = "BABYLON.ShaderMaterial";
  30485. serializationObject.options = this._options;
  30486. serializationObject.shaderPath = this._shaderPath;
  30487. // Texture
  30488. serializationObject.textures = {};
  30489. for (var name in this._textures) {
  30490. serializationObject.textures[name] = this._textures[name].serialize();
  30491. }
  30492. // Float
  30493. serializationObject.floats = {};
  30494. for (name in this._floats) {
  30495. serializationObject.floats[name] = this._floats[name];
  30496. }
  30497. // Float s
  30498. serializationObject.floatArrays = {};
  30499. for (name in this._floatsArrays) {
  30500. serializationObject.floatArrays[name] = this._floatsArrays[name];
  30501. }
  30502. // Color3
  30503. serializationObject.colors3 = {};
  30504. for (name in this._colors3) {
  30505. serializationObject.colors3[name] = this._colors3[name].asArray();
  30506. }
  30507. // Color4
  30508. serializationObject.colors4 = {};
  30509. for (name in this._colors4) {
  30510. serializationObject.colors4[name] = this._colors4[name].asArray();
  30511. }
  30512. // Vector2
  30513. serializationObject.vectors2 = {};
  30514. for (name in this._vectors2) {
  30515. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  30516. }
  30517. // Vector3
  30518. serializationObject.vectors3 = {};
  30519. for (name in this._vectors3) {
  30520. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  30521. }
  30522. // Vector4
  30523. serializationObject.vectors4 = {};
  30524. for (name in this._vectors4) {
  30525. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  30526. }
  30527. // Matrix
  30528. serializationObject.matrices = {};
  30529. for (name in this._matrices) {
  30530. serializationObject.matrices[name] = this._matrices[name].asArray();
  30531. }
  30532. // Matrix 3x3
  30533. serializationObject.matrices3x3 = {};
  30534. for (name in this._matrices3x3) {
  30535. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  30536. }
  30537. // Matrix 2x2
  30538. serializationObject.matrices2x2 = {};
  30539. for (name in this._matrices2x2) {
  30540. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  30541. }
  30542. return serializationObject;
  30543. };
  30544. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  30545. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  30546. // Texture
  30547. for (var name in source.textures) {
  30548. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  30549. }
  30550. // Float
  30551. for (name in source.floats) {
  30552. material.setFloat(name, source.floats[name]);
  30553. }
  30554. // Float s
  30555. for (name in source.floatsArrays) {
  30556. material.setFloats(name, source.floatsArrays[name]);
  30557. }
  30558. // Color3
  30559. for (name in source.colors3) {
  30560. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  30561. }
  30562. // Color4
  30563. for (name in source.colors4) {
  30564. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  30565. }
  30566. // Vector2
  30567. for (name in source.vectors2) {
  30568. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  30569. }
  30570. // Vector3
  30571. for (name in source.vectors3) {
  30572. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  30573. }
  30574. // Vector4
  30575. for (name in source.vectors4) {
  30576. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  30577. }
  30578. // Matrix
  30579. for (name in source.matrices) {
  30580. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  30581. }
  30582. // Matrix 3x3
  30583. for (name in source.matrices3x3) {
  30584. material.setMatrix3x3(name, source.matrices3x3[name]);
  30585. }
  30586. // Matrix 2x2
  30587. for (name in source.matrices2x2) {
  30588. material.setMatrix2x2(name, source.matrices2x2[name]);
  30589. }
  30590. return material;
  30591. };
  30592. return ShaderMaterial;
  30593. })(BABYLON.Material);
  30594. BABYLON.ShaderMaterial = ShaderMaterial;
  30595. })(BABYLON || (BABYLON = {}));
  30596. var BABYLON;
  30597. (function (BABYLON) {
  30598. var Internals;
  30599. (function (Internals) {
  30600. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  30601. // All values and structures referenced from:
  30602. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  30603. var DDS_MAGIC = 0x20534444;
  30604. 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;
  30605. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  30606. 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;
  30607. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  30608. function FourCCToInt32(value) {
  30609. return value.charCodeAt(0) +
  30610. (value.charCodeAt(1) << 8) +
  30611. (value.charCodeAt(2) << 16) +
  30612. (value.charCodeAt(3) << 24);
  30613. }
  30614. function Int32ToFourCC(value) {
  30615. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  30616. }
  30617. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  30618. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  30619. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  30620. var headerLengthInt = 31; // The header length in 32 bit ints
  30621. // Offsets into the header array
  30622. var off_magic = 0;
  30623. var off_size = 1;
  30624. var off_flags = 2;
  30625. var off_height = 3;
  30626. var off_width = 4;
  30627. var off_mipmapCount = 7;
  30628. var off_pfFlags = 20;
  30629. var off_pfFourCC = 21;
  30630. var off_RGBbpp = 22;
  30631. var off_RMask = 23;
  30632. var off_GMask = 24;
  30633. var off_BMask = 25;
  30634. var off_AMask = 26;
  30635. var off_caps1 = 27;
  30636. var off_caps2 = 28;
  30637. ;
  30638. var DDSTools = (function () {
  30639. function DDSTools() {
  30640. }
  30641. DDSTools.GetDDSInfo = function (arrayBuffer) {
  30642. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  30643. var mipmapCount = 1;
  30644. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  30645. mipmapCount = Math.max(1, header[off_mipmapCount]);
  30646. }
  30647. return {
  30648. width: header[off_width],
  30649. height: header[off_height],
  30650. mipmapCount: mipmapCount,
  30651. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  30652. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  30653. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  30654. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  30655. };
  30656. };
  30657. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  30658. var byteArray = new Uint8Array(dataLength);
  30659. var srcData = new Uint8Array(arrayBuffer);
  30660. var index = 0;
  30661. for (var y = height - 1; y >= 0; y--) {
  30662. for (var x = 0; x < width; x++) {
  30663. var srcPos = dataOffset + (x + y * width) * 4;
  30664. byteArray[index + 2] = srcData[srcPos];
  30665. byteArray[index + 1] = srcData[srcPos + 1];
  30666. byteArray[index] = srcData[srcPos + 2];
  30667. byteArray[index + 3] = srcData[srcPos + 3];
  30668. index += 4;
  30669. }
  30670. }
  30671. return byteArray;
  30672. };
  30673. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  30674. var byteArray = new Uint8Array(dataLength);
  30675. var srcData = new Uint8Array(arrayBuffer);
  30676. var index = 0;
  30677. for (var y = height - 1; y >= 0; y--) {
  30678. for (var x = 0; x < width; x++) {
  30679. var srcPos = dataOffset + (x + y * width) * 3;
  30680. byteArray[index + 2] = srcData[srcPos];
  30681. byteArray[index + 1] = srcData[srcPos + 1];
  30682. byteArray[index] = srcData[srcPos + 2];
  30683. index += 3;
  30684. }
  30685. }
  30686. return byteArray;
  30687. };
  30688. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  30689. var byteArray = new Uint8Array(dataLength);
  30690. var srcData = new Uint8Array(arrayBuffer);
  30691. var index = 0;
  30692. for (var y = height - 1; y >= 0; y--) {
  30693. for (var x = 0; x < width; x++) {
  30694. var srcPos = dataOffset + (x + y * width);
  30695. byteArray[index] = srcData[srcPos];
  30696. index++;
  30697. }
  30698. }
  30699. return byteArray;
  30700. };
  30701. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  30702. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  30703. if (header[off_magic] != DDS_MAGIC) {
  30704. BABYLON.Tools.Error("Invalid magic number in DDS header");
  30705. return;
  30706. }
  30707. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  30708. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  30709. return;
  30710. }
  30711. if (info.isFourCC) {
  30712. fourCC = header[off_pfFourCC];
  30713. switch (fourCC) {
  30714. case FOURCC_DXT1:
  30715. blockBytes = 8;
  30716. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  30717. break;
  30718. case FOURCC_DXT3:
  30719. blockBytes = 16;
  30720. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  30721. break;
  30722. case FOURCC_DXT5:
  30723. blockBytes = 16;
  30724. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  30725. break;
  30726. default:
  30727. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  30728. return;
  30729. }
  30730. }
  30731. mipmapCount = 1;
  30732. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  30733. mipmapCount = Math.max(1, header[off_mipmapCount]);
  30734. }
  30735. var bpp = header[off_RGBbpp];
  30736. for (var face = 0; face < faces; face++) {
  30737. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  30738. width = header[off_width];
  30739. height = header[off_height];
  30740. dataOffset = header[off_size] + 4;
  30741. for (i = 0; i < mipmapCount; ++i) {
  30742. if (info.isRGB) {
  30743. if (bpp === 24) {
  30744. dataLength = width * height * 3;
  30745. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  30746. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  30747. }
  30748. else {
  30749. dataLength = width * height * 4;
  30750. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  30751. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  30752. }
  30753. }
  30754. else if (info.isLuminance) {
  30755. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  30756. var unpaddedRowSize = width;
  30757. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  30758. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  30759. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  30760. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  30761. }
  30762. else {
  30763. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  30764. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  30765. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  30766. }
  30767. dataOffset += dataLength;
  30768. width *= 0.5;
  30769. height *= 0.5;
  30770. width = Math.max(1.0, width);
  30771. height = Math.max(1.0, height);
  30772. }
  30773. }
  30774. };
  30775. return DDSTools;
  30776. })();
  30777. Internals.DDSTools = DDSTools;
  30778. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  30779. })(BABYLON || (BABYLON = {}));
  30780. var BABYLON;
  30781. (function (BABYLON) {
  30782. var CannonJSPlugin = (function () {
  30783. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  30784. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  30785. if (iterations === void 0) { iterations = 10; }
  30786. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  30787. this.name = "CannonJSPlugin";
  30788. this._physicsMaterials = [];
  30789. this._fixedTimeStep = 1 / 60;
  30790. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  30791. this._currentCollisionGroup = 2;
  30792. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  30793. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  30794. this._tmpPosition = BABYLON.Vector3.Zero();
  30795. this._tmpQuaternion = new BABYLON.Quaternion();
  30796. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  30797. this._tmpDeltaRotation = new BABYLON.Quaternion();
  30798. this._tmpUnityRotation = new BABYLON.Quaternion();
  30799. if (!this.isSupported()) {
  30800. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  30801. return;
  30802. }
  30803. this.world = new CANNON.World();
  30804. this.world.broadphase = new CANNON.NaiveBroadphase();
  30805. this.world.solver.iterations = iterations;
  30806. }
  30807. CannonJSPlugin.prototype.setGravity = function (gravity) {
  30808. this.world.gravity.copy(gravity);
  30809. };
  30810. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  30811. this._fixedTimeStep = timeStep;
  30812. };
  30813. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  30814. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  30815. };
  30816. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  30817. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  30818. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  30819. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  30820. };
  30821. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  30822. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  30823. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  30824. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  30825. };
  30826. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  30827. //parent-child relationship. Does this impostor has a parent impostor?
  30828. if (impostor.parent) {
  30829. if (impostor.physicsBody) {
  30830. this.removePhysicsBody(impostor);
  30831. //TODO is that needed?
  30832. impostor.forceUpdate();
  30833. }
  30834. return;
  30835. }
  30836. //should a new body be created for this impostor?
  30837. if (impostor.isBodyInitRequired()) {
  30838. if (!impostor.mesh.rotationQuaternion) {
  30839. impostor.mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(impostor.mesh.rotation.y, impostor.mesh.rotation.x, impostor.mesh.rotation.z);
  30840. }
  30841. var shape = this._createShape(impostor);
  30842. //unregister events, if body is being changed
  30843. var oldBody = impostor.physicsBody;
  30844. if (oldBody) {
  30845. this.removePhysicsBody(impostor);
  30846. }
  30847. //create the body and material
  30848. var material = this._addMaterial("mat-" + impostor.mesh.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  30849. var bodyCreationObject = {
  30850. mass: impostor.getParam("mass"),
  30851. material: material
  30852. };
  30853. // A simple extend, in case native options were used.
  30854. var nativeOptions = impostor.getParam("nativeOptions");
  30855. for (var key in nativeOptions) {
  30856. if (nativeOptions.hasOwnProperty(key)) {
  30857. bodyCreationObject[key] = nativeOptions[key];
  30858. }
  30859. }
  30860. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  30861. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  30862. this.world.addEventListener("preStep", impostor.beforeStep);
  30863. this.world.addEventListener("postStep", impostor.afterStep);
  30864. impostor.physicsBody.addShape(shape);
  30865. this.world.add(impostor.physicsBody);
  30866. //try to keep the body moving in the right direction by taking old properties.
  30867. //Should be tested!
  30868. if (oldBody) {
  30869. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  30870. impostor.physicsBody[param].copy(oldBody[param]);
  30871. });
  30872. }
  30873. this._processChildMeshes(impostor);
  30874. }
  30875. //now update the body's transformation
  30876. this._updatePhysicsBodyTransformation(impostor);
  30877. };
  30878. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  30879. var _this = this;
  30880. var meshChildren = mainImpostor.mesh.getChildMeshes();
  30881. if (meshChildren.length) {
  30882. var processMesh = function (localPosition, mesh) {
  30883. var childImpostor = mesh.getPhysicsImpostor();
  30884. if (childImpostor) {
  30885. var parent = childImpostor.parent;
  30886. if (parent !== mainImpostor) {
  30887. var localPosition = mesh.position;
  30888. if (childImpostor.physicsBody) {
  30889. _this.removePhysicsBody(childImpostor);
  30890. childImpostor.physicsBody = null;
  30891. }
  30892. childImpostor.parent = mainImpostor;
  30893. childImpostor.resetUpdateFlags();
  30894. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  30895. //Add the mass of the children.
  30896. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  30897. }
  30898. }
  30899. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  30900. };
  30901. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  30902. }
  30903. };
  30904. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  30905. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  30906. this.world.removeEventListener("preStep", impostor.beforeStep);
  30907. this.world.removeEventListener("postStep", impostor.afterStep);
  30908. this.world.remove(impostor.physicsBody);
  30909. };
  30910. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  30911. var mainBody = impostorJoint.mainImpostor.physicsBody;
  30912. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  30913. if (!mainBody || !connectedBody) {
  30914. return;
  30915. }
  30916. var constraint;
  30917. var jointData = impostorJoint.joint.jointData;
  30918. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  30919. var constraintData = {
  30920. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  30921. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  30922. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  30923. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  30924. maxForce: jointData.nativeParams.maxForce,
  30925. collideConnected: !!jointData.collision
  30926. };
  30927. //Not needed, Cannon has a collideConnected flag
  30928. /*if (!jointData.collision) {
  30929. //add 1st body to a collision group of its own, if it is not in 1
  30930. if (mainBody.collisionFilterGroup === 1) {
  30931. mainBody.collisionFilterGroup = this._currentCollisionGroup;
  30932. this._currentCollisionGroup <<= 1;
  30933. }
  30934. if (connectedBody.collisionFilterGroup === 1) {
  30935. connectedBody.collisionFilterGroup = this._currentCollisionGroup;
  30936. this._currentCollisionGroup <<= 1;
  30937. }
  30938. //add their mask to the collisionFilterMask of each other:
  30939. connectedBody.collisionFilterMask = connectedBody.collisionFilterMask | ~mainBody.collisionFilterGroup;
  30940. mainBody.collisionFilterMask = mainBody.collisionFilterMask | ~connectedBody.collisionFilterGroup;
  30941. }*/
  30942. switch (impostorJoint.joint.type) {
  30943. case BABYLON.PhysicsJoint.HingeJoint:
  30944. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  30945. break;
  30946. case BABYLON.PhysicsJoint.DistanceJoint:
  30947. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  30948. break;
  30949. case BABYLON.PhysicsJoint.SpringJoint:
  30950. var springData = jointData;
  30951. constraint = new CANNON.Spring(mainBody, connectedBody, {
  30952. restLength: springData.length,
  30953. stiffness: springData.stiffness,
  30954. damping: springData.damping,
  30955. localAnchorA: constraintData.pivotA,
  30956. localAnchorB: constraintData.pivotB
  30957. });
  30958. break;
  30959. default:
  30960. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  30961. break;
  30962. }
  30963. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  30964. constraint.collideConnected = !!jointData.collision;
  30965. impostorJoint.joint.physicsJoint = constraint;
  30966. //don't add spring as constraint, as it is not one.
  30967. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  30968. this.world.addConstraint(constraint);
  30969. }
  30970. else {
  30971. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  30972. constraint.applyForce();
  30973. });
  30974. }
  30975. };
  30976. CannonJSPlugin.prototype.removeJoint = function (joint) {
  30977. //TODO
  30978. };
  30979. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  30980. var index;
  30981. var mat;
  30982. for (index = 0; index < this._physicsMaterials.length; index++) {
  30983. mat = this._physicsMaterials[index];
  30984. if (mat.friction === friction && mat.restitution === restitution) {
  30985. return mat;
  30986. }
  30987. }
  30988. var currentMat = new CANNON.Material("mat");
  30989. currentMat.friction = friction;
  30990. currentMat.restitution = restitution;
  30991. this._physicsMaterials.push(currentMat);
  30992. return currentMat;
  30993. };
  30994. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  30995. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  30996. };
  30997. CannonJSPlugin.prototype._createShape = function (impostor) {
  30998. var mesh = impostor.mesh;
  30999. //get the correct bounding box
  31000. var oldQuaternion = mesh.rotationQuaternion;
  31001. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  31002. mesh.computeWorldMatrix(true);
  31003. var returnValue;
  31004. switch (impostor.type) {
  31005. case BABYLON.PhysicsEngine.SphereImpostor:
  31006. var bbox = mesh.getBoundingInfo().boundingBox;
  31007. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  31008. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  31009. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  31010. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  31011. break;
  31012. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  31013. case BABYLON.PhysicsEngine.CylinderImpostor:
  31014. BABYLON.Tools.Warn("CylinderImposter not yet implemented, using BoxImposter instead");
  31015. case BABYLON.PhysicsEngine.BoxImpostor:
  31016. bbox = mesh.getBoundingInfo().boundingBox;
  31017. var min = bbox.minimumWorld;
  31018. var max = bbox.maximumWorld;
  31019. var box = max.subtract(min).scale(0.5);
  31020. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  31021. break;
  31022. case BABYLON.PhysicsEngine.PlaneImpostor:
  31023. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  31024. returnValue = new CANNON.Plane();
  31025. break;
  31026. case BABYLON.PhysicsEngine.MeshImpostor:
  31027. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31028. var rawFaces = mesh.getIndices();
  31029. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  31030. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  31031. break;
  31032. case BABYLON.PhysicsEngine.HeightmapImpostor:
  31033. returnValue = this._createHeightmap(mesh);
  31034. break;
  31035. }
  31036. mesh.rotationQuaternion = oldQuaternion;
  31037. return returnValue;
  31038. };
  31039. CannonJSPlugin.prototype._createHeightmap = function (mesh, pointDepth) {
  31040. var pos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31041. var matrix = [];
  31042. //For now pointDepth will not be used and will be automatically calculated.
  31043. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  31044. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  31045. var dim = Math.min(mesh.getBoundingInfo().boundingBox.extendSize.x, mesh.getBoundingInfo().boundingBox.extendSize.z);
  31046. var elementSize = dim * 2 / arraySize;
  31047. var minY = mesh.getBoundingInfo().boundingBox.extendSize.y;
  31048. for (var i = 0; i < pos.length; i = i + 3) {
  31049. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  31050. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  31051. var y = pos[i + 1] + minY;
  31052. if (!matrix[x]) {
  31053. matrix[x] = [];
  31054. }
  31055. if (!matrix[x][z]) {
  31056. matrix[x][z] = y;
  31057. }
  31058. matrix[x][z] = Math.max(y, matrix[x][z]);
  31059. }
  31060. for (var x = 0; x <= arraySize; ++x) {
  31061. if (!matrix[x]) {
  31062. var loc = 1;
  31063. while (!matrix[(x + loc) % arraySize]) {
  31064. loc++;
  31065. }
  31066. matrix[x] = matrix[(x + loc) % arraySize].slice();
  31067. }
  31068. for (var z = 0; z <= arraySize; ++z) {
  31069. if (!matrix[x][z]) {
  31070. var loc = 1;
  31071. var newValue;
  31072. while (newValue === undefined) {
  31073. newValue = matrix[x][(z + loc++) % arraySize];
  31074. }
  31075. matrix[x][z] = newValue;
  31076. }
  31077. }
  31078. }
  31079. var shape = new CANNON.Heightfield(matrix, {
  31080. elementSize: elementSize
  31081. });
  31082. //For future reference, needed for body transformation
  31083. shape.minY = minY;
  31084. return shape;
  31085. };
  31086. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  31087. var mesh = impostor.mesh;
  31088. //make sure it is updated...
  31089. impostor.mesh.computeWorldMatrix(true);
  31090. // The delta between the mesh position and the mesh bounding box center
  31091. var bbox = mesh.getBoundingInfo().boundingBox;
  31092. this._tmpDeltaPosition.copyFrom(mesh.position.subtract(bbox.center));
  31093. var quaternion = mesh.rotationQuaternion;
  31094. this._tmpPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center);
  31095. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  31096. if (impostor.type === BABYLON.PhysicsEngine.PlaneImpostor || impostor.type === BABYLON.PhysicsEngine.HeightmapImpostor) {
  31097. //-90 DEG in X, precalculated
  31098. quaternion = quaternion.multiply(this._minus90X);
  31099. //Invert! (Precalculated, 90 deg in X)
  31100. //No need to clone. this will never change.
  31101. impostor.setDeltaRotation(this._plus90X);
  31102. }
  31103. //If it is a heightfield, if should be centered.
  31104. if (impostor.type === BABYLON.PhysicsEngine.HeightmapImpostor) {
  31105. //calculate the correct body position:
  31106. var rotationQuaternion = mesh.rotationQuaternion;
  31107. mesh.rotationQuaternion = this._tmpUnityRotation;
  31108. mesh.computeWorldMatrix(true);
  31109. //get original center with no rotation
  31110. var center = mesh.getBoundingInfo().boundingBox.center.clone();
  31111. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  31112. //rotation is back
  31113. mesh.rotationQuaternion = rotationQuaternion;
  31114. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  31115. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  31116. mesh.setPivotMatrix(p);
  31117. mesh.computeWorldMatrix(true);
  31118. //calculate the translation
  31119. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  31120. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  31121. //add it inverted to the delta
  31122. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center.subtract(center));
  31123. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  31124. mesh.setPivotMatrix(oldPivot);
  31125. mesh.computeWorldMatrix(true);
  31126. }
  31127. else if (impostor.type === BABYLON.PhysicsEngine.MeshImpostor) {
  31128. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  31129. this._tmpPosition.copyFrom(mesh.position);
  31130. }
  31131. impostor.setDeltaPosition(this._tmpDeltaPosition);
  31132. //Now update the impostor object
  31133. impostor.physicsBody.position.copy(this._tmpPosition);
  31134. impostor.physicsBody.quaternion.copy(quaternion);
  31135. };
  31136. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  31137. impostor.mesh.position.copyFrom(impostor.physicsBody.position);
  31138. impostor.mesh.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  31139. };
  31140. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  31141. impostor.physicsBody.position.copy(newPosition);
  31142. impostor.physicsBody.quaternion.copy(newRotation);
  31143. };
  31144. CannonJSPlugin.prototype.isSupported = function () {
  31145. return window.CANNON !== undefined;
  31146. };
  31147. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  31148. impostor.physicsBody.velocity.copy(velocity);
  31149. };
  31150. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  31151. impostor.physicsBody.angularVelocity.copy(velocity);
  31152. };
  31153. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  31154. impostor.physicsBody.mass = mass;
  31155. impostor.physicsBody.updateMassProperties();
  31156. };
  31157. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  31158. impostor.physicsBody.sleep();
  31159. };
  31160. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  31161. impostor.physicsBody.wakeUp();
  31162. };
  31163. CannonJSPlugin.prototype.dispose = function () {
  31164. //nothing to do, actually.
  31165. };
  31166. return CannonJSPlugin;
  31167. })();
  31168. BABYLON.CannonJSPlugin = CannonJSPlugin;
  31169. })(BABYLON || (BABYLON = {}));
  31170. var BABYLON;
  31171. (function (BABYLON) {
  31172. var OimoJSPlugin = (function () {
  31173. function OimoJSPlugin(iterations) {
  31174. this.name = "OimoJSPlugin";
  31175. this._tmpImpostorsArray = [];
  31176. this._tmpPositionVector = BABYLON.Vector3.Zero();
  31177. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  31178. this.world.clear();
  31179. //making sure no stats are calculated
  31180. this.world.isNoStat = true;
  31181. }
  31182. OimoJSPlugin.prototype.setGravity = function (gravity) {
  31183. this.world.gravity.copy(gravity);
  31184. };
  31185. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  31186. this.world.timeStep = timeStep;
  31187. };
  31188. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  31189. var _this = this;
  31190. impostors.forEach(function (impostor) {
  31191. impostor.beforeStep();
  31192. });
  31193. this.world.step();
  31194. impostors.forEach(function (impostor) {
  31195. impostor.afterStep();
  31196. //update the ordered impostors array
  31197. _this._tmpImpostorsArray[impostor.mesh.uniqueId] = impostor;
  31198. });
  31199. //check for collisions
  31200. var contact = this.world.contacts;
  31201. while (contact !== null) {
  31202. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  31203. contact = contact.next;
  31204. continue;
  31205. }
  31206. //is this body colliding with any other? get the impostor
  31207. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  31208. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  31209. if (!mainImpostor || !collidingImpostor) {
  31210. contact = contact.next;
  31211. continue;
  31212. }
  31213. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  31214. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  31215. contact = contact.next;
  31216. }
  31217. };
  31218. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  31219. var mass = impostor.physicsBody.massInfo.mass;
  31220. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  31221. };
  31222. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  31223. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  31224. this.applyImpulse(impostor, force, contactPoint);
  31225. };
  31226. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  31227. var _this = this;
  31228. //parent-child relationship. Does this impostor has a parent impostor?
  31229. if (impostor.parent) {
  31230. if (impostor.physicsBody) {
  31231. this.removePhysicsBody(impostor);
  31232. //TODO is that needed?
  31233. impostor.forceUpdate();
  31234. }
  31235. return;
  31236. }
  31237. impostor.mesh.computeWorldMatrix(true);
  31238. if (impostor.isBodyInitRequired()) {
  31239. if (!impostor.mesh.rotationQuaternion) {
  31240. impostor.mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(impostor.mesh.rotation.y, impostor.mesh.rotation.x, impostor.mesh.rotation.z);
  31241. }
  31242. var bodyConfig = {
  31243. name: impostor.mesh.uniqueId,
  31244. //Oimo must have mass, also for static objects.
  31245. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  31246. size: [],
  31247. type: [],
  31248. pos: [],
  31249. rot: [],
  31250. move: impostor.getParam("mass") !== 0,
  31251. //Supporting older versions of Oimo
  31252. world: this.world
  31253. };
  31254. var impostors = [impostor];
  31255. function addToArray(parent) {
  31256. parent.getChildMeshes().forEach(function (m) {
  31257. if (m.physicsImpostor) {
  31258. impostors.push(m.physicsImpostor);
  31259. m.physicsImpostor._init();
  31260. }
  31261. });
  31262. }
  31263. addToArray(impostor.mesh);
  31264. function checkWithEpsilon(value) {
  31265. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  31266. }
  31267. impostors.forEach(function (i) {
  31268. //get the correct bounding box
  31269. var oldQuaternion = i.mesh.rotationQuaternion;
  31270. var rot = new OIMO.Euler().setFromQuaternion({ x: impostor.mesh.rotationQuaternion.x, y: impostor.mesh.rotationQuaternion.y, z: impostor.mesh.rotationQuaternion.z, s: impostor.mesh.rotationQuaternion.w });
  31271. i.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  31272. i.mesh.computeWorldMatrix(true);
  31273. var bbox = i.mesh.getBoundingInfo().boundingBox;
  31274. if (i === impostor) {
  31275. impostor.mesh.position.subtractToRef(impostor.mesh.getBoundingInfo().boundingBox.center, _this._tmpPositionVector);
  31276. //Can also use Array.prototype.push.apply
  31277. bodyConfig.pos.push(bbox.center.x);
  31278. bodyConfig.pos.push(bbox.center.y);
  31279. bodyConfig.pos.push(bbox.center.z);
  31280. //tmp solution
  31281. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  31282. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  31283. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  31284. }
  31285. else {
  31286. bodyConfig.pos.push(i.mesh.position.x);
  31287. bodyConfig.pos.push(i.mesh.position.y);
  31288. bodyConfig.pos.push(i.mesh.position.z);
  31289. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  31290. bodyConfig.rot.push(0);
  31291. bodyConfig.rot.push(0);
  31292. bodyConfig.rot.push(0);
  31293. }
  31294. // register mesh
  31295. switch (i.type) {
  31296. case BABYLON.PhysicsEngine.SphereImpostor:
  31297. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  31298. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  31299. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  31300. var size = Math.max(checkWithEpsilon(radiusX), checkWithEpsilon(radiusY), checkWithEpsilon(radiusZ)) / 2;
  31301. bodyConfig.type.push('sphere');
  31302. //due to the way oimo works with compounds, add 3 times
  31303. bodyConfig.size.push(size);
  31304. bodyConfig.size.push(size);
  31305. bodyConfig.size.push(size);
  31306. break;
  31307. case BABYLON.PhysicsEngine.PlaneImpostor:
  31308. //TODO Oimo now supports cylinder!
  31309. case BABYLON.PhysicsEngine.CylinderImpostor:
  31310. case BABYLON.PhysicsEngine.BoxImpostor:
  31311. default:
  31312. var min = bbox.minimumWorld;
  31313. var max = bbox.maximumWorld;
  31314. var box = max.subtract(min);
  31315. var sizeX = checkWithEpsilon(box.x);
  31316. var sizeY = checkWithEpsilon(box.y);
  31317. var sizeZ = checkWithEpsilon(box.z);
  31318. bodyConfig.type.push('box');
  31319. bodyConfig.size.push(sizeX);
  31320. bodyConfig.size.push(sizeY);
  31321. bodyConfig.size.push(sizeZ);
  31322. break;
  31323. }
  31324. //actually not needed, but hey...
  31325. i.mesh.rotationQuaternion = oldQuaternion;
  31326. });
  31327. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  31328. }
  31329. else {
  31330. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  31331. }
  31332. impostor.setDeltaPosition(this._tmpPositionVector);
  31333. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  31334. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  31335. };
  31336. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  31337. //impostor.physicsBody.dispose();
  31338. //Same as : (older oimo versions)
  31339. this.world.removeRigidBody(impostor.physicsBody);
  31340. };
  31341. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  31342. var mainBody = impostorJoint.mainImpostor.physicsBody;
  31343. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  31344. if (!mainBody || !connectedBody) {
  31345. return;
  31346. }
  31347. var jointData = impostorJoint.joint.jointData;
  31348. var options = jointData.nativeParams || {};
  31349. var type;
  31350. var nativeJointData = {
  31351. body1: mainBody,
  31352. body2: connectedBody,
  31353. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  31354. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  31355. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  31356. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  31357. min: options.min,
  31358. max: options.max,
  31359. collision: options.collision || jointData.collision,
  31360. spring: options.spring,
  31361. //supporting older version of Oimo
  31362. world: this.world
  31363. };
  31364. switch (impostorJoint.joint.type) {
  31365. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  31366. type = "jointBall";
  31367. break;
  31368. case BABYLON.PhysicsJoint.SpringJoint:
  31369. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  31370. var springData = jointData;
  31371. nativeJointData.min = springData.length || nativeJointData.min;
  31372. //Max should also be set, just make sure it is at least min
  31373. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  31374. case BABYLON.PhysicsJoint.DistanceJoint:
  31375. type = "jointDistance";
  31376. nativeJointData.max = jointData.maxDistance;
  31377. break;
  31378. case BABYLON.PhysicsJoint.PrismaticJoint:
  31379. type = "jointPrisme";
  31380. break;
  31381. case BABYLON.PhysicsJoint.SliderJoint:
  31382. type = "jointSlide";
  31383. break;
  31384. case BABYLON.PhysicsJoint.WheelJoint:
  31385. type = "jointWheel";
  31386. break;
  31387. case BABYLON.PhysicsJoint.HingeJoint:
  31388. default:
  31389. type = "jointHinge";
  31390. break;
  31391. }
  31392. nativeJointData.type = type;
  31393. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  31394. };
  31395. OimoJSPlugin.prototype.removeJoint = function (joint) {
  31396. joint.joint.physicsJoint.dispose();
  31397. };
  31398. OimoJSPlugin.prototype.isSupported = function () {
  31399. return OIMO !== undefined;
  31400. };
  31401. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  31402. if (!impostor.physicsBody.sleeping) {
  31403. //TODO check that
  31404. if (impostor.physicsBody.shapes.next) {
  31405. var parentShape = this._getLastShape(impostor.physicsBody);
  31406. impostor.mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  31407. impostor.mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  31408. impostor.mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  31409. }
  31410. else {
  31411. impostor.mesh.position.copyFrom(impostor.physicsBody.getPosition());
  31412. }
  31413. impostor.mesh.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  31414. }
  31415. };
  31416. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  31417. var body = impostor.physicsBody;
  31418. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  31419. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  31420. body.syncShapes();
  31421. body.awake();
  31422. };
  31423. OimoJSPlugin.prototype._getLastShape = function (body) {
  31424. var lastShape = body.shapes;
  31425. while (lastShape.next) {
  31426. lastShape = lastShape.next;
  31427. }
  31428. return lastShape;
  31429. };
  31430. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  31431. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  31432. };
  31433. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  31434. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  31435. };
  31436. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  31437. var staticBody = mass === 0;
  31438. //this will actually set the body's density and not its mass.
  31439. //But this is how oimo treats the mass variable.
  31440. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  31441. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  31442. };
  31443. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  31444. impostor.physicsBody.sleep();
  31445. };
  31446. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  31447. impostor.physicsBody.awake();
  31448. };
  31449. OimoJSPlugin.prototype.dispose = function () {
  31450. this.world.clear();
  31451. };
  31452. return OimoJSPlugin;
  31453. })();
  31454. BABYLON.OimoJSPlugin = OimoJSPlugin;
  31455. })(BABYLON || (BABYLON = {}));
  31456. var BABYLON;
  31457. (function (BABYLON) {
  31458. var DisplayPassPostProcess = (function (_super) {
  31459. __extends(DisplayPassPostProcess, _super);
  31460. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  31461. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  31462. }
  31463. return DisplayPassPostProcess;
  31464. })(BABYLON.PostProcess);
  31465. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  31466. })(BABYLON || (BABYLON = {}));
  31467. var BABYLON;
  31468. (function (BABYLON) {
  31469. var SimplificationSettings = (function () {
  31470. function SimplificationSettings(quality, distance, optimizeMesh) {
  31471. this.quality = quality;
  31472. this.distance = distance;
  31473. this.optimizeMesh = optimizeMesh;
  31474. }
  31475. return SimplificationSettings;
  31476. })();
  31477. BABYLON.SimplificationSettings = SimplificationSettings;
  31478. var SimplificationQueue = (function () {
  31479. function SimplificationQueue() {
  31480. this.running = false;
  31481. this._simplificationArray = [];
  31482. }
  31483. SimplificationQueue.prototype.addTask = function (task) {
  31484. this._simplificationArray.push(task);
  31485. };
  31486. SimplificationQueue.prototype.executeNext = function () {
  31487. var task = this._simplificationArray.pop();
  31488. if (task) {
  31489. this.running = true;
  31490. this.runSimplification(task);
  31491. }
  31492. else {
  31493. this.running = false;
  31494. }
  31495. };
  31496. SimplificationQueue.prototype.runSimplification = function (task) {
  31497. var _this = this;
  31498. if (task.parallelProcessing) {
  31499. //parallel simplifier
  31500. task.settings.forEach(function (setting) {
  31501. var simplifier = _this.getSimplifier(task);
  31502. simplifier.simplify(setting, function (newMesh) {
  31503. task.mesh.addLODLevel(setting.distance, newMesh);
  31504. newMesh.isVisible = true;
  31505. //check if it is the last
  31506. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  31507. //all done, run the success callback.
  31508. task.successCallback();
  31509. }
  31510. _this.executeNext();
  31511. });
  31512. });
  31513. }
  31514. else {
  31515. //single simplifier.
  31516. var simplifier = this.getSimplifier(task);
  31517. var runDecimation = function (setting, callback) {
  31518. simplifier.simplify(setting, function (newMesh) {
  31519. task.mesh.addLODLevel(setting.distance, newMesh);
  31520. newMesh.isVisible = true;
  31521. //run the next quality level
  31522. callback();
  31523. });
  31524. };
  31525. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  31526. runDecimation(task.settings[loop.index], function () {
  31527. loop.executeNext();
  31528. });
  31529. }, function () {
  31530. //execution ended, run the success callback.
  31531. if (task.successCallback) {
  31532. task.successCallback();
  31533. }
  31534. _this.executeNext();
  31535. });
  31536. }
  31537. };
  31538. SimplificationQueue.prototype.getSimplifier = function (task) {
  31539. switch (task.simplificationType) {
  31540. case SimplificationType.QUADRATIC:
  31541. default:
  31542. return new QuadraticErrorSimplification(task.mesh);
  31543. }
  31544. };
  31545. return SimplificationQueue;
  31546. })();
  31547. BABYLON.SimplificationQueue = SimplificationQueue;
  31548. /**
  31549. * The implemented types of simplification.
  31550. * At the moment only Quadratic Error Decimation is implemented.
  31551. */
  31552. (function (SimplificationType) {
  31553. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  31554. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  31555. var SimplificationType = BABYLON.SimplificationType;
  31556. var DecimationTriangle = (function () {
  31557. function DecimationTriangle(vertices) {
  31558. this.vertices = vertices;
  31559. this.error = new Array(4);
  31560. this.deleted = false;
  31561. this.isDirty = false;
  31562. this.deletePending = false;
  31563. this.borderFactor = 0;
  31564. }
  31565. return DecimationTriangle;
  31566. })();
  31567. BABYLON.DecimationTriangle = DecimationTriangle;
  31568. var DecimationVertex = (function () {
  31569. function DecimationVertex(position, id) {
  31570. this.position = position;
  31571. this.id = id;
  31572. this.isBorder = true;
  31573. this.q = new QuadraticMatrix();
  31574. this.triangleCount = 0;
  31575. this.triangleStart = 0;
  31576. this.originalOffsets = [];
  31577. }
  31578. DecimationVertex.prototype.updatePosition = function (newPosition) {
  31579. this.position.copyFrom(newPosition);
  31580. };
  31581. return DecimationVertex;
  31582. })();
  31583. BABYLON.DecimationVertex = DecimationVertex;
  31584. var QuadraticMatrix = (function () {
  31585. function QuadraticMatrix(data) {
  31586. this.data = new Array(10);
  31587. for (var i = 0; i < 10; ++i) {
  31588. if (data && data[i]) {
  31589. this.data[i] = data[i];
  31590. }
  31591. else {
  31592. this.data[i] = 0;
  31593. }
  31594. }
  31595. }
  31596. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  31597. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  31598. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  31599. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  31600. return det;
  31601. };
  31602. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  31603. for (var i = 0; i < 10; ++i) {
  31604. this.data[i] += matrix.data[i];
  31605. }
  31606. };
  31607. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  31608. for (var i = 0; i < 10; ++i) {
  31609. this.data[i] += data[i];
  31610. }
  31611. };
  31612. QuadraticMatrix.prototype.add = function (matrix) {
  31613. var m = new QuadraticMatrix();
  31614. for (var i = 0; i < 10; ++i) {
  31615. m.data[i] = this.data[i] + matrix.data[i];
  31616. }
  31617. return m;
  31618. };
  31619. QuadraticMatrix.FromData = function (a, b, c, d) {
  31620. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  31621. };
  31622. //returning an array to avoid garbage collection
  31623. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  31624. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  31625. };
  31626. return QuadraticMatrix;
  31627. })();
  31628. BABYLON.QuadraticMatrix = QuadraticMatrix;
  31629. var Reference = (function () {
  31630. function Reference(vertexId, triangleId) {
  31631. this.vertexId = vertexId;
  31632. this.triangleId = triangleId;
  31633. }
  31634. return Reference;
  31635. })();
  31636. BABYLON.Reference = Reference;
  31637. /**
  31638. * An implementation of the Quadratic Error simplification algorithm.
  31639. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  31640. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  31641. * @author RaananW
  31642. */
  31643. var QuadraticErrorSimplification = (function () {
  31644. function QuadraticErrorSimplification(_mesh) {
  31645. this._mesh = _mesh;
  31646. this.initialized = false;
  31647. this.syncIterations = 5000;
  31648. this.aggressiveness = 7;
  31649. this.decimationIterations = 100;
  31650. this.boundingBoxEpsilon = BABYLON.Epsilon;
  31651. }
  31652. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  31653. var _this = this;
  31654. this.initDecimatedMesh();
  31655. //iterating through the submeshes array, one after the other.
  31656. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  31657. _this.initWithMesh(loop.index, function () {
  31658. _this.runDecimation(settings, loop.index, function () {
  31659. loop.executeNext();
  31660. });
  31661. }, settings.optimizeMesh);
  31662. }, function () {
  31663. setTimeout(function () {
  31664. successCallback(_this._reconstructedMesh);
  31665. }, 0);
  31666. });
  31667. };
  31668. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  31669. var _this = this;
  31670. var gCount = 0;
  31671. triangle.vertices.forEach(function (vertex) {
  31672. var count = 0;
  31673. var vPos = vertex.position;
  31674. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  31675. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  31676. ++count;
  31677. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  31678. ++count;
  31679. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  31680. ++count;
  31681. if (count > 1) {
  31682. ++gCount;
  31683. }
  31684. ;
  31685. });
  31686. if (gCount > 1) {
  31687. console.log(triangle, gCount);
  31688. }
  31689. return gCount > 1;
  31690. };
  31691. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  31692. var _this = this;
  31693. var targetCount = ~~(this.triangles.length * settings.quality);
  31694. var deletedTriangles = 0;
  31695. var triangleCount = this.triangles.length;
  31696. var iterationFunction = function (iteration, callback) {
  31697. setTimeout(function () {
  31698. if (iteration % 5 === 0) {
  31699. _this.updateMesh(iteration === 0);
  31700. }
  31701. for (var i = 0; i < _this.triangles.length; ++i) {
  31702. _this.triangles[i].isDirty = false;
  31703. }
  31704. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  31705. var trianglesIterator = function (i) {
  31706. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  31707. var t = _this.triangles[tIdx];
  31708. if (!t)
  31709. return;
  31710. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  31711. return;
  31712. }
  31713. for (var j = 0; j < 3; ++j) {
  31714. if (t.error[j] < threshold) {
  31715. var deleted0 = [];
  31716. var deleted1 = [];
  31717. var v0 = t.vertices[j];
  31718. var v1 = t.vertices[(j + 1) % 3];
  31719. if (v0.isBorder !== v1.isBorder)
  31720. continue;
  31721. var p = BABYLON.Vector3.Zero();
  31722. var n = BABYLON.Vector3.Zero();
  31723. var uv = BABYLON.Vector2.Zero();
  31724. var color = new BABYLON.Color4(0, 0, 0, 1);
  31725. _this.calculateError(v0, v1, p, n, uv, color);
  31726. var delTr = [];
  31727. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  31728. continue;
  31729. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  31730. continue;
  31731. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  31732. continue;
  31733. var uniqueArray = [];
  31734. delTr.forEach(function (deletedT) {
  31735. if (uniqueArray.indexOf(deletedT) === -1) {
  31736. deletedT.deletePending = true;
  31737. uniqueArray.push(deletedT);
  31738. }
  31739. });
  31740. if (uniqueArray.length % 2 !== 0) {
  31741. continue;
  31742. }
  31743. v0.q = v1.q.add(v0.q);
  31744. v0.updatePosition(p);
  31745. var tStart = _this.references.length;
  31746. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  31747. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  31748. var tCount = _this.references.length - tStart;
  31749. if (tCount <= v0.triangleCount) {
  31750. if (tCount) {
  31751. for (var c = 0; c < tCount; c++) {
  31752. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  31753. }
  31754. }
  31755. }
  31756. else {
  31757. v0.triangleStart = tStart;
  31758. }
  31759. v0.triangleCount = tCount;
  31760. break;
  31761. }
  31762. }
  31763. };
  31764. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  31765. }, 0);
  31766. };
  31767. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  31768. if (triangleCount - deletedTriangles <= targetCount)
  31769. loop.breakLoop();
  31770. else {
  31771. iterationFunction(loop.index, function () {
  31772. loop.executeNext();
  31773. });
  31774. }
  31775. }, function () {
  31776. setTimeout(function () {
  31777. //reconstruct this part of the mesh
  31778. _this.reconstructMesh(submeshIndex);
  31779. successCallback();
  31780. }, 0);
  31781. });
  31782. };
  31783. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  31784. var _this = this;
  31785. this.vertices = [];
  31786. this.triangles = [];
  31787. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31788. var indices = this._mesh.getIndices();
  31789. var submesh = this._mesh.subMeshes[submeshIndex];
  31790. var findInVertices = function (positionToSearch) {
  31791. if (optimizeMesh) {
  31792. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  31793. if (_this.vertices[ii].position.equals(positionToSearch)) {
  31794. return _this.vertices[ii];
  31795. }
  31796. }
  31797. }
  31798. return null;
  31799. };
  31800. var vertexReferences = [];
  31801. var vertexInit = function (i) {
  31802. var offset = i + submesh.verticesStart;
  31803. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  31804. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  31805. vertex.originalOffsets.push(offset);
  31806. if (vertex.id === _this.vertices.length) {
  31807. _this.vertices.push(vertex);
  31808. }
  31809. vertexReferences.push(vertex.id);
  31810. };
  31811. //var totalVertices = mesh.getTotalVertices();
  31812. var totalVertices = submesh.verticesCount;
  31813. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  31814. var indicesInit = function (i) {
  31815. var offset = (submesh.indexStart / 3) + i;
  31816. var pos = (offset * 3);
  31817. var i0 = indices[pos + 0];
  31818. var i1 = indices[pos + 1];
  31819. var i2 = indices[pos + 2];
  31820. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  31821. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  31822. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  31823. var triangle = new DecimationTriangle([v0, v1, v2]);
  31824. triangle.originalOffset = pos;
  31825. _this.triangles.push(triangle);
  31826. };
  31827. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  31828. _this.init(callback);
  31829. });
  31830. });
  31831. };
  31832. QuadraticErrorSimplification.prototype.init = function (callback) {
  31833. var _this = this;
  31834. var triangleInit1 = function (i) {
  31835. var t = _this.triangles[i];
  31836. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  31837. for (var j = 0; j < 3; j++) {
  31838. 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))));
  31839. }
  31840. };
  31841. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  31842. var triangleInit2 = function (i) {
  31843. var t = _this.triangles[i];
  31844. for (var j = 0; j < 3; ++j) {
  31845. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  31846. }
  31847. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  31848. };
  31849. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  31850. _this.initialized = true;
  31851. callback();
  31852. });
  31853. });
  31854. };
  31855. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  31856. var newTriangles = [];
  31857. var i;
  31858. for (i = 0; i < this.vertices.length; ++i) {
  31859. this.vertices[i].triangleCount = 0;
  31860. }
  31861. var t;
  31862. var j;
  31863. for (i = 0; i < this.triangles.length; ++i) {
  31864. if (!this.triangles[i].deleted) {
  31865. t = this.triangles[i];
  31866. for (j = 0; j < 3; ++j) {
  31867. t.vertices[j].triangleCount = 1;
  31868. }
  31869. newTriangles.push(t);
  31870. }
  31871. }
  31872. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  31873. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  31874. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  31875. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  31876. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31877. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  31878. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  31879. var vertexCount = 0;
  31880. for (i = 0; i < this.vertices.length; ++i) {
  31881. var vertex = this.vertices[i];
  31882. vertex.id = vertexCount;
  31883. if (vertex.triangleCount) {
  31884. vertex.originalOffsets.forEach(function (originalOffset) {
  31885. newPositionData.push(vertex.position.x);
  31886. newPositionData.push(vertex.position.y);
  31887. newPositionData.push(vertex.position.z);
  31888. newNormalData.push(normalData[originalOffset * 3]);
  31889. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  31890. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  31891. if (uvs && uvs.length) {
  31892. newUVsData.push(uvs[(originalOffset * 2)]);
  31893. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  31894. }
  31895. else if (colorsData && colorsData.length) {
  31896. newColorsData.push(colorsData[(originalOffset * 4)]);
  31897. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  31898. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  31899. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  31900. }
  31901. ++vertexCount;
  31902. });
  31903. }
  31904. }
  31905. var startingIndex = this._reconstructedMesh.getTotalIndices();
  31906. var startingVertex = this._reconstructedMesh.getTotalVertices();
  31907. var submeshesArray = this._reconstructedMesh.subMeshes;
  31908. this._reconstructedMesh.subMeshes = [];
  31909. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  31910. var originalIndices = this._mesh.getIndices();
  31911. for (i = 0; i < newTriangles.length; ++i) {
  31912. t = newTriangles[i]; //now get the new referencing point for each vertex
  31913. [0, 1, 2].forEach(function (idx) {
  31914. var id = originalIndices[t.originalOffset + idx];
  31915. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  31916. if (offset < 0)
  31917. offset = 0;
  31918. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  31919. });
  31920. }
  31921. //overwriting the old vertex buffers and indices.
  31922. this._reconstructedMesh.setIndices(newIndicesArray);
  31923. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  31924. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  31925. if (newUVsData.length > 0)
  31926. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  31927. if (newColorsData.length > 0)
  31928. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  31929. //create submesh
  31930. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  31931. if (submeshIndex > 0) {
  31932. this._reconstructedMesh.subMeshes = [];
  31933. submeshesArray.forEach(function (submesh) {
  31934. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  31935. });
  31936. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  31937. }
  31938. };
  31939. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  31940. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  31941. this._reconstructedMesh.material = this._mesh.material;
  31942. this._reconstructedMesh.parent = this._mesh.parent;
  31943. this._reconstructedMesh.isVisible = false;
  31944. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  31945. };
  31946. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  31947. for (var i = 0; i < vertex1.triangleCount; ++i) {
  31948. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  31949. if (t.deleted)
  31950. continue;
  31951. var s = this.references[vertex1.triangleStart + i].vertexId;
  31952. var v1 = t.vertices[(s + 1) % 3];
  31953. var v2 = t.vertices[(s + 2) % 3];
  31954. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  31955. deletedArray[i] = true;
  31956. delTr.push(t);
  31957. continue;
  31958. }
  31959. var d1 = v1.position.subtract(point);
  31960. d1 = d1.normalize();
  31961. var d2 = v2.position.subtract(point);
  31962. d2 = d2.normalize();
  31963. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  31964. return true;
  31965. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  31966. deletedArray[i] = false;
  31967. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  31968. return true;
  31969. }
  31970. return false;
  31971. };
  31972. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  31973. var newDeleted = deletedTriangles;
  31974. for (var i = 0; i < vertex.triangleCount; ++i) {
  31975. var ref = this.references[vertex.triangleStart + i];
  31976. var t = this.triangles[ref.triangleId];
  31977. if (t.deleted)
  31978. continue;
  31979. if (deletedArray[i] && t.deletePending) {
  31980. t.deleted = true;
  31981. newDeleted++;
  31982. continue;
  31983. }
  31984. t.vertices[ref.vertexId] = origVertex;
  31985. t.isDirty = true;
  31986. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  31987. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  31988. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  31989. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  31990. this.references.push(ref);
  31991. }
  31992. return newDeleted;
  31993. };
  31994. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  31995. for (var i = 0; i < this.vertices.length; ++i) {
  31996. var vCount = [];
  31997. var vId = [];
  31998. var v = this.vertices[i];
  31999. var j;
  32000. for (j = 0; j < v.triangleCount; ++j) {
  32001. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  32002. for (var ii = 0; ii < 3; ii++) {
  32003. var ofs = 0;
  32004. var vv = triangle.vertices[ii];
  32005. while (ofs < vCount.length) {
  32006. if (vId[ofs] === vv.id)
  32007. break;
  32008. ++ofs;
  32009. }
  32010. if (ofs === vCount.length) {
  32011. vCount.push(1);
  32012. vId.push(vv.id);
  32013. }
  32014. else {
  32015. vCount[ofs]++;
  32016. }
  32017. }
  32018. }
  32019. for (j = 0; j < vCount.length; ++j) {
  32020. if (vCount[j] === 1) {
  32021. this.vertices[vId[j]].isBorder = true;
  32022. }
  32023. else {
  32024. this.vertices[vId[j]].isBorder = false;
  32025. }
  32026. }
  32027. }
  32028. };
  32029. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  32030. if (identifyBorders === void 0) { identifyBorders = false; }
  32031. var i;
  32032. if (!identifyBorders) {
  32033. var newTrianglesVector = [];
  32034. for (i = 0; i < this.triangles.length; ++i) {
  32035. if (!this.triangles[i].deleted) {
  32036. newTrianglesVector.push(this.triangles[i]);
  32037. }
  32038. }
  32039. this.triangles = newTrianglesVector;
  32040. }
  32041. for (i = 0; i < this.vertices.length; ++i) {
  32042. this.vertices[i].triangleCount = 0;
  32043. this.vertices[i].triangleStart = 0;
  32044. }
  32045. var t;
  32046. var j;
  32047. var v;
  32048. for (i = 0; i < this.triangles.length; ++i) {
  32049. t = this.triangles[i];
  32050. for (j = 0; j < 3; ++j) {
  32051. v = t.vertices[j];
  32052. v.triangleCount++;
  32053. }
  32054. }
  32055. var tStart = 0;
  32056. for (i = 0; i < this.vertices.length; ++i) {
  32057. this.vertices[i].triangleStart = tStart;
  32058. tStart += this.vertices[i].triangleCount;
  32059. this.vertices[i].triangleCount = 0;
  32060. }
  32061. var newReferences = new Array(this.triangles.length * 3);
  32062. for (i = 0; i < this.triangles.length; ++i) {
  32063. t = this.triangles[i];
  32064. for (j = 0; j < 3; ++j) {
  32065. v = t.vertices[j];
  32066. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  32067. v.triangleCount++;
  32068. }
  32069. }
  32070. this.references = newReferences;
  32071. if (identifyBorders) {
  32072. this.identifyBorder();
  32073. }
  32074. };
  32075. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  32076. var x = point.x;
  32077. var y = point.y;
  32078. var z = point.z;
  32079. 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
  32080. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  32081. };
  32082. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  32083. var q = vertex1.q.add(vertex2.q);
  32084. var border = vertex1.isBorder && vertex2.isBorder;
  32085. var error = 0;
  32086. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  32087. if (qDet !== 0 && !border) {
  32088. if (!pointResult) {
  32089. pointResult = BABYLON.Vector3.Zero();
  32090. }
  32091. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  32092. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  32093. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  32094. error = this.vertexError(q, pointResult);
  32095. }
  32096. else {
  32097. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  32098. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  32099. var error1 = this.vertexError(q, vertex1.position);
  32100. var error2 = this.vertexError(q, vertex2.position);
  32101. var error3 = this.vertexError(q, p3);
  32102. error = Math.min(error1, error2, error3);
  32103. if (error === error1) {
  32104. if (pointResult) {
  32105. pointResult.copyFrom(vertex1.position);
  32106. }
  32107. }
  32108. else if (error === error2) {
  32109. if (pointResult) {
  32110. pointResult.copyFrom(vertex2.position);
  32111. }
  32112. }
  32113. else {
  32114. if (pointResult) {
  32115. pointResult.copyFrom(p3);
  32116. }
  32117. }
  32118. }
  32119. return error;
  32120. };
  32121. return QuadraticErrorSimplification;
  32122. })();
  32123. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  32124. })(BABYLON || (BABYLON = {}));
  32125. var BABYLON;
  32126. (function (BABYLON) {
  32127. var serializedGeometries = [];
  32128. var serializeGeometry = function (geometry, serializationGeometries) {
  32129. if (serializedGeometries[geometry.id]) {
  32130. return;
  32131. }
  32132. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  32133. serializationGeometries.boxes.push(geometry.serialize());
  32134. }
  32135. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  32136. serializationGeometries.spheres.push(geometry.serialize());
  32137. }
  32138. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  32139. serializationGeometries.cylinders.push(geometry.serialize());
  32140. }
  32141. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  32142. serializationGeometries.toruses.push(geometry.serialize());
  32143. }
  32144. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  32145. serializationGeometries.grounds.push(geometry.serialize());
  32146. }
  32147. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  32148. serializationGeometries.planes.push(geometry.serialize());
  32149. }
  32150. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  32151. serializationGeometries.torusKnots.push(geometry.serialize());
  32152. }
  32153. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  32154. throw new Error("Unknown primitive type");
  32155. }
  32156. else {
  32157. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  32158. }
  32159. serializedGeometries[geometry.id] = true;
  32160. };
  32161. var serializeMesh = function (mesh, serializationScene) {
  32162. var serializationObject = {};
  32163. serializationObject.name = mesh.name;
  32164. serializationObject.id = mesh.id;
  32165. if (BABYLON.Tags.HasTags(mesh)) {
  32166. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  32167. }
  32168. serializationObject.position = mesh.position.asArray();
  32169. if (mesh.rotationQuaternion) {
  32170. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  32171. }
  32172. else if (mesh.rotation) {
  32173. serializationObject.rotation = mesh.rotation.asArray();
  32174. }
  32175. serializationObject.scaling = mesh.scaling.asArray();
  32176. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  32177. serializationObject.isEnabled = mesh.isEnabled();
  32178. serializationObject.isVisible = mesh.isVisible;
  32179. serializationObject.infiniteDistance = mesh.infiniteDistance;
  32180. serializationObject.pickable = mesh.isPickable;
  32181. serializationObject.receiveShadows = mesh.receiveShadows;
  32182. serializationObject.billboardMode = mesh.billboardMode;
  32183. serializationObject.visibility = mesh.visibility;
  32184. serializationObject.checkCollisions = mesh.checkCollisions;
  32185. // Parent
  32186. if (mesh.parent) {
  32187. serializationObject.parentId = mesh.parent.id;
  32188. }
  32189. // Geometry
  32190. var geometry = mesh._geometry;
  32191. if (geometry) {
  32192. var geometryId = geometry.id;
  32193. serializationObject.geometryId = geometryId;
  32194. if (!mesh.getScene().getGeometryByID(geometryId)) {
  32195. // 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
  32196. serializeGeometry(geometry, serializationScene.geometries);
  32197. }
  32198. // SubMeshes
  32199. serializationObject.subMeshes = [];
  32200. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  32201. var subMesh = mesh.subMeshes[subIndex];
  32202. serializationObject.subMeshes.push({
  32203. materialIndex: subMesh.materialIndex,
  32204. verticesStart: subMesh.verticesStart,
  32205. verticesCount: subMesh.verticesCount,
  32206. indexStart: subMesh.indexStart,
  32207. indexCount: subMesh.indexCount
  32208. });
  32209. }
  32210. }
  32211. // Material
  32212. if (mesh.material) {
  32213. serializationObject.materialId = mesh.material.id;
  32214. }
  32215. else {
  32216. mesh.material = null;
  32217. }
  32218. // Skeleton
  32219. if (mesh.skeleton) {
  32220. serializationObject.skeletonId = mesh.skeleton.id;
  32221. }
  32222. // Physics
  32223. if (mesh.getPhysicsImpostor().type !== BABYLON.PhysicsEngine.NoImpostor) {
  32224. serializationObject.physicsMass = mesh.getPhysicsMass();
  32225. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  32226. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  32227. switch (mesh.getPhysicsImpostor().type) {
  32228. case BABYLON.PhysicsEngine.BoxImpostor:
  32229. serializationObject.physicsImpostor = 1;
  32230. break;
  32231. case BABYLON.PhysicsEngine.SphereImpostor:
  32232. serializationObject.physicsImpostor = 2;
  32233. break;
  32234. }
  32235. }
  32236. // Instances
  32237. serializationObject.instances = [];
  32238. for (var index = 0; index < mesh.instances.length; index++) {
  32239. var instance = mesh.instances[index];
  32240. var serializationInstance = {
  32241. name: instance.name,
  32242. position: instance.position.asArray(),
  32243. scaling: instance.scaling.asArray()
  32244. };
  32245. if (instance.rotationQuaternion) {
  32246. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  32247. }
  32248. else if (instance.rotation) {
  32249. serializationInstance.rotation = instance.rotation.asArray();
  32250. }
  32251. serializationObject.instances.push(serializationInstance);
  32252. // Animations
  32253. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  32254. serializationInstance.ranges = instance.serializeAnimationRanges();
  32255. }
  32256. // Animations
  32257. BABYLON.Animation.AppendSerializedAnimations(mesh, serializationObject);
  32258. serializationObject.ranges = mesh.serializeAnimationRanges();
  32259. // Layer mask
  32260. serializationObject.layerMask = mesh.layerMask;
  32261. return serializationObject;
  32262. };
  32263. var finalizeSingleMesh = function (mesh, serializationObject) {
  32264. //only works if the mesh is already loaded
  32265. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  32266. //serialize material
  32267. if (mesh.material) {
  32268. if (mesh.material instanceof BABYLON.StandardMaterial) {
  32269. serializationObject.materials = serializationObject.materials || [];
  32270. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  32271. serializationObject.materials.push(mesh.material.serialize());
  32272. }
  32273. }
  32274. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  32275. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  32276. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  32277. serializationObject.multiMaterials.push(mesh.material.serialize());
  32278. }
  32279. }
  32280. }
  32281. //serialize geometry
  32282. var geometry = mesh._geometry;
  32283. if (geometry) {
  32284. if (!serializationObject.geometries) {
  32285. serializationObject.geometries = {};
  32286. serializationObject.geometries.boxes = [];
  32287. serializationObject.geometries.spheres = [];
  32288. serializationObject.geometries.cylinders = [];
  32289. serializationObject.geometries.toruses = [];
  32290. serializationObject.geometries.grounds = [];
  32291. serializationObject.geometries.planes = [];
  32292. serializationObject.geometries.torusKnots = [];
  32293. serializationObject.geometries.vertexData = [];
  32294. }
  32295. serializeGeometry(geometry, serializationObject.geometries);
  32296. }
  32297. // Skeletons
  32298. if (mesh.skeleton) {
  32299. serializationObject.skeletons = serializationObject.skeletons || [];
  32300. serializationObject.skeletons.push(mesh.skeleton.serialize());
  32301. }
  32302. //serialize the actual mesh
  32303. serializationObject.meshes = serializationObject.meshes || [];
  32304. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  32305. }
  32306. };
  32307. var SceneSerializer = (function () {
  32308. function SceneSerializer() {
  32309. }
  32310. SceneSerializer.ClearCache = function () {
  32311. serializedGeometries = [];
  32312. };
  32313. SceneSerializer.Serialize = function (scene) {
  32314. var serializationObject = {};
  32315. // Scene
  32316. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  32317. serializationObject.autoClear = scene.autoClear;
  32318. serializationObject.clearColor = scene.clearColor.asArray();
  32319. serializationObject.ambientColor = scene.ambientColor.asArray();
  32320. serializationObject.gravity = scene.gravity.asArray();
  32321. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  32322. serializationObject.workerCollisions = scene.workerCollisions;
  32323. // Fog
  32324. if (scene.fogMode && scene.fogMode !== 0) {
  32325. serializationObject.fogMode = scene.fogMode;
  32326. serializationObject.fogColor = scene.fogColor.asArray();
  32327. serializationObject.fogStart = scene.fogStart;
  32328. serializationObject.fogEnd = scene.fogEnd;
  32329. serializationObject.fogDensity = scene.fogDensity;
  32330. }
  32331. //Physics
  32332. if (scene.isPhysicsEnabled()) {
  32333. serializationObject.physicsEnabled = true;
  32334. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  32335. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  32336. }
  32337. // Lights
  32338. serializationObject.lights = [];
  32339. var index;
  32340. var light;
  32341. for (index = 0; index < scene.lights.length; index++) {
  32342. light = scene.lights[index];
  32343. serializationObject.lights.push(light.serialize());
  32344. }
  32345. // Cameras
  32346. serializationObject.cameras = [];
  32347. for (index = 0; index < scene.cameras.length; index++) {
  32348. var camera = scene.cameras[index];
  32349. serializationObject.cameras.push(camera.serialize());
  32350. }
  32351. if (scene.activeCamera) {
  32352. serializationObject.activeCameraID = scene.activeCamera.id;
  32353. }
  32354. // Animations
  32355. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  32356. // Materials
  32357. serializationObject.materials = [];
  32358. serializationObject.multiMaterials = [];
  32359. var material;
  32360. for (index = 0; index < scene.materials.length; index++) {
  32361. material = scene.materials[index];
  32362. serializationObject.materials.push(material.serialize());
  32363. }
  32364. // MultiMaterials
  32365. serializationObject.multiMaterials = [];
  32366. for (index = 0; index < scene.multiMaterials.length; index++) {
  32367. var multiMaterial = scene.multiMaterials[index];
  32368. serializationObject.multiMaterials.push(multiMaterial.serialize());
  32369. }
  32370. // Skeletons
  32371. serializationObject.skeletons = [];
  32372. for (index = 0; index < scene.skeletons.length; index++) {
  32373. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  32374. }
  32375. // Geometries
  32376. serializationObject.geometries = {};
  32377. serializationObject.geometries.boxes = [];
  32378. serializationObject.geometries.spheres = [];
  32379. serializationObject.geometries.cylinders = [];
  32380. serializationObject.geometries.toruses = [];
  32381. serializationObject.geometries.grounds = [];
  32382. serializationObject.geometries.planes = [];
  32383. serializationObject.geometries.torusKnots = [];
  32384. serializationObject.geometries.vertexData = [];
  32385. serializedGeometries = [];
  32386. var geometries = scene.getGeometries();
  32387. for (index = 0; index < geometries.length; index++) {
  32388. var geometry = geometries[index];
  32389. if (geometry.isReady()) {
  32390. serializeGeometry(geometry, serializationObject.geometries);
  32391. }
  32392. }
  32393. // Meshes
  32394. serializationObject.meshes = [];
  32395. for (index = 0; index < scene.meshes.length; index++) {
  32396. var abstractMesh = scene.meshes[index];
  32397. if (abstractMesh instanceof BABYLON.Mesh) {
  32398. var mesh = abstractMesh;
  32399. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  32400. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  32401. }
  32402. }
  32403. }
  32404. // Particles Systems
  32405. serializationObject.particleSystems = [];
  32406. for (index = 0; index < scene.particleSystems.length; index++) {
  32407. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  32408. }
  32409. // Lens flares
  32410. serializationObject.lensFlareSystems = [];
  32411. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  32412. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  32413. }
  32414. // Shadows
  32415. serializationObject.shadowGenerators = [];
  32416. for (index = 0; index < scene.lights.length; index++) {
  32417. light = scene.lights[index];
  32418. if (light.getShadowGenerator()) {
  32419. serializationObject.shadowGenerators.push(light.getShadowGenerator().serialize());
  32420. }
  32421. }
  32422. return serializationObject;
  32423. };
  32424. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  32425. if (withParents === void 0) { withParents = false; }
  32426. if (withChildren === void 0) { withChildren = false; }
  32427. var serializationObject = {};
  32428. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  32429. if (withParents || withChildren) {
  32430. //deliberate for loop! not for each, appended should be processed as well.
  32431. for (var i = 0; i < toSerialize.length; ++i) {
  32432. if (withChildren) {
  32433. toSerialize[i].getDescendants().forEach(function (node) {
  32434. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  32435. toSerialize.push(node);
  32436. }
  32437. });
  32438. }
  32439. //make sure the array doesn't contain the object already
  32440. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  32441. toSerialize.push(toSerialize[i].parent);
  32442. }
  32443. }
  32444. }
  32445. toSerialize.forEach(function (mesh) {
  32446. finalizeSingleMesh(mesh, serializationObject);
  32447. });
  32448. return serializationObject;
  32449. };
  32450. return SceneSerializer;
  32451. })();
  32452. BABYLON.SceneSerializer = SceneSerializer;
  32453. })(BABYLON || (BABYLON = {}));
  32454. var BABYLON;
  32455. (function (BABYLON) {
  32456. // Unique ID when we import meshes from Babylon to CSG
  32457. var currentCSGMeshId = 0;
  32458. // # class Vertex
  32459. // Represents a vertex of a polygon. Use your own vertex class instead of this
  32460. // one to provide additional features like texture coordinates and vertex
  32461. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  32462. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  32463. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  32464. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  32465. // is not used anywhere else.
  32466. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  32467. var Vertex = (function () {
  32468. function Vertex(pos, normal, uv) {
  32469. this.pos = pos;
  32470. this.normal = normal;
  32471. this.uv = uv;
  32472. }
  32473. Vertex.prototype.clone = function () {
  32474. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  32475. };
  32476. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  32477. // orientation of a polygon is flipped.
  32478. Vertex.prototype.flip = function () {
  32479. this.normal = this.normal.scale(-1);
  32480. };
  32481. // Create a new vertex between this vertex and `other` by linearly
  32482. // interpolating all properties using a parameter of `t`. Subclasses should
  32483. // override this to interpolate additional properties.
  32484. Vertex.prototype.interpolate = function (other, t) {
  32485. 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));
  32486. };
  32487. return Vertex;
  32488. })();
  32489. // # class Plane
  32490. // Represents a plane in 3D space.
  32491. var Plane = (function () {
  32492. function Plane(normal, w) {
  32493. this.normal = normal;
  32494. this.w = w;
  32495. }
  32496. Plane.FromPoints = function (a, b, c) {
  32497. var v0 = c.subtract(a);
  32498. var v1 = b.subtract(a);
  32499. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  32500. return null;
  32501. }
  32502. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  32503. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  32504. };
  32505. Plane.prototype.clone = function () {
  32506. return new Plane(this.normal.clone(), this.w);
  32507. };
  32508. Plane.prototype.flip = function () {
  32509. this.normal.scaleInPlace(-1);
  32510. this.w = -this.w;
  32511. };
  32512. // Split `polygon` by this plane if needed, then put the polygon or polygon
  32513. // fragments in the appropriate lists. Coplanar polygons go into either
  32514. // `coplanarFront` or `coplanarBack` depending on their orientation with
  32515. // respect to this plane. Polygons in front or in back of this plane go into
  32516. // either `front` or `back`.
  32517. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  32518. var COPLANAR = 0;
  32519. var FRONT = 1;
  32520. var BACK = 2;
  32521. var SPANNING = 3;
  32522. // Classify each point as well as the entire polygon into one of the above
  32523. // four classes.
  32524. var polygonType = 0;
  32525. var types = [];
  32526. var i;
  32527. var t;
  32528. for (i = 0; i < polygon.vertices.length; i++) {
  32529. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  32530. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  32531. polygonType |= type;
  32532. types.push(type);
  32533. }
  32534. // Put the polygon in the correct list, splitting it when necessary.
  32535. switch (polygonType) {
  32536. case COPLANAR:
  32537. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  32538. break;
  32539. case FRONT:
  32540. front.push(polygon);
  32541. break;
  32542. case BACK:
  32543. back.push(polygon);
  32544. break;
  32545. case SPANNING:
  32546. var f = [], b = [];
  32547. for (i = 0; i < polygon.vertices.length; i++) {
  32548. var j = (i + 1) % polygon.vertices.length;
  32549. var ti = types[i], tj = types[j];
  32550. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  32551. if (ti !== BACK)
  32552. f.push(vi);
  32553. if (ti !== FRONT)
  32554. b.push(ti !== BACK ? vi.clone() : vi);
  32555. if ((ti | tj) === SPANNING) {
  32556. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  32557. var v = vi.interpolate(vj, t);
  32558. f.push(v);
  32559. b.push(v.clone());
  32560. }
  32561. }
  32562. var poly;
  32563. if (f.length >= 3) {
  32564. poly = new Polygon(f, polygon.shared);
  32565. if (poly.plane)
  32566. front.push(poly);
  32567. }
  32568. if (b.length >= 3) {
  32569. poly = new Polygon(b, polygon.shared);
  32570. if (poly.plane)
  32571. back.push(poly);
  32572. }
  32573. break;
  32574. }
  32575. };
  32576. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  32577. // point is on the plane.
  32578. Plane.EPSILON = 1e-5;
  32579. return Plane;
  32580. })();
  32581. // # class Polygon
  32582. // Represents a convex polygon. The vertices used to initialize a polygon must
  32583. // be coplanar and form a convex loop.
  32584. //
  32585. // Each convex polygon has a `shared` property, which is shared between all
  32586. // polygons that are clones of each other or were split from the same polygon.
  32587. // This can be used to define per-polygon properties (such as surface color).
  32588. var Polygon = (function () {
  32589. function Polygon(vertices, shared) {
  32590. this.vertices = vertices;
  32591. this.shared = shared;
  32592. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  32593. }
  32594. Polygon.prototype.clone = function () {
  32595. var vertices = this.vertices.map(function (v) { return v.clone(); });
  32596. return new Polygon(vertices, this.shared);
  32597. };
  32598. Polygon.prototype.flip = function () {
  32599. this.vertices.reverse().map(function (v) { v.flip(); });
  32600. this.plane.flip();
  32601. };
  32602. return Polygon;
  32603. })();
  32604. // # class Node
  32605. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  32606. // by picking a polygon to split along. That polygon (and all other coplanar
  32607. // polygons) are added directly to that node and the other polygons are added to
  32608. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  32609. // no distinction between internal and leaf nodes.
  32610. var Node = (function () {
  32611. function Node(polygons) {
  32612. this.plane = null;
  32613. this.front = null;
  32614. this.back = null;
  32615. this.polygons = [];
  32616. if (polygons) {
  32617. this.build(polygons);
  32618. }
  32619. }
  32620. Node.prototype.clone = function () {
  32621. var node = new Node();
  32622. node.plane = this.plane && this.plane.clone();
  32623. node.front = this.front && this.front.clone();
  32624. node.back = this.back && this.back.clone();
  32625. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  32626. return node;
  32627. };
  32628. // Convert solid space to empty space and empty space to solid space.
  32629. Node.prototype.invert = function () {
  32630. for (var i = 0; i < this.polygons.length; i++) {
  32631. this.polygons[i].flip();
  32632. }
  32633. if (this.plane) {
  32634. this.plane.flip();
  32635. }
  32636. if (this.front) {
  32637. this.front.invert();
  32638. }
  32639. if (this.back) {
  32640. this.back.invert();
  32641. }
  32642. var temp = this.front;
  32643. this.front = this.back;
  32644. this.back = temp;
  32645. };
  32646. // Recursively remove all polygons in `polygons` that are inside this BSP
  32647. // tree.
  32648. Node.prototype.clipPolygons = function (polygons) {
  32649. if (!this.plane)
  32650. return polygons.slice();
  32651. var front = [], back = [];
  32652. for (var i = 0; i < polygons.length; i++) {
  32653. this.plane.splitPolygon(polygons[i], front, back, front, back);
  32654. }
  32655. if (this.front) {
  32656. front = this.front.clipPolygons(front);
  32657. }
  32658. if (this.back) {
  32659. back = this.back.clipPolygons(back);
  32660. }
  32661. else {
  32662. back = [];
  32663. }
  32664. return front.concat(back);
  32665. };
  32666. // Remove all polygons in this BSP tree that are inside the other BSP tree
  32667. // `bsp`.
  32668. Node.prototype.clipTo = function (bsp) {
  32669. this.polygons = bsp.clipPolygons(this.polygons);
  32670. if (this.front)
  32671. this.front.clipTo(bsp);
  32672. if (this.back)
  32673. this.back.clipTo(bsp);
  32674. };
  32675. // Return a list of all polygons in this BSP tree.
  32676. Node.prototype.allPolygons = function () {
  32677. var polygons = this.polygons.slice();
  32678. if (this.front)
  32679. polygons = polygons.concat(this.front.allPolygons());
  32680. if (this.back)
  32681. polygons = polygons.concat(this.back.allPolygons());
  32682. return polygons;
  32683. };
  32684. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  32685. // new polygons are filtered down to the bottom of the tree and become new
  32686. // nodes there. Each set of polygons is partitioned using the first polygon
  32687. // (no heuristic is used to pick a good split).
  32688. Node.prototype.build = function (polygons) {
  32689. if (!polygons.length)
  32690. return;
  32691. if (!this.plane)
  32692. this.plane = polygons[0].plane.clone();
  32693. var front = [], back = [];
  32694. for (var i = 0; i < polygons.length; i++) {
  32695. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  32696. }
  32697. if (front.length) {
  32698. if (!this.front)
  32699. this.front = new Node();
  32700. this.front.build(front);
  32701. }
  32702. if (back.length) {
  32703. if (!this.back)
  32704. this.back = new Node();
  32705. this.back.build(back);
  32706. }
  32707. };
  32708. return Node;
  32709. })();
  32710. var CSG = (function () {
  32711. function CSG() {
  32712. this.polygons = new Array();
  32713. }
  32714. // Convert BABYLON.Mesh to BABYLON.CSG
  32715. CSG.FromMesh = function (mesh) {
  32716. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  32717. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  32718. if (mesh instanceof BABYLON.Mesh) {
  32719. mesh.computeWorldMatrix(true);
  32720. matrix = mesh.getWorldMatrix();
  32721. meshPosition = mesh.position.clone();
  32722. meshRotation = mesh.rotation.clone();
  32723. if (mesh.rotationQuaternion) {
  32724. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  32725. }
  32726. meshScaling = mesh.scaling.clone();
  32727. }
  32728. else {
  32729. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  32730. }
  32731. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32732. var subMeshes = mesh.subMeshes;
  32733. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  32734. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  32735. vertices = [];
  32736. for (var j = 0; j < 3; j++) {
  32737. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  32738. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  32739. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  32740. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  32741. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  32742. vertex = new Vertex(position, normal, uv);
  32743. vertices.push(vertex);
  32744. }
  32745. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  32746. // To handle the case of degenerated triangle
  32747. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  32748. if (polygon.plane)
  32749. polygons.push(polygon);
  32750. }
  32751. }
  32752. var csg = CSG.FromPolygons(polygons);
  32753. csg.matrix = matrix;
  32754. csg.position = meshPosition;
  32755. csg.rotation = meshRotation;
  32756. csg.scaling = meshScaling;
  32757. csg.rotationQuaternion = meshRotationQuaternion;
  32758. currentCSGMeshId++;
  32759. return csg;
  32760. };
  32761. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  32762. CSG.FromPolygons = function (polygons) {
  32763. var csg = new CSG();
  32764. csg.polygons = polygons;
  32765. return csg;
  32766. };
  32767. CSG.prototype.clone = function () {
  32768. var csg = new CSG();
  32769. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  32770. csg.copyTransformAttributes(this);
  32771. return csg;
  32772. };
  32773. CSG.prototype.toPolygons = function () {
  32774. return this.polygons;
  32775. };
  32776. CSG.prototype.union = function (csg) {
  32777. var a = new Node(this.clone().polygons);
  32778. var b = new Node(csg.clone().polygons);
  32779. a.clipTo(b);
  32780. b.clipTo(a);
  32781. b.invert();
  32782. b.clipTo(a);
  32783. b.invert();
  32784. a.build(b.allPolygons());
  32785. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  32786. };
  32787. CSG.prototype.unionInPlace = function (csg) {
  32788. var a = new Node(this.polygons);
  32789. var b = new Node(csg.polygons);
  32790. a.clipTo(b);
  32791. b.clipTo(a);
  32792. b.invert();
  32793. b.clipTo(a);
  32794. b.invert();
  32795. a.build(b.allPolygons());
  32796. this.polygons = a.allPolygons();
  32797. };
  32798. CSG.prototype.subtract = function (csg) {
  32799. var a = new Node(this.clone().polygons);
  32800. var b = new Node(csg.clone().polygons);
  32801. a.invert();
  32802. a.clipTo(b);
  32803. b.clipTo(a);
  32804. b.invert();
  32805. b.clipTo(a);
  32806. b.invert();
  32807. a.build(b.allPolygons());
  32808. a.invert();
  32809. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  32810. };
  32811. CSG.prototype.subtractInPlace = function (csg) {
  32812. var a = new Node(this.polygons);
  32813. var b = new Node(csg.polygons);
  32814. a.invert();
  32815. a.clipTo(b);
  32816. b.clipTo(a);
  32817. b.invert();
  32818. b.clipTo(a);
  32819. b.invert();
  32820. a.build(b.allPolygons());
  32821. a.invert();
  32822. this.polygons = a.allPolygons();
  32823. };
  32824. CSG.prototype.intersect = function (csg) {
  32825. var a = new Node(this.clone().polygons);
  32826. var b = new Node(csg.clone().polygons);
  32827. a.invert();
  32828. b.clipTo(a);
  32829. b.invert();
  32830. a.clipTo(b);
  32831. b.clipTo(a);
  32832. a.build(b.allPolygons());
  32833. a.invert();
  32834. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  32835. };
  32836. CSG.prototype.intersectInPlace = function (csg) {
  32837. var a = new Node(this.polygons);
  32838. var b = new Node(csg.polygons);
  32839. a.invert();
  32840. b.clipTo(a);
  32841. b.invert();
  32842. a.clipTo(b);
  32843. b.clipTo(a);
  32844. a.build(b.allPolygons());
  32845. a.invert();
  32846. this.polygons = a.allPolygons();
  32847. };
  32848. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  32849. // not modified.
  32850. CSG.prototype.inverse = function () {
  32851. var csg = this.clone();
  32852. csg.inverseInPlace();
  32853. return csg;
  32854. };
  32855. CSG.prototype.inverseInPlace = function () {
  32856. this.polygons.map(function (p) { p.flip(); });
  32857. };
  32858. // This is used to keep meshes transformations so they can be restored
  32859. // when we build back a Babylon Mesh
  32860. // NB : All CSG operations are performed in world coordinates
  32861. CSG.prototype.copyTransformAttributes = function (csg) {
  32862. this.matrix = csg.matrix;
  32863. this.position = csg.position;
  32864. this.rotation = csg.rotation;
  32865. this.scaling = csg.scaling;
  32866. this.rotationQuaternion = csg.rotationQuaternion;
  32867. return this;
  32868. };
  32869. // Build Raw mesh from CSG
  32870. // Coordinates here are in world space
  32871. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  32872. var matrix = this.matrix.clone();
  32873. matrix.invert();
  32874. 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;
  32875. if (keepSubMeshes) {
  32876. // Sort Polygons, since subMeshes are indices range
  32877. polygons.sort(function (a, b) {
  32878. if (a.shared.meshId === b.shared.meshId) {
  32879. return a.shared.subMeshId - b.shared.subMeshId;
  32880. }
  32881. else {
  32882. return a.shared.meshId - b.shared.meshId;
  32883. }
  32884. });
  32885. }
  32886. for (var i = 0, il = polygons.length; i < il; i++) {
  32887. polygon = polygons[i];
  32888. // Building SubMeshes
  32889. if (!subMesh_dict[polygon.shared.meshId]) {
  32890. subMesh_dict[polygon.shared.meshId] = {};
  32891. }
  32892. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  32893. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  32894. indexStart: +Infinity,
  32895. indexEnd: -Infinity,
  32896. materialIndex: polygon.shared.materialIndex
  32897. };
  32898. }
  32899. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  32900. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  32901. polygonIndices[0] = 0;
  32902. polygonIndices[1] = j - 1;
  32903. polygonIndices[2] = j;
  32904. for (var k = 0; k < 3; k++) {
  32905. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  32906. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  32907. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  32908. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  32909. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  32910. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  32911. // Check if 2 points can be merged
  32912. if (!(typeof vertex_idx !== 'undefined' &&
  32913. normals[vertex_idx * 3] === localNormal.x &&
  32914. normals[vertex_idx * 3 + 1] === localNormal.y &&
  32915. normals[vertex_idx * 3 + 2] === localNormal.z &&
  32916. uvs[vertex_idx * 2] === uv.x &&
  32917. uvs[vertex_idx * 2 + 1] === uv.y)) {
  32918. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  32919. uvs.push(uv.x, uv.y);
  32920. normals.push(normal.x, normal.y, normal.z);
  32921. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  32922. }
  32923. indices.push(vertex_idx);
  32924. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  32925. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  32926. currentIndex++;
  32927. }
  32928. }
  32929. }
  32930. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  32931. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32932. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  32933. mesh.setIndices(indices);
  32934. if (keepSubMeshes) {
  32935. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  32936. var materialIndexOffset = 0, materialMaxIndex;
  32937. mesh.subMeshes = new Array();
  32938. for (var m in subMesh_dict) {
  32939. materialMaxIndex = -1;
  32940. for (var sm in subMesh_dict[m]) {
  32941. subMesh_obj = subMesh_dict[m][sm];
  32942. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  32943. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  32944. }
  32945. materialIndexOffset += ++materialMaxIndex;
  32946. }
  32947. }
  32948. return mesh;
  32949. };
  32950. // Build Mesh from CSG taking material and transforms into account
  32951. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  32952. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  32953. mesh.material = material;
  32954. mesh.position.copyFrom(this.position);
  32955. mesh.rotation.copyFrom(this.rotation);
  32956. if (this.rotationQuaternion) {
  32957. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  32958. }
  32959. mesh.scaling.copyFrom(this.scaling);
  32960. mesh.computeWorldMatrix(true);
  32961. return mesh;
  32962. };
  32963. return CSG;
  32964. })();
  32965. BABYLON.CSG = CSG;
  32966. })(BABYLON || (BABYLON = {}));
  32967. var BABYLON;
  32968. (function (BABYLON) {
  32969. var VRDistortionCorrectionPostProcess = (function (_super) {
  32970. __extends(VRDistortionCorrectionPostProcess, _super);
  32971. //ANY
  32972. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  32973. var _this = this;
  32974. _super.call(this, name, "vrDistortionCorrection", [
  32975. 'LensCenter',
  32976. 'Scale',
  32977. 'ScaleIn',
  32978. 'HmdWarpParam'
  32979. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  32980. this._isRightEye = isRightEye;
  32981. this._distortionFactors = vrMetrics.distortionK;
  32982. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  32983. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  32984. this.onSizeChanged = function () {
  32985. _this.aspectRatio = _this.width * .5 / _this.height;
  32986. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  32987. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  32988. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  32989. };
  32990. this.onApply = function (effect) {
  32991. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  32992. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  32993. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  32994. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  32995. };
  32996. }
  32997. return VRDistortionCorrectionPostProcess;
  32998. })(BABYLON.PostProcess);
  32999. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  33000. })(BABYLON || (BABYLON = {}));
  33001. // Mainly based on these 2 articles :
  33002. // 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
  33003. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  33004. var BABYLON;
  33005. (function (BABYLON) {
  33006. (function (JoystickAxis) {
  33007. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  33008. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  33009. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  33010. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  33011. var JoystickAxis = BABYLON.JoystickAxis;
  33012. var VirtualJoystick = (function () {
  33013. function VirtualJoystick(leftJoystick) {
  33014. var _this = this;
  33015. if (leftJoystick) {
  33016. this._leftJoystick = true;
  33017. }
  33018. else {
  33019. this._leftJoystick = false;
  33020. }
  33021. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  33022. VirtualJoystick._globalJoystickIndex++;
  33023. // By default left & right arrow keys are moving the X
  33024. // and up & down keys are moving the Y
  33025. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  33026. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  33027. this.reverseLeftRight = false;
  33028. this.reverseUpDown = false;
  33029. // collections of pointers
  33030. this._touches = new BABYLON.SmartCollection();
  33031. this.deltaPosition = BABYLON.Vector3.Zero();
  33032. this._joystickSensibility = 25;
  33033. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  33034. this._rotationSpeed = 25;
  33035. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  33036. this._rotateOnAxisRelativeToMesh = false;
  33037. this._onResize = function (evt) {
  33038. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  33039. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  33040. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  33041. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  33042. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  33043. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  33044. };
  33045. // injecting a canvas element on top of the canvas 3D game
  33046. if (!VirtualJoystick.vjCanvas) {
  33047. window.addEventListener("resize", this._onResize, false);
  33048. VirtualJoystick.vjCanvas = document.createElement("canvas");
  33049. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  33050. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  33051. VirtualJoystick.vjCanvas.width = window.innerWidth;
  33052. VirtualJoystick.vjCanvas.height = window.innerHeight;
  33053. VirtualJoystick.vjCanvas.style.width = "100%";
  33054. VirtualJoystick.vjCanvas.style.height = "100%";
  33055. VirtualJoystick.vjCanvas.style.position = "absolute";
  33056. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  33057. VirtualJoystick.vjCanvas.style.top = "0px";
  33058. VirtualJoystick.vjCanvas.style.left = "0px";
  33059. VirtualJoystick.vjCanvas.style.zIndex = "5";
  33060. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  33061. // Support for jQuery PEP polyfill
  33062. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  33063. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  33064. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  33065. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  33066. document.body.appendChild(VirtualJoystick.vjCanvas);
  33067. }
  33068. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  33069. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  33070. this.pressed = false;
  33071. // default joystick color
  33072. this._joystickColor = "cyan";
  33073. this._joystickPointerID = -1;
  33074. // current joystick position
  33075. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  33076. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  33077. // origin joystick position
  33078. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  33079. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  33080. this._onPointerDownHandlerRef = function (evt) {
  33081. _this._onPointerDown(evt);
  33082. };
  33083. this._onPointerMoveHandlerRef = function (evt) {
  33084. _this._onPointerMove(evt);
  33085. };
  33086. this._onPointerOutHandlerRef = function (evt) {
  33087. _this._onPointerUp(evt);
  33088. };
  33089. this._onPointerUpHandlerRef = function (evt) {
  33090. _this._onPointerUp(evt);
  33091. };
  33092. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  33093. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  33094. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  33095. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  33096. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  33097. evt.preventDefault(); // Disables system menu
  33098. }, false);
  33099. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  33100. }
  33101. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  33102. this._joystickSensibility = newJoystickSensibility;
  33103. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  33104. };
  33105. VirtualJoystick.prototype._onPointerDown = function (e) {
  33106. var positionOnScreenCondition;
  33107. e.preventDefault();
  33108. if (this._leftJoystick === true) {
  33109. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  33110. }
  33111. else {
  33112. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  33113. }
  33114. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  33115. // First contact will be dedicated to the virtual joystick
  33116. this._joystickPointerID = e.pointerId;
  33117. this._joystickPointerStartPos.x = e.clientX;
  33118. this._joystickPointerStartPos.y = e.clientY;
  33119. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  33120. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  33121. this._deltaJoystickVector.x = 0;
  33122. this._deltaJoystickVector.y = 0;
  33123. this.pressed = true;
  33124. this._touches.add(e.pointerId.toString(), e);
  33125. }
  33126. else {
  33127. // You can only trigger the action buttons with a joystick declared
  33128. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  33129. this._action();
  33130. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  33131. }
  33132. }
  33133. };
  33134. VirtualJoystick.prototype._onPointerMove = function (e) {
  33135. // If the current pointer is the one associated to the joystick (first touch contact)
  33136. if (this._joystickPointerID == e.pointerId) {
  33137. this._joystickPointerPos.x = e.clientX;
  33138. this._joystickPointerPos.y = e.clientY;
  33139. this._deltaJoystickVector = this._joystickPointerPos.clone();
  33140. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  33141. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  33142. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  33143. switch (this._axisTargetedByLeftAndRight) {
  33144. case JoystickAxis.X:
  33145. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  33146. break;
  33147. case JoystickAxis.Y:
  33148. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  33149. break;
  33150. case JoystickAxis.Z:
  33151. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  33152. break;
  33153. }
  33154. var directionUpDown = this.reverseUpDown ? 1 : -1;
  33155. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  33156. switch (this._axisTargetedByUpAndDown) {
  33157. case JoystickAxis.X:
  33158. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  33159. break;
  33160. case JoystickAxis.Y:
  33161. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  33162. break;
  33163. case JoystickAxis.Z:
  33164. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  33165. break;
  33166. }
  33167. }
  33168. else {
  33169. if (this._touches.item(e.pointerId.toString())) {
  33170. this._touches.item(e.pointerId.toString()).x = e.clientX;
  33171. this._touches.item(e.pointerId.toString()).y = e.clientY;
  33172. }
  33173. }
  33174. };
  33175. VirtualJoystick.prototype._onPointerUp = function (e) {
  33176. if (this._joystickPointerID == e.pointerId) {
  33177. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  33178. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  33179. this._joystickPointerID = -1;
  33180. this.pressed = false;
  33181. }
  33182. else {
  33183. var touch = this._touches.item(e.pointerId.toString());
  33184. if (touch) {
  33185. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  33186. }
  33187. }
  33188. this._deltaJoystickVector.x = 0;
  33189. this._deltaJoystickVector.y = 0;
  33190. this._touches.remove(e.pointerId.toString());
  33191. };
  33192. /**
  33193. * Change the color of the virtual joystick
  33194. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  33195. */
  33196. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  33197. this._joystickColor = newColor;
  33198. };
  33199. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  33200. this._action = action;
  33201. };
  33202. // Define which axis you'd like to control for left & right
  33203. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  33204. switch (axis) {
  33205. case JoystickAxis.X:
  33206. case JoystickAxis.Y:
  33207. case JoystickAxis.Z:
  33208. this._axisTargetedByLeftAndRight = axis;
  33209. break;
  33210. default:
  33211. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  33212. break;
  33213. }
  33214. };
  33215. // Define which axis you'd like to control for up & down
  33216. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  33217. switch (axis) {
  33218. case JoystickAxis.X:
  33219. case JoystickAxis.Y:
  33220. case JoystickAxis.Z:
  33221. this._axisTargetedByUpAndDown = axis;
  33222. break;
  33223. default:
  33224. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  33225. break;
  33226. }
  33227. };
  33228. VirtualJoystick.prototype._clearCanvas = function () {
  33229. if (this._leftJoystick) {
  33230. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  33231. }
  33232. else {
  33233. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  33234. }
  33235. };
  33236. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  33237. var _this = this;
  33238. if (this.pressed) {
  33239. this._touches.forEach(function (touch) {
  33240. if (touch.pointerId === _this._joystickPointerID) {
  33241. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  33242. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  33243. VirtualJoystick.vjCanvasContext.beginPath();
  33244. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  33245. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  33246. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  33247. VirtualJoystick.vjCanvasContext.stroke();
  33248. VirtualJoystick.vjCanvasContext.closePath();
  33249. VirtualJoystick.vjCanvasContext.beginPath();
  33250. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  33251. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  33252. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  33253. VirtualJoystick.vjCanvasContext.stroke();
  33254. VirtualJoystick.vjCanvasContext.closePath();
  33255. VirtualJoystick.vjCanvasContext.beginPath();
  33256. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  33257. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  33258. VirtualJoystick.vjCanvasContext.stroke();
  33259. VirtualJoystick.vjCanvasContext.closePath();
  33260. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  33261. }
  33262. else {
  33263. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  33264. VirtualJoystick.vjCanvasContext.beginPath();
  33265. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  33266. VirtualJoystick.vjCanvasContext.beginPath();
  33267. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  33268. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  33269. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  33270. VirtualJoystick.vjCanvasContext.stroke();
  33271. VirtualJoystick.vjCanvasContext.closePath();
  33272. touch.prevX = touch.x;
  33273. touch.prevY = touch.y;
  33274. }
  33275. ;
  33276. });
  33277. }
  33278. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  33279. };
  33280. VirtualJoystick.prototype.releaseCanvas = function () {
  33281. if (VirtualJoystick.vjCanvas) {
  33282. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  33283. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  33284. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  33285. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  33286. window.removeEventListener("resize", this._onResize);
  33287. document.body.removeChild(VirtualJoystick.vjCanvas);
  33288. VirtualJoystick.vjCanvas = null;
  33289. }
  33290. };
  33291. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  33292. VirtualJoystick._globalJoystickIndex = 0;
  33293. return VirtualJoystick;
  33294. })();
  33295. BABYLON.VirtualJoystick = VirtualJoystick;
  33296. })(BABYLON || (BABYLON = {}));
  33297. var BABYLON;
  33298. (function (BABYLON) {
  33299. // We're mainly based on the logic defined into the FreeCamera code
  33300. var VirtualJoysticksCamera = (function (_super) {
  33301. __extends(VirtualJoysticksCamera, _super);
  33302. function VirtualJoysticksCamera(name, position, scene) {
  33303. _super.call(this, name, position, scene);
  33304. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  33305. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  33306. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  33307. this._leftjoystick.setJoystickSensibility(0.15);
  33308. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  33309. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  33310. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  33311. this._rightjoystick.reverseUpDown = true;
  33312. this._rightjoystick.setJoystickSensibility(0.05);
  33313. this._rightjoystick.setJoystickColor("yellow");
  33314. }
  33315. VirtualJoysticksCamera.prototype.getLeftJoystick = function () {
  33316. return this._leftjoystick;
  33317. };
  33318. VirtualJoysticksCamera.prototype.getRightJoystick = function () {
  33319. return this._rightjoystick;
  33320. };
  33321. VirtualJoysticksCamera.prototype._checkInputs = function () {
  33322. var speed = this._computeLocalCameraSpeed() * 50;
  33323. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  33324. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  33325. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  33326. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  33327. if (!this._leftjoystick.pressed) {
  33328. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  33329. }
  33330. if (!this._rightjoystick.pressed) {
  33331. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  33332. }
  33333. _super.prototype._checkInputs.call(this);
  33334. };
  33335. VirtualJoysticksCamera.prototype.dispose = function () {
  33336. this._leftjoystick.releaseCanvas();
  33337. _super.prototype.dispose.call(this);
  33338. };
  33339. VirtualJoysticksCamera.prototype.getTypeName = function () {
  33340. return "VirtualJoysticksCamera";
  33341. };
  33342. return VirtualJoysticksCamera;
  33343. })(BABYLON.FreeCamera);
  33344. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  33345. })(BABYLON || (BABYLON = {}));
  33346. var BABYLON;
  33347. (function (BABYLON) {
  33348. var AnaglyphPostProcess = (function (_super) {
  33349. __extends(AnaglyphPostProcess, _super);
  33350. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  33351. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  33352. }
  33353. return AnaglyphPostProcess;
  33354. })(BABYLON.PostProcess);
  33355. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  33356. })(BABYLON || (BABYLON = {}));
  33357. var BABYLON;
  33358. (function (BABYLON) {
  33359. var OutlineRenderer = (function () {
  33360. function OutlineRenderer(scene) {
  33361. this._scene = scene;
  33362. }
  33363. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  33364. var _this = this;
  33365. if (useOverlay === void 0) { useOverlay = false; }
  33366. var scene = this._scene;
  33367. var engine = this._scene.getEngine();
  33368. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  33369. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  33370. return;
  33371. }
  33372. var mesh = subMesh.getRenderingMesh();
  33373. var material = subMesh.getMaterial();
  33374. engine.enableEffect(this._effect);
  33375. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  33376. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  33377. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  33378. // Bones
  33379. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  33380. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  33381. }
  33382. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  33383. // Alpha test
  33384. if (material && material.needAlphaTesting()) {
  33385. var alphaTexture = material.getAlphaTestTexture();
  33386. this._effect.setTexture("diffuseSampler", alphaTexture);
  33387. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  33388. }
  33389. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  33390. };
  33391. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  33392. var defines = [];
  33393. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  33394. var mesh = subMesh.getMesh();
  33395. var material = subMesh.getMaterial();
  33396. // Alpha test
  33397. if (material && material.needAlphaTesting()) {
  33398. defines.push("#define ALPHATEST");
  33399. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33400. attribs.push(BABYLON.VertexBuffer.UVKind);
  33401. defines.push("#define UV1");
  33402. }
  33403. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  33404. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  33405. defines.push("#define UV2");
  33406. }
  33407. }
  33408. // Bones
  33409. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  33410. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33411. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33412. if (mesh.numBoneInfluencers > 4) {
  33413. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  33414. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  33415. }
  33416. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  33417. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  33418. }
  33419. else {
  33420. defines.push("#define NUM_BONE_INFLUENCERS 0");
  33421. }
  33422. // Instances
  33423. if (useInstances) {
  33424. defines.push("#define INSTANCES");
  33425. attribs.push("world0");
  33426. attribs.push("world1");
  33427. attribs.push("world2");
  33428. attribs.push("world3");
  33429. }
  33430. // Get correct effect
  33431. var join = defines.join("\n");
  33432. if (this._cachedDefines !== join) {
  33433. this._cachedDefines = join;
  33434. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  33435. }
  33436. return this._effect.isReady();
  33437. };
  33438. return OutlineRenderer;
  33439. })();
  33440. BABYLON.OutlineRenderer = OutlineRenderer;
  33441. })(BABYLON || (BABYLON = {}));
  33442. var BABYLON;
  33443. (function (BABYLON) {
  33444. var MeshAssetTask = (function () {
  33445. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  33446. this.name = name;
  33447. this.meshesNames = meshesNames;
  33448. this.rootUrl = rootUrl;
  33449. this.sceneFilename = sceneFilename;
  33450. this.isCompleted = false;
  33451. }
  33452. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  33453. var _this = this;
  33454. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  33455. _this.loadedMeshes = meshes;
  33456. _this.loadedParticleSystems = particleSystems;
  33457. _this.loadedSkeletons = skeletons;
  33458. _this.isCompleted = true;
  33459. if (_this.onSuccess) {
  33460. _this.onSuccess(_this);
  33461. }
  33462. onSuccess();
  33463. }, null, function () {
  33464. if (_this.onError) {
  33465. _this.onError(_this);
  33466. }
  33467. onError();
  33468. });
  33469. };
  33470. return MeshAssetTask;
  33471. })();
  33472. BABYLON.MeshAssetTask = MeshAssetTask;
  33473. var TextFileAssetTask = (function () {
  33474. function TextFileAssetTask(name, url) {
  33475. this.name = name;
  33476. this.url = url;
  33477. this.isCompleted = false;
  33478. }
  33479. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  33480. var _this = this;
  33481. BABYLON.Tools.LoadFile(this.url, function (data) {
  33482. _this.text = data;
  33483. _this.isCompleted = true;
  33484. if (_this.onSuccess) {
  33485. _this.onSuccess(_this);
  33486. }
  33487. onSuccess();
  33488. }, null, scene.database, false, function () {
  33489. if (_this.onError) {
  33490. _this.onError(_this);
  33491. }
  33492. onError();
  33493. });
  33494. };
  33495. return TextFileAssetTask;
  33496. })();
  33497. BABYLON.TextFileAssetTask = TextFileAssetTask;
  33498. var BinaryFileAssetTask = (function () {
  33499. function BinaryFileAssetTask(name, url) {
  33500. this.name = name;
  33501. this.url = url;
  33502. this.isCompleted = false;
  33503. }
  33504. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  33505. var _this = this;
  33506. BABYLON.Tools.LoadFile(this.url, function (data) {
  33507. _this.data = data;
  33508. _this.isCompleted = true;
  33509. if (_this.onSuccess) {
  33510. _this.onSuccess(_this);
  33511. }
  33512. onSuccess();
  33513. }, null, scene.database, true, function () {
  33514. if (_this.onError) {
  33515. _this.onError(_this);
  33516. }
  33517. onError();
  33518. });
  33519. };
  33520. return BinaryFileAssetTask;
  33521. })();
  33522. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  33523. var ImageAssetTask = (function () {
  33524. function ImageAssetTask(name, url) {
  33525. this.name = name;
  33526. this.url = url;
  33527. this.isCompleted = false;
  33528. }
  33529. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  33530. var _this = this;
  33531. var img = new Image();
  33532. img.onload = function () {
  33533. _this.image = img;
  33534. _this.isCompleted = true;
  33535. if (_this.onSuccess) {
  33536. _this.onSuccess(_this);
  33537. }
  33538. onSuccess();
  33539. };
  33540. img.onerror = function () {
  33541. if (_this.onError) {
  33542. _this.onError(_this);
  33543. }
  33544. onError();
  33545. };
  33546. img.src = this.url;
  33547. };
  33548. return ImageAssetTask;
  33549. })();
  33550. BABYLON.ImageAssetTask = ImageAssetTask;
  33551. var TextureAssetTask = (function () {
  33552. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  33553. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33554. this.name = name;
  33555. this.url = url;
  33556. this.noMipmap = noMipmap;
  33557. this.invertY = invertY;
  33558. this.samplingMode = samplingMode;
  33559. this.isCompleted = false;
  33560. }
  33561. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  33562. var _this = this;
  33563. var onload = function () {
  33564. _this.isCompleted = true;
  33565. if (_this.onSuccess) {
  33566. _this.onSuccess(_this);
  33567. }
  33568. onSuccess();
  33569. };
  33570. var onerror = function () {
  33571. if (_this.onError) {
  33572. _this.onError(_this);
  33573. }
  33574. onError();
  33575. };
  33576. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  33577. };
  33578. return TextureAssetTask;
  33579. })();
  33580. BABYLON.TextureAssetTask = TextureAssetTask;
  33581. var AssetsManager = (function () {
  33582. function AssetsManager(scene) {
  33583. this._tasks = new Array();
  33584. this._waitingTasksCount = 0;
  33585. this.useDefaultLoadingScreen = true;
  33586. this._scene = scene;
  33587. }
  33588. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  33589. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  33590. this._tasks.push(task);
  33591. return task;
  33592. };
  33593. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  33594. var task = new TextFileAssetTask(taskName, url);
  33595. this._tasks.push(task);
  33596. return task;
  33597. };
  33598. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  33599. var task = new BinaryFileAssetTask(taskName, url);
  33600. this._tasks.push(task);
  33601. return task;
  33602. };
  33603. AssetsManager.prototype.addImageTask = function (taskName, url) {
  33604. var task = new ImageAssetTask(taskName, url);
  33605. this._tasks.push(task);
  33606. return task;
  33607. };
  33608. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  33609. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33610. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  33611. this._tasks.push(task);
  33612. return task;
  33613. };
  33614. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  33615. this._waitingTasksCount--;
  33616. if (this._waitingTasksCount === 0) {
  33617. if (this.onFinish) {
  33618. this.onFinish(this._tasks);
  33619. }
  33620. this._scene.getEngine().hideLoadingUI();
  33621. }
  33622. };
  33623. AssetsManager.prototype._runTask = function (task) {
  33624. var _this = this;
  33625. task.run(this._scene, function () {
  33626. if (_this.onTaskSuccess) {
  33627. _this.onTaskSuccess(task);
  33628. }
  33629. _this._decreaseWaitingTasksCount();
  33630. }, function () {
  33631. if (_this.onTaskError) {
  33632. _this.onTaskError(task);
  33633. }
  33634. _this._decreaseWaitingTasksCount();
  33635. });
  33636. };
  33637. AssetsManager.prototype.reset = function () {
  33638. this._tasks = new Array();
  33639. return this;
  33640. };
  33641. AssetsManager.prototype.load = function () {
  33642. this._waitingTasksCount = this._tasks.length;
  33643. if (this._waitingTasksCount === 0) {
  33644. if (this.onFinish) {
  33645. this.onFinish(this._tasks);
  33646. }
  33647. return this;
  33648. }
  33649. if (this.useDefaultLoadingScreen) {
  33650. this._scene.getEngine().displayLoadingUI();
  33651. }
  33652. for (var index = 0; index < this._tasks.length; index++) {
  33653. var task = this._tasks[index];
  33654. this._runTask(task);
  33655. }
  33656. return this;
  33657. };
  33658. return AssetsManager;
  33659. })();
  33660. BABYLON.AssetsManager = AssetsManager;
  33661. })(BABYLON || (BABYLON = {}));
  33662. var BABYLON;
  33663. (function (BABYLON) {
  33664. var VRCameraMetrics = (function () {
  33665. function VRCameraMetrics() {
  33666. this.compensateDistortion = true;
  33667. }
  33668. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  33669. get: function () {
  33670. return this.hResolution / (2 * this.vResolution);
  33671. },
  33672. enumerable: true,
  33673. configurable: true
  33674. });
  33675. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  33676. get: function () {
  33677. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  33678. },
  33679. enumerable: true,
  33680. configurable: true
  33681. });
  33682. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  33683. get: function () {
  33684. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  33685. var h = (4 * meters) / this.hScreenSize;
  33686. return BABYLON.Matrix.Translation(h, 0, 0);
  33687. },
  33688. enumerable: true,
  33689. configurable: true
  33690. });
  33691. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  33692. get: function () {
  33693. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  33694. var h = (4 * meters) / this.hScreenSize;
  33695. return BABYLON.Matrix.Translation(-h, 0, 0);
  33696. },
  33697. enumerable: true,
  33698. configurable: true
  33699. });
  33700. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  33701. get: function () {
  33702. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  33703. },
  33704. enumerable: true,
  33705. configurable: true
  33706. });
  33707. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  33708. get: function () {
  33709. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  33710. },
  33711. enumerable: true,
  33712. configurable: true
  33713. });
  33714. VRCameraMetrics.GetDefault = function () {
  33715. var result = new VRCameraMetrics();
  33716. result.hResolution = 1280;
  33717. result.vResolution = 800;
  33718. result.hScreenSize = 0.149759993;
  33719. result.vScreenSize = 0.0935999975;
  33720. result.vScreenCenter = 0.0467999987,
  33721. result.eyeToScreenDistance = 0.0410000011;
  33722. result.lensSeparationDistance = 0.0635000020;
  33723. result.interpupillaryDistance = 0.0640000030;
  33724. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  33725. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  33726. result.postProcessScaleFactor = 1.714605507808412;
  33727. result.lensCenterOffset = 0.151976421;
  33728. return result;
  33729. };
  33730. return VRCameraMetrics;
  33731. })();
  33732. BABYLON.VRCameraMetrics = VRCameraMetrics;
  33733. })(BABYLON || (BABYLON = {}));
  33734. var BABYLON;
  33735. (function (BABYLON) {
  33736. var VRDeviceOrientationFreeCamera = (function (_super) {
  33737. __extends(VRDeviceOrientationFreeCamera, _super);
  33738. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion) {
  33739. if (compensateDistortion === void 0) { compensateDistortion = true; }
  33740. _super.call(this, name, position, scene);
  33741. this._alpha = 0;
  33742. this._beta = 0;
  33743. this._gamma = 0;
  33744. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  33745. metrics.compensateDistortion = compensateDistortion;
  33746. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  33747. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  33748. }
  33749. VRDeviceOrientationFreeCamera.prototype._onOrientationEvent = function (evt) {
  33750. this._alpha = +evt.alpha | 0;
  33751. this._beta = +evt.beta | 0;
  33752. this._gamma = +evt.gamma | 0;
  33753. if (this._gamma < 0) {
  33754. this._gamma = 90 + this._gamma;
  33755. }
  33756. else {
  33757. // Incline it in the correct angle.
  33758. this._gamma = 270 - this._gamma;
  33759. }
  33760. this.rotation.x = this._gamma / 180.0 * Math.PI;
  33761. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  33762. this.rotation.z = this._beta / 180.0 * Math.PI;
  33763. };
  33764. VRDeviceOrientationFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  33765. _super.prototype.attachControl.call(this, element, noPreventDefault);
  33766. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  33767. };
  33768. VRDeviceOrientationFreeCamera.prototype.detachControl = function (element) {
  33769. _super.prototype.detachControl.call(this, element);
  33770. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  33771. };
  33772. VRDeviceOrientationFreeCamera.prototype.getTypeName = function () {
  33773. return "VRDeviceOrientationFreeCamera";
  33774. };
  33775. return VRDeviceOrientationFreeCamera;
  33776. })(BABYLON.FreeCamera);
  33777. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  33778. })(BABYLON || (BABYLON = {}));
  33779. var BABYLON;
  33780. (function (BABYLON) {
  33781. var WebVRFreeCamera = (function (_super) {
  33782. __extends(WebVRFreeCamera, _super);
  33783. function WebVRFreeCamera(name, position, scene, compensateDistortion) {
  33784. if (compensateDistortion === void 0) { compensateDistortion = true; }
  33785. _super.call(this, name, position, scene);
  33786. this._hmdDevice = null;
  33787. this._sensorDevice = null;
  33788. this._cacheState = null;
  33789. this._cacheQuaternion = new BABYLON.Quaternion();
  33790. this._cacheRotation = BABYLON.Vector3.Zero();
  33791. this._vrEnabled = false;
  33792. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  33793. metrics.compensateDistortion = compensateDistortion;
  33794. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  33795. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  33796. }
  33797. WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
  33798. var size = devices.length;
  33799. var i = 0;
  33800. // Reset devices.
  33801. this._sensorDevice = null;
  33802. this._hmdDevice = null;
  33803. // Search for a HmdDevice.
  33804. while (i < size && this._hmdDevice === null) {
  33805. if (devices[i] instanceof HMDVRDevice) {
  33806. this._hmdDevice = devices[i];
  33807. }
  33808. i++;
  33809. }
  33810. i = 0;
  33811. while (i < size && this._sensorDevice === null) {
  33812. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  33813. this._sensorDevice = devices[i];
  33814. }
  33815. i++;
  33816. }
  33817. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  33818. };
  33819. WebVRFreeCamera.prototype._checkInputs = function () {
  33820. if (this._vrEnabled) {
  33821. this._cacheState = this._sensorDevice.getState();
  33822. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  33823. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  33824. this.rotation.x = -this._cacheRotation.x;
  33825. this.rotation.y = -this._cacheRotation.y;
  33826. this.rotation.z = this._cacheRotation.z;
  33827. }
  33828. _super.prototype._checkInputs.call(this);
  33829. };
  33830. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  33831. _super.prototype.attachControl.call(this, element, noPreventDefault);
  33832. if (navigator.getVRDevices) {
  33833. navigator.getVRDevices().then(this._getWebVRDevices);
  33834. }
  33835. else if (navigator.mozGetVRDevices) {
  33836. navigator.mozGetVRDevices(this._getWebVRDevices);
  33837. }
  33838. };
  33839. WebVRFreeCamera.prototype.detachControl = function (element) {
  33840. _super.prototype.detachControl.call(this, element);
  33841. this._vrEnabled = false;
  33842. };
  33843. WebVRFreeCamera.prototype.getTypeName = function () {
  33844. return "WebVRFreeCamera";
  33845. };
  33846. return WebVRFreeCamera;
  33847. })(BABYLON.FreeCamera);
  33848. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  33849. })(BABYLON || (BABYLON = {}));
  33850. var BABYLON;
  33851. (function (BABYLON) {
  33852. // Standard optimizations
  33853. var SceneOptimization = (function () {
  33854. function SceneOptimization(priority) {
  33855. if (priority === void 0) { priority = 0; }
  33856. this.priority = priority;
  33857. this.apply = function (scene) {
  33858. return true; // Return true if everything that can be done was applied
  33859. };
  33860. }
  33861. return SceneOptimization;
  33862. })();
  33863. BABYLON.SceneOptimization = SceneOptimization;
  33864. var TextureOptimization = (function (_super) {
  33865. __extends(TextureOptimization, _super);
  33866. function TextureOptimization(priority, maximumSize) {
  33867. var _this = this;
  33868. if (priority === void 0) { priority = 0; }
  33869. if (maximumSize === void 0) { maximumSize = 1024; }
  33870. _super.call(this, priority);
  33871. this.priority = priority;
  33872. this.maximumSize = maximumSize;
  33873. this.apply = function (scene) {
  33874. var allDone = true;
  33875. for (var index = 0; index < scene.textures.length; index++) {
  33876. var texture = scene.textures[index];
  33877. if (!texture.canRescale) {
  33878. continue;
  33879. }
  33880. var currentSize = texture.getSize();
  33881. var maxDimension = Math.max(currentSize.width, currentSize.height);
  33882. if (maxDimension > _this.maximumSize) {
  33883. texture.scale(0.5);
  33884. allDone = false;
  33885. }
  33886. }
  33887. return allDone;
  33888. };
  33889. }
  33890. return TextureOptimization;
  33891. })(SceneOptimization);
  33892. BABYLON.TextureOptimization = TextureOptimization;
  33893. var HardwareScalingOptimization = (function (_super) {
  33894. __extends(HardwareScalingOptimization, _super);
  33895. function HardwareScalingOptimization(priority, maximumScale) {
  33896. var _this = this;
  33897. if (priority === void 0) { priority = 0; }
  33898. if (maximumScale === void 0) { maximumScale = 2; }
  33899. _super.call(this, priority);
  33900. this.priority = priority;
  33901. this.maximumScale = maximumScale;
  33902. this._currentScale = 1;
  33903. this.apply = function (scene) {
  33904. _this._currentScale++;
  33905. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  33906. return _this._currentScale >= _this.maximumScale;
  33907. };
  33908. }
  33909. return HardwareScalingOptimization;
  33910. })(SceneOptimization);
  33911. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  33912. var ShadowsOptimization = (function (_super) {
  33913. __extends(ShadowsOptimization, _super);
  33914. function ShadowsOptimization() {
  33915. _super.apply(this, arguments);
  33916. this.apply = function (scene) {
  33917. scene.shadowsEnabled = false;
  33918. return true;
  33919. };
  33920. }
  33921. return ShadowsOptimization;
  33922. })(SceneOptimization);
  33923. BABYLON.ShadowsOptimization = ShadowsOptimization;
  33924. var PostProcessesOptimization = (function (_super) {
  33925. __extends(PostProcessesOptimization, _super);
  33926. function PostProcessesOptimization() {
  33927. _super.apply(this, arguments);
  33928. this.apply = function (scene) {
  33929. scene.postProcessesEnabled = false;
  33930. return true;
  33931. };
  33932. }
  33933. return PostProcessesOptimization;
  33934. })(SceneOptimization);
  33935. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  33936. var LensFlaresOptimization = (function (_super) {
  33937. __extends(LensFlaresOptimization, _super);
  33938. function LensFlaresOptimization() {
  33939. _super.apply(this, arguments);
  33940. this.apply = function (scene) {
  33941. scene.lensFlaresEnabled = false;
  33942. return true;
  33943. };
  33944. }
  33945. return LensFlaresOptimization;
  33946. })(SceneOptimization);
  33947. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  33948. var ParticlesOptimization = (function (_super) {
  33949. __extends(ParticlesOptimization, _super);
  33950. function ParticlesOptimization() {
  33951. _super.apply(this, arguments);
  33952. this.apply = function (scene) {
  33953. scene.particlesEnabled = false;
  33954. return true;
  33955. };
  33956. }
  33957. return ParticlesOptimization;
  33958. })(SceneOptimization);
  33959. BABYLON.ParticlesOptimization = ParticlesOptimization;
  33960. var RenderTargetsOptimization = (function (_super) {
  33961. __extends(RenderTargetsOptimization, _super);
  33962. function RenderTargetsOptimization() {
  33963. _super.apply(this, arguments);
  33964. this.apply = function (scene) {
  33965. scene.renderTargetsEnabled = false;
  33966. return true;
  33967. };
  33968. }
  33969. return RenderTargetsOptimization;
  33970. })(SceneOptimization);
  33971. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  33972. var MergeMeshesOptimization = (function (_super) {
  33973. __extends(MergeMeshesOptimization, _super);
  33974. function MergeMeshesOptimization() {
  33975. var _this = this;
  33976. _super.apply(this, arguments);
  33977. this._canBeMerged = function (abstractMesh) {
  33978. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  33979. return false;
  33980. }
  33981. var mesh = abstractMesh;
  33982. if (!mesh.isVisible || !mesh.isEnabled()) {
  33983. return false;
  33984. }
  33985. if (mesh.instances.length > 0) {
  33986. return false;
  33987. }
  33988. if (mesh.skeleton || mesh.hasLODLevels) {
  33989. return false;
  33990. }
  33991. if (mesh.parent) {
  33992. return false;
  33993. }
  33994. return true;
  33995. };
  33996. this.apply = function (scene, updateSelectionTree) {
  33997. var globalPool = scene.meshes.slice(0);
  33998. var globalLength = globalPool.length;
  33999. for (var index = 0; index < globalLength; index++) {
  34000. var currentPool = new Array();
  34001. var current = globalPool[index];
  34002. // Checks
  34003. if (!_this._canBeMerged(current)) {
  34004. continue;
  34005. }
  34006. currentPool.push(current);
  34007. // Find compatible meshes
  34008. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  34009. var otherMesh = globalPool[subIndex];
  34010. if (!_this._canBeMerged(otherMesh)) {
  34011. continue;
  34012. }
  34013. if (otherMesh.material !== current.material) {
  34014. continue;
  34015. }
  34016. if (otherMesh.checkCollisions !== current.checkCollisions) {
  34017. continue;
  34018. }
  34019. currentPool.push(otherMesh);
  34020. globalLength--;
  34021. globalPool.splice(subIndex, 1);
  34022. subIndex--;
  34023. }
  34024. if (currentPool.length < 2) {
  34025. continue;
  34026. }
  34027. // Merge meshes
  34028. BABYLON.Mesh.MergeMeshes(currentPool);
  34029. }
  34030. if (updateSelectionTree != undefined) {
  34031. if (updateSelectionTree) {
  34032. scene.createOrUpdateSelectionOctree();
  34033. }
  34034. }
  34035. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  34036. scene.createOrUpdateSelectionOctree();
  34037. }
  34038. return true;
  34039. };
  34040. }
  34041. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  34042. get: function () {
  34043. return MergeMeshesOptimization._UpdateSelectionTree;
  34044. },
  34045. set: function (value) {
  34046. MergeMeshesOptimization._UpdateSelectionTree = value;
  34047. },
  34048. enumerable: true,
  34049. configurable: true
  34050. });
  34051. MergeMeshesOptimization._UpdateSelectionTree = false;
  34052. return MergeMeshesOptimization;
  34053. })(SceneOptimization);
  34054. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  34055. // Options
  34056. var SceneOptimizerOptions = (function () {
  34057. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  34058. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  34059. if (trackerDuration === void 0) { trackerDuration = 2000; }
  34060. this.targetFrameRate = targetFrameRate;
  34061. this.trackerDuration = trackerDuration;
  34062. this.optimizations = new Array();
  34063. }
  34064. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  34065. var result = new SceneOptimizerOptions(targetFrameRate);
  34066. var priority = 0;
  34067. result.optimizations.push(new MergeMeshesOptimization(priority));
  34068. result.optimizations.push(new ShadowsOptimization(priority));
  34069. result.optimizations.push(new LensFlaresOptimization(priority));
  34070. // Next priority
  34071. priority++;
  34072. result.optimizations.push(new PostProcessesOptimization(priority));
  34073. result.optimizations.push(new ParticlesOptimization(priority));
  34074. // Next priority
  34075. priority++;
  34076. result.optimizations.push(new TextureOptimization(priority, 1024));
  34077. return result;
  34078. };
  34079. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  34080. var result = new SceneOptimizerOptions(targetFrameRate);
  34081. var priority = 0;
  34082. result.optimizations.push(new MergeMeshesOptimization(priority));
  34083. result.optimizations.push(new ShadowsOptimization(priority));
  34084. result.optimizations.push(new LensFlaresOptimization(priority));
  34085. // Next priority
  34086. priority++;
  34087. result.optimizations.push(new PostProcessesOptimization(priority));
  34088. result.optimizations.push(new ParticlesOptimization(priority));
  34089. // Next priority
  34090. priority++;
  34091. result.optimizations.push(new TextureOptimization(priority, 512));
  34092. // Next priority
  34093. priority++;
  34094. result.optimizations.push(new RenderTargetsOptimization(priority));
  34095. // Next priority
  34096. priority++;
  34097. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  34098. return result;
  34099. };
  34100. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  34101. var result = new SceneOptimizerOptions(targetFrameRate);
  34102. var priority = 0;
  34103. result.optimizations.push(new MergeMeshesOptimization(priority));
  34104. result.optimizations.push(new ShadowsOptimization(priority));
  34105. result.optimizations.push(new LensFlaresOptimization(priority));
  34106. // Next priority
  34107. priority++;
  34108. result.optimizations.push(new PostProcessesOptimization(priority));
  34109. result.optimizations.push(new ParticlesOptimization(priority));
  34110. // Next priority
  34111. priority++;
  34112. result.optimizations.push(new TextureOptimization(priority, 256));
  34113. // Next priority
  34114. priority++;
  34115. result.optimizations.push(new RenderTargetsOptimization(priority));
  34116. // Next priority
  34117. priority++;
  34118. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  34119. return result;
  34120. };
  34121. return SceneOptimizerOptions;
  34122. })();
  34123. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  34124. // Scene optimizer tool
  34125. var SceneOptimizer = (function () {
  34126. function SceneOptimizer() {
  34127. }
  34128. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  34129. // TODO: add an epsilon
  34130. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  34131. if (onSuccess) {
  34132. onSuccess();
  34133. }
  34134. return;
  34135. }
  34136. // Apply current level of optimizations
  34137. var allDone = true;
  34138. var noOptimizationApplied = true;
  34139. for (var index = 0; index < options.optimizations.length; index++) {
  34140. var optimization = options.optimizations[index];
  34141. if (optimization.priority === currentPriorityLevel) {
  34142. noOptimizationApplied = false;
  34143. allDone = allDone && optimization.apply(scene);
  34144. }
  34145. }
  34146. // If no optimization was applied, this is a failure :(
  34147. if (noOptimizationApplied) {
  34148. if (onFailure) {
  34149. onFailure();
  34150. }
  34151. return;
  34152. }
  34153. // If all optimizations were done, move to next level
  34154. if (allDone) {
  34155. currentPriorityLevel++;
  34156. }
  34157. // Let's the system running for a specific amount of time before checking FPS
  34158. scene.executeWhenReady(function () {
  34159. setTimeout(function () {
  34160. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  34161. }, options.trackerDuration);
  34162. });
  34163. };
  34164. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  34165. if (!options) {
  34166. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  34167. }
  34168. // Let's the system running for a specific amount of time before checking FPS
  34169. scene.executeWhenReady(function () {
  34170. setTimeout(function () {
  34171. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  34172. }, options.trackerDuration);
  34173. });
  34174. };
  34175. return SceneOptimizer;
  34176. })();
  34177. BABYLON.SceneOptimizer = SceneOptimizer;
  34178. })(BABYLON || (BABYLON = {}));
  34179. var BABYLON;
  34180. (function (BABYLON) {
  34181. var Internals;
  34182. (function (Internals) {
  34183. var MeshLODLevel = (function () {
  34184. function MeshLODLevel(distance, mesh) {
  34185. this.distance = distance;
  34186. this.mesh = mesh;
  34187. }
  34188. return MeshLODLevel;
  34189. })();
  34190. Internals.MeshLODLevel = MeshLODLevel;
  34191. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  34192. })(BABYLON || (BABYLON = {}));
  34193. var BABYLON;
  34194. (function (BABYLON) {
  34195. var RawTexture = (function (_super) {
  34196. __extends(RawTexture, _super);
  34197. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  34198. if (generateMipMaps === void 0) { generateMipMaps = true; }
  34199. if (invertY === void 0) { invertY = false; }
  34200. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  34201. _super.call(this, null, scene, !generateMipMaps, invertY);
  34202. this.format = format;
  34203. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  34204. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34205. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34206. }
  34207. RawTexture.prototype.update = function (data) {
  34208. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  34209. };
  34210. // Statics
  34211. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  34212. if (generateMipMaps === void 0) { generateMipMaps = true; }
  34213. if (invertY === void 0) { invertY = false; }
  34214. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  34215. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  34216. };
  34217. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  34218. if (generateMipMaps === void 0) { generateMipMaps = true; }
  34219. if (invertY === void 0) { invertY = false; }
  34220. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  34221. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  34222. };
  34223. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  34224. if (generateMipMaps === void 0) { generateMipMaps = true; }
  34225. if (invertY === void 0) { invertY = false; }
  34226. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  34227. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  34228. };
  34229. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  34230. if (generateMipMaps === void 0) { generateMipMaps = true; }
  34231. if (invertY === void 0) { invertY = false; }
  34232. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  34233. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  34234. };
  34235. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  34236. if (generateMipMaps === void 0) { generateMipMaps = true; }
  34237. if (invertY === void 0) { invertY = false; }
  34238. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  34239. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  34240. };
  34241. return RawTexture;
  34242. })(BABYLON.Texture);
  34243. BABYLON.RawTexture = RawTexture;
  34244. })(BABYLON || (BABYLON = {}));
  34245. var BABYLON;
  34246. (function (BABYLON) {
  34247. var IndexedVector2 = (function (_super) {
  34248. __extends(IndexedVector2, _super);
  34249. function IndexedVector2(original, index) {
  34250. _super.call(this, original.x, original.y);
  34251. this.index = index;
  34252. }
  34253. return IndexedVector2;
  34254. })(BABYLON.Vector2);
  34255. var PolygonPoints = (function () {
  34256. function PolygonPoints() {
  34257. this.elements = new Array();
  34258. }
  34259. PolygonPoints.prototype.add = function (originalPoints) {
  34260. var _this = this;
  34261. var result = new Array();
  34262. originalPoints.forEach(function (point) {
  34263. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  34264. var newPoint = new IndexedVector2(point, _this.elements.length);
  34265. result.push(newPoint);
  34266. _this.elements.push(newPoint);
  34267. }
  34268. });
  34269. return result;
  34270. };
  34271. PolygonPoints.prototype.computeBounds = function () {
  34272. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  34273. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  34274. this.elements.forEach(function (point) {
  34275. // x
  34276. if (point.x < lmin.x) {
  34277. lmin.x = point.x;
  34278. }
  34279. else if (point.x > lmax.x) {
  34280. lmax.x = point.x;
  34281. }
  34282. // y
  34283. if (point.y < lmin.y) {
  34284. lmin.y = point.y;
  34285. }
  34286. else if (point.y > lmax.y) {
  34287. lmax.y = point.y;
  34288. }
  34289. });
  34290. return {
  34291. min: lmin,
  34292. max: lmax,
  34293. width: lmax.x - lmin.x,
  34294. height: lmax.y - lmin.y
  34295. };
  34296. };
  34297. return PolygonPoints;
  34298. })();
  34299. var Polygon = (function () {
  34300. function Polygon() {
  34301. }
  34302. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  34303. return [
  34304. new BABYLON.Vector2(xmin, ymin),
  34305. new BABYLON.Vector2(xmax, ymin),
  34306. new BABYLON.Vector2(xmax, ymax),
  34307. new BABYLON.Vector2(xmin, ymax)
  34308. ];
  34309. };
  34310. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  34311. if (cx === void 0) { cx = 0; }
  34312. if (cy === void 0) { cy = 0; }
  34313. if (numberOfSides === void 0) { numberOfSides = 32; }
  34314. var result = new Array();
  34315. var angle = 0;
  34316. var increment = (Math.PI * 2) / numberOfSides;
  34317. for (var i = 0; i < numberOfSides; i++) {
  34318. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  34319. angle -= increment;
  34320. }
  34321. return result;
  34322. };
  34323. Polygon.Parse = function (input) {
  34324. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  34325. var i, result = [];
  34326. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  34327. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  34328. }
  34329. return result;
  34330. };
  34331. Polygon.StartingAt = function (x, y) {
  34332. return BABYLON.Path2.StartingAt(x, y);
  34333. };
  34334. return Polygon;
  34335. })();
  34336. BABYLON.Polygon = Polygon;
  34337. var PolygonMeshBuilder = (function () {
  34338. function PolygonMeshBuilder(name, contours, scene) {
  34339. this._points = new PolygonPoints();
  34340. this._outlinepoints = new PolygonPoints();
  34341. this._holes = [];
  34342. if (!("poly2tri" in window)) {
  34343. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  34344. }
  34345. this._name = name;
  34346. this._scene = scene;
  34347. var points;
  34348. if (contours instanceof BABYLON.Path2) {
  34349. points = contours.getPoints();
  34350. }
  34351. else {
  34352. points = contours;
  34353. }
  34354. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  34355. this._outlinepoints.add(points);
  34356. }
  34357. PolygonMeshBuilder.prototype.addHole = function (hole) {
  34358. this._swctx.addHole(this._points.add(hole));
  34359. var holepoints = new PolygonPoints();
  34360. holepoints.add(hole);
  34361. this._holes.push(holepoints);
  34362. return this;
  34363. };
  34364. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  34365. var _this = this;
  34366. if (updatable === void 0) { updatable = false; }
  34367. var result = new BABYLON.Mesh(this._name, this._scene);
  34368. var normals = [];
  34369. var positions = [];
  34370. var uvs = [];
  34371. var bounds = this._points.computeBounds();
  34372. this._points.elements.forEach(function (p) {
  34373. normals.push(0, 1.0, 0);
  34374. positions.push(p.x, 0, p.y);
  34375. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  34376. });
  34377. var indices = [];
  34378. this._swctx.triangulate();
  34379. this._swctx.getTriangles().forEach(function (triangle) {
  34380. triangle.getPoints().forEach(function (point) {
  34381. indices.push(point.index);
  34382. });
  34383. });
  34384. if (depth > 0) {
  34385. var positionscount = (positions.length / 3); //get the current pointcount
  34386. this._points.elements.forEach(function (p) {
  34387. normals.push(0, -1.0, 0);
  34388. positions.push(p.x, -depth, p.y);
  34389. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  34390. });
  34391. var p1; //we need to change order of point so the triangles are made in the rigth way.
  34392. var p2;
  34393. var poscounter = 0;
  34394. this._swctx.getTriangles().forEach(function (triangle) {
  34395. triangle.getPoints().forEach(function (point) {
  34396. switch (poscounter) {
  34397. case 0:
  34398. p1 = point;
  34399. break;
  34400. case 1:
  34401. p2 = point;
  34402. break;
  34403. case 2:
  34404. indices.push(point.index + positionscount);
  34405. indices.push(p2.index + positionscount);
  34406. indices.push(p1.index + positionscount);
  34407. poscounter = -1;
  34408. break;
  34409. }
  34410. poscounter++;
  34411. //indices.push((<IndexedVector2>point).index + positionscount);
  34412. });
  34413. });
  34414. //Add the sides
  34415. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  34416. this._holes.forEach(function (hole) {
  34417. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  34418. });
  34419. }
  34420. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  34421. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  34422. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  34423. result.setIndices(indices);
  34424. return result;
  34425. };
  34426. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  34427. var StartIndex = positions.length / 3;
  34428. var ulength = 0;
  34429. for (var i = 0; i < points.elements.length; i++) {
  34430. var p = points.elements[i];
  34431. var p1;
  34432. if ((i + 1) > points.elements.length - 1) {
  34433. p1 = points.elements[0];
  34434. }
  34435. else {
  34436. p1 = points.elements[i + 1];
  34437. }
  34438. positions.push(p.x, 0, p.y);
  34439. positions.push(p.x, -depth, p.y);
  34440. positions.push(p1.x, 0, p1.y);
  34441. positions.push(p1.x, -depth, p1.y);
  34442. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  34443. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  34444. var v3 = v2.subtract(v1);
  34445. var v4 = new BABYLON.Vector3(0, 1, 0);
  34446. var vn = BABYLON.Vector3.Cross(v3, v4);
  34447. vn = vn.normalize();
  34448. uvs.push(ulength / bounds.width, 0);
  34449. uvs.push(ulength / bounds.width, 1);
  34450. ulength += v3.length();
  34451. uvs.push((ulength / bounds.width), 0);
  34452. uvs.push((ulength / bounds.width), 1);
  34453. if (!flip) {
  34454. normals.push(-vn.x, -vn.y, -vn.z);
  34455. normals.push(-vn.x, -vn.y, -vn.z);
  34456. normals.push(-vn.x, -vn.y, -vn.z);
  34457. normals.push(-vn.x, -vn.y, -vn.z);
  34458. indices.push(StartIndex);
  34459. indices.push(StartIndex + 1);
  34460. indices.push(StartIndex + 2);
  34461. indices.push(StartIndex + 1);
  34462. indices.push(StartIndex + 3);
  34463. indices.push(StartIndex + 2);
  34464. }
  34465. else {
  34466. normals.push(vn.x, vn.y, vn.z);
  34467. normals.push(vn.x, vn.y, vn.z);
  34468. normals.push(vn.x, vn.y, vn.z);
  34469. normals.push(vn.x, vn.y, vn.z);
  34470. indices.push(StartIndex);
  34471. indices.push(StartIndex + 2);
  34472. indices.push(StartIndex + 1);
  34473. indices.push(StartIndex + 1);
  34474. indices.push(StartIndex + 2);
  34475. indices.push(StartIndex + 3);
  34476. }
  34477. StartIndex += 4;
  34478. }
  34479. ;
  34480. };
  34481. return PolygonMeshBuilder;
  34482. })();
  34483. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  34484. })(BABYLON || (BABYLON = {}));
  34485. var BABYLON;
  34486. (function (BABYLON) {
  34487. var Octree = (function () {
  34488. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  34489. if (maxDepth === void 0) { maxDepth = 2; }
  34490. this.maxDepth = maxDepth;
  34491. this.dynamicContent = new Array();
  34492. this._maxBlockCapacity = maxBlockCapacity || 64;
  34493. this._selectionContent = new BABYLON.SmartArray(1024);
  34494. this._creationFunc = creationFunc;
  34495. }
  34496. // Methods
  34497. Octree.prototype.update = function (worldMin, worldMax, entries) {
  34498. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  34499. };
  34500. Octree.prototype.addMesh = function (entry) {
  34501. for (var index = 0; index < this.blocks.length; index++) {
  34502. var block = this.blocks[index];
  34503. block.addEntry(entry);
  34504. }
  34505. };
  34506. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  34507. this._selectionContent.reset();
  34508. for (var index = 0; index < this.blocks.length; index++) {
  34509. var block = this.blocks[index];
  34510. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  34511. }
  34512. if (allowDuplicate) {
  34513. this._selectionContent.concat(this.dynamicContent);
  34514. }
  34515. else {
  34516. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  34517. }
  34518. return this._selectionContent;
  34519. };
  34520. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  34521. this._selectionContent.reset();
  34522. for (var index = 0; index < this.blocks.length; index++) {
  34523. var block = this.blocks[index];
  34524. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  34525. }
  34526. if (allowDuplicate) {
  34527. this._selectionContent.concat(this.dynamicContent);
  34528. }
  34529. else {
  34530. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  34531. }
  34532. return this._selectionContent;
  34533. };
  34534. Octree.prototype.intersectsRay = function (ray) {
  34535. this._selectionContent.reset();
  34536. for (var index = 0; index < this.blocks.length; index++) {
  34537. var block = this.blocks[index];
  34538. block.intersectsRay(ray, this._selectionContent);
  34539. }
  34540. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  34541. return this._selectionContent;
  34542. };
  34543. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  34544. target.blocks = new Array();
  34545. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  34546. // Segmenting space
  34547. for (var x = 0; x < 2; x++) {
  34548. for (var y = 0; y < 2; y++) {
  34549. for (var z = 0; z < 2; z++) {
  34550. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  34551. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  34552. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  34553. block.addEntries(entries);
  34554. target.blocks.push(block);
  34555. }
  34556. }
  34557. }
  34558. };
  34559. Octree.CreationFuncForMeshes = function (entry, block) {
  34560. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  34561. block.entries.push(entry);
  34562. }
  34563. };
  34564. Octree.CreationFuncForSubMeshes = function (entry, block) {
  34565. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  34566. block.entries.push(entry);
  34567. }
  34568. };
  34569. return Octree;
  34570. })();
  34571. BABYLON.Octree = Octree;
  34572. })(BABYLON || (BABYLON = {}));
  34573. var BABYLON;
  34574. (function (BABYLON) {
  34575. var OctreeBlock = (function () {
  34576. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  34577. this.entries = new Array();
  34578. this._boundingVectors = new Array();
  34579. this._capacity = capacity;
  34580. this._depth = depth;
  34581. this._maxDepth = maxDepth;
  34582. this._creationFunc = creationFunc;
  34583. this._minPoint = minPoint;
  34584. this._maxPoint = maxPoint;
  34585. this._boundingVectors.push(minPoint.clone());
  34586. this._boundingVectors.push(maxPoint.clone());
  34587. this._boundingVectors.push(minPoint.clone());
  34588. this._boundingVectors[2].x = maxPoint.x;
  34589. this._boundingVectors.push(minPoint.clone());
  34590. this._boundingVectors[3].y = maxPoint.y;
  34591. this._boundingVectors.push(minPoint.clone());
  34592. this._boundingVectors[4].z = maxPoint.z;
  34593. this._boundingVectors.push(maxPoint.clone());
  34594. this._boundingVectors[5].z = minPoint.z;
  34595. this._boundingVectors.push(maxPoint.clone());
  34596. this._boundingVectors[6].x = minPoint.x;
  34597. this._boundingVectors.push(maxPoint.clone());
  34598. this._boundingVectors[7].y = minPoint.y;
  34599. }
  34600. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  34601. // Property
  34602. get: function () {
  34603. return this._capacity;
  34604. },
  34605. enumerable: true,
  34606. configurable: true
  34607. });
  34608. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  34609. get: function () {
  34610. return this._minPoint;
  34611. },
  34612. enumerable: true,
  34613. configurable: true
  34614. });
  34615. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  34616. get: function () {
  34617. return this._maxPoint;
  34618. },
  34619. enumerable: true,
  34620. configurable: true
  34621. });
  34622. // Methods
  34623. OctreeBlock.prototype.addEntry = function (entry) {
  34624. if (this.blocks) {
  34625. for (var index = 0; index < this.blocks.length; index++) {
  34626. var block = this.blocks[index];
  34627. block.addEntry(entry);
  34628. }
  34629. return;
  34630. }
  34631. this._creationFunc(entry, this);
  34632. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  34633. this.createInnerBlocks();
  34634. }
  34635. };
  34636. OctreeBlock.prototype.addEntries = function (entries) {
  34637. for (var index = 0; index < entries.length; index++) {
  34638. var mesh = entries[index];
  34639. this.addEntry(mesh);
  34640. }
  34641. };
  34642. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  34643. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  34644. if (this.blocks) {
  34645. for (var index = 0; index < this.blocks.length; index++) {
  34646. var block = this.blocks[index];
  34647. block.select(frustumPlanes, selection, allowDuplicate);
  34648. }
  34649. return;
  34650. }
  34651. if (allowDuplicate) {
  34652. selection.concat(this.entries);
  34653. }
  34654. else {
  34655. selection.concatWithNoDuplicate(this.entries);
  34656. }
  34657. }
  34658. };
  34659. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  34660. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  34661. if (this.blocks) {
  34662. for (var index = 0; index < this.blocks.length; index++) {
  34663. var block = this.blocks[index];
  34664. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  34665. }
  34666. return;
  34667. }
  34668. if (allowDuplicate) {
  34669. selection.concat(this.entries);
  34670. }
  34671. else {
  34672. selection.concatWithNoDuplicate(this.entries);
  34673. }
  34674. }
  34675. };
  34676. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  34677. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  34678. if (this.blocks) {
  34679. for (var index = 0; index < this.blocks.length; index++) {
  34680. var block = this.blocks[index];
  34681. block.intersectsRay(ray, selection);
  34682. }
  34683. return;
  34684. }
  34685. selection.concatWithNoDuplicate(this.entries);
  34686. }
  34687. };
  34688. OctreeBlock.prototype.createInnerBlocks = function () {
  34689. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  34690. };
  34691. return OctreeBlock;
  34692. })();
  34693. BABYLON.OctreeBlock = OctreeBlock;
  34694. })(BABYLON || (BABYLON = {}));
  34695. var BABYLON;
  34696. (function (BABYLON) {
  34697. var BlurPostProcess = (function (_super) {
  34698. __extends(BlurPostProcess, _super);
  34699. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  34700. var _this = this;
  34701. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  34702. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  34703. this.direction = direction;
  34704. this.blurWidth = blurWidth;
  34705. this.onApply = function (effect) {
  34706. effect.setFloat2("screenSize", _this.width, _this.height);
  34707. effect.setVector2("direction", _this.direction);
  34708. effect.setFloat("blurWidth", _this.blurWidth);
  34709. };
  34710. }
  34711. return BlurPostProcess;
  34712. })(BABYLON.PostProcess);
  34713. BABYLON.BlurPostProcess = BlurPostProcess;
  34714. })(BABYLON || (BABYLON = {}));
  34715. var BABYLON;
  34716. (function (BABYLON) {
  34717. var RefractionPostProcess = (function (_super) {
  34718. __extends(RefractionPostProcess, _super);
  34719. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  34720. var _this = this;
  34721. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  34722. this.color = color;
  34723. this.depth = depth;
  34724. this.colorLevel = colorLevel;
  34725. this.onActivate = function (cam) {
  34726. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  34727. };
  34728. this.onApply = function (effect) {
  34729. effect.setColor3("baseColor", _this.color);
  34730. effect.setFloat("depth", _this.depth);
  34731. effect.setFloat("colorLevel", _this.colorLevel);
  34732. effect.setTexture("refractionSampler", _this._refRexture);
  34733. };
  34734. }
  34735. // Methods
  34736. RefractionPostProcess.prototype.dispose = function (camera) {
  34737. if (this._refRexture) {
  34738. this._refRexture.dispose();
  34739. }
  34740. _super.prototype.dispose.call(this, camera);
  34741. };
  34742. return RefractionPostProcess;
  34743. })(BABYLON.PostProcess);
  34744. BABYLON.RefractionPostProcess = RefractionPostProcess;
  34745. })(BABYLON || (BABYLON = {}));
  34746. var BABYLON;
  34747. (function (BABYLON) {
  34748. var BlackAndWhitePostProcess = (function (_super) {
  34749. __extends(BlackAndWhitePostProcess, _super);
  34750. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  34751. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  34752. }
  34753. return BlackAndWhitePostProcess;
  34754. })(BABYLON.PostProcess);
  34755. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  34756. })(BABYLON || (BABYLON = {}));
  34757. var BABYLON;
  34758. (function (BABYLON) {
  34759. var ConvolutionPostProcess = (function (_super) {
  34760. __extends(ConvolutionPostProcess, _super);
  34761. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  34762. var _this = this;
  34763. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  34764. this.kernel = kernel;
  34765. this.onApply = function (effect) {
  34766. effect.setFloat2("screenSize", _this.width, _this.height);
  34767. effect.setArray("kernel", _this.kernel);
  34768. };
  34769. }
  34770. // Statics
  34771. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  34772. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  34773. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  34774. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  34775. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  34776. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  34777. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  34778. return ConvolutionPostProcess;
  34779. })(BABYLON.PostProcess);
  34780. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  34781. })(BABYLON || (BABYLON = {}));
  34782. var BABYLON;
  34783. (function (BABYLON) {
  34784. var FilterPostProcess = (function (_super) {
  34785. __extends(FilterPostProcess, _super);
  34786. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  34787. var _this = this;
  34788. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  34789. this.kernelMatrix = kernelMatrix;
  34790. this.onApply = function (effect) {
  34791. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  34792. };
  34793. }
  34794. return FilterPostProcess;
  34795. })(BABYLON.PostProcess);
  34796. BABYLON.FilterPostProcess = FilterPostProcess;
  34797. })(BABYLON || (BABYLON = {}));
  34798. var BABYLON;
  34799. (function (BABYLON) {
  34800. var FxaaPostProcess = (function (_super) {
  34801. __extends(FxaaPostProcess, _super);
  34802. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  34803. var _this = this;
  34804. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  34805. this.onSizeChanged = function () {
  34806. _this.texelWidth = 1.0 / _this.width;
  34807. _this.texelHeight = 1.0 / _this.height;
  34808. };
  34809. this.onApply = function (effect) {
  34810. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  34811. };
  34812. }
  34813. return FxaaPostProcess;
  34814. })(BABYLON.PostProcess);
  34815. BABYLON.FxaaPostProcess = FxaaPostProcess;
  34816. })(BABYLON || (BABYLON = {}));
  34817. var BABYLON;
  34818. (function (BABYLON) {
  34819. var StereoscopicInterlacePostProcess = (function (_super) {
  34820. __extends(StereoscopicInterlacePostProcess, _super);
  34821. function StereoscopicInterlacePostProcess(name, camB, postProcessA, isStereoscopicHoriz, samplingMode) {
  34822. var _this = this;
  34823. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, camB, samplingMode, camB.getScene().getEngine(), false, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  34824. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  34825. this.onSizeChanged = function () {
  34826. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  34827. };
  34828. this.onApply = function (effect) {
  34829. effect.setTextureFromPostProcess("camASampler", postProcessA);
  34830. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  34831. };
  34832. }
  34833. return StereoscopicInterlacePostProcess;
  34834. })(BABYLON.PostProcess);
  34835. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  34836. })(BABYLON || (BABYLON = {}));
  34837. var BABYLON;
  34838. (function (BABYLON) {
  34839. var LensFlare = (function () {
  34840. function LensFlare(size, position, color, imgUrl, system) {
  34841. this.size = size;
  34842. this.position = position;
  34843. this.dispose = function () {
  34844. if (this.texture) {
  34845. this.texture.dispose();
  34846. }
  34847. // Remove from scene
  34848. var index = this._system.lensFlares.indexOf(this);
  34849. this._system.lensFlares.splice(index, 1);
  34850. };
  34851. this.color = color || new BABYLON.Color3(1, 1, 1);
  34852. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  34853. this._system = system;
  34854. system.lensFlares.push(this);
  34855. }
  34856. return LensFlare;
  34857. })();
  34858. BABYLON.LensFlare = LensFlare;
  34859. })(BABYLON || (BABYLON = {}));
  34860. var BABYLON;
  34861. (function (BABYLON) {
  34862. var LensFlareSystem = (function () {
  34863. function LensFlareSystem(name, emitter, scene) {
  34864. this.name = name;
  34865. this.lensFlares = new Array();
  34866. this.borderLimit = 300;
  34867. this.layerMask = 0x0FFFFFFF;
  34868. this._vertexDeclaration = [2];
  34869. this._vertexStrideSize = 2 * 4;
  34870. this._isEnabled = true;
  34871. this._scene = scene;
  34872. this._emitter = emitter;
  34873. scene.lensFlareSystems.push(this);
  34874. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  34875. // VBO
  34876. var vertices = [];
  34877. vertices.push(1, 1);
  34878. vertices.push(-1, 1);
  34879. vertices.push(-1, -1);
  34880. vertices.push(1, -1);
  34881. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  34882. // Indices
  34883. var indices = [];
  34884. indices.push(0);
  34885. indices.push(1);
  34886. indices.push(2);
  34887. indices.push(0);
  34888. indices.push(2);
  34889. indices.push(3);
  34890. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  34891. // Effects
  34892. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  34893. }
  34894. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  34895. get: function () {
  34896. return this._isEnabled;
  34897. },
  34898. set: function (value) {
  34899. this._isEnabled = value;
  34900. },
  34901. enumerable: true,
  34902. configurable: true
  34903. });
  34904. LensFlareSystem.prototype.getScene = function () {
  34905. return this._scene;
  34906. };
  34907. LensFlareSystem.prototype.getEmitter = function () {
  34908. return this._emitter;
  34909. };
  34910. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  34911. this._emitter = newEmitter;
  34912. };
  34913. LensFlareSystem.prototype.getEmitterPosition = function () {
  34914. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  34915. };
  34916. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  34917. var position = this.getEmitterPosition();
  34918. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  34919. this._positionX = position.x;
  34920. this._positionY = position.y;
  34921. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  34922. if (position.z > 0) {
  34923. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  34924. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  34925. return true;
  34926. }
  34927. }
  34928. return false;
  34929. };
  34930. LensFlareSystem.prototype._isVisible = function () {
  34931. if (!this._isEnabled) {
  34932. return false;
  34933. }
  34934. var emitterPosition = this.getEmitterPosition();
  34935. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  34936. var distance = direction.length();
  34937. direction.normalize();
  34938. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  34939. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  34940. return !pickInfo.hit || pickInfo.distance > distance;
  34941. };
  34942. LensFlareSystem.prototype.render = function () {
  34943. if (!this._effect.isReady())
  34944. return false;
  34945. var engine = this._scene.getEngine();
  34946. var viewport = this._scene.activeCamera.viewport;
  34947. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  34948. // Position
  34949. if (!this.computeEffectivePosition(globalViewport)) {
  34950. return false;
  34951. }
  34952. // Visibility
  34953. if (!this._isVisible()) {
  34954. return false;
  34955. }
  34956. // Intensity
  34957. var awayX;
  34958. var awayY;
  34959. if (this._positionX < this.borderLimit + globalViewport.x) {
  34960. awayX = this.borderLimit + globalViewport.x - this._positionX;
  34961. }
  34962. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  34963. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  34964. }
  34965. else {
  34966. awayX = 0;
  34967. }
  34968. if (this._positionY < this.borderLimit + globalViewport.y) {
  34969. awayY = this.borderLimit + globalViewport.y - this._positionY;
  34970. }
  34971. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  34972. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  34973. }
  34974. else {
  34975. awayY = 0;
  34976. }
  34977. var away = (awayX > awayY) ? awayX : awayY;
  34978. if (away > this.borderLimit) {
  34979. away = this.borderLimit;
  34980. }
  34981. var intensity = 1.0 - (away / this.borderLimit);
  34982. if (intensity < 0) {
  34983. return false;
  34984. }
  34985. if (intensity > 1.0) {
  34986. intensity = 1.0;
  34987. }
  34988. // Position
  34989. var centerX = globalViewport.x + globalViewport.width / 2;
  34990. var centerY = globalViewport.y + globalViewport.height / 2;
  34991. var distX = centerX - this._positionX;
  34992. var distY = centerY - this._positionY;
  34993. // Effects
  34994. engine.enableEffect(this._effect);
  34995. engine.setState(false);
  34996. engine.setDepthBuffer(false);
  34997. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  34998. // VBOs
  34999. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  35000. // Flares
  35001. for (var index = 0; index < this.lensFlares.length; index++) {
  35002. var flare = this.lensFlares[index];
  35003. var x = centerX - (distX * flare.position);
  35004. var y = centerY - (distY * flare.position);
  35005. var cw = flare.size;
  35006. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  35007. var cx = 2 * (x / globalViewport.width) - 1.0;
  35008. var cy = 1.0 - 2 * (y / globalViewport.height);
  35009. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  35010. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  35011. // Texture
  35012. this._effect.setTexture("textureSampler", flare.texture);
  35013. // Color
  35014. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  35015. // Draw order
  35016. engine.draw(true, 0, 6);
  35017. }
  35018. engine.setDepthBuffer(true);
  35019. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  35020. return true;
  35021. };
  35022. LensFlareSystem.prototype.dispose = function () {
  35023. if (this._vertexBuffer) {
  35024. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  35025. this._vertexBuffer = null;
  35026. }
  35027. if (this._indexBuffer) {
  35028. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  35029. this._indexBuffer = null;
  35030. }
  35031. while (this.lensFlares.length) {
  35032. this.lensFlares[0].dispose();
  35033. }
  35034. // Remove from scene
  35035. var index = this._scene.lensFlareSystems.indexOf(this);
  35036. this._scene.lensFlareSystems.splice(index, 1);
  35037. };
  35038. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  35039. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  35040. var lensFlareSystem = new LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  35041. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  35042. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  35043. var parsedFlare = parsedLensFlareSystem.flares[index];
  35044. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  35045. }
  35046. return lensFlareSystem;
  35047. };
  35048. LensFlareSystem.prototype.serialize = function () {
  35049. var serializationObject = {};
  35050. serializationObject.emitterId = this.getEmitter().id;
  35051. serializationObject.borderLimit = this.borderLimit;
  35052. serializationObject.flares = [];
  35053. for (var index = 0; index < this.lensFlares.length; index++) {
  35054. var flare = this.lensFlares[index];
  35055. serializationObject.flares.push({
  35056. size: flare.size,
  35057. position: flare.position,
  35058. color: flare.color.asArray(),
  35059. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  35060. });
  35061. }
  35062. return serializationObject;
  35063. };
  35064. return LensFlareSystem;
  35065. })();
  35066. BABYLON.LensFlareSystem = LensFlareSystem;
  35067. })(BABYLON || (BABYLON = {}));
  35068. var BABYLON;
  35069. (function (BABYLON) {
  35070. // We're mainly based on the logic defined into the FreeCamera code
  35071. var DeviceOrientationCamera = (function (_super) {
  35072. __extends(DeviceOrientationCamera, _super);
  35073. function DeviceOrientationCamera(name, position, scene) {
  35074. var _this = this;
  35075. _super.call(this, name, position, scene);
  35076. this._offsetX = null;
  35077. this._offsetY = null;
  35078. this._orientationGamma = 0;
  35079. this._orientationBeta = 0;
  35080. this._initialOrientationGamma = 0;
  35081. this._initialOrientationBeta = 0;
  35082. this.angularSensibility = 10000.0;
  35083. this.moveSensibility = 50.0;
  35084. window.addEventListener("resize", function () {
  35085. _this._initialOrientationGamma = null;
  35086. }, false);
  35087. }
  35088. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  35089. var _this = this;
  35090. if (this._attachedCanvas) {
  35091. return;
  35092. }
  35093. this._attachedCanvas = canvas;
  35094. if (!this._orientationChanged) {
  35095. this._orientationChanged = function (evt) {
  35096. if (!_this._initialOrientationGamma) {
  35097. _this._initialOrientationGamma = evt.gamma;
  35098. _this._initialOrientationBeta = evt.beta;
  35099. }
  35100. _this._orientationGamma = evt.gamma;
  35101. _this._orientationBeta = evt.beta;
  35102. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  35103. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  35104. };
  35105. }
  35106. window.addEventListener("deviceorientation", this._orientationChanged);
  35107. };
  35108. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  35109. if (this._attachedCanvas !== canvas) {
  35110. return;
  35111. }
  35112. window.removeEventListener("deviceorientation", this._orientationChanged);
  35113. this._attachedCanvas = null;
  35114. this._orientationGamma = 0;
  35115. this._orientationBeta = 0;
  35116. this._initialOrientationGamma = 0;
  35117. this._initialOrientationBeta = 0;
  35118. };
  35119. DeviceOrientationCamera.prototype._checkInputs = function () {
  35120. if (!this._offsetX) {
  35121. return;
  35122. }
  35123. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  35124. var speed = this._computeLocalCameraSpeed();
  35125. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  35126. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  35127. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  35128. _super.prototype._checkInputs.call(this);
  35129. };
  35130. DeviceOrientationCamera.prototype.getTypeName = function () {
  35131. return "DeviceOrientationCamera";
  35132. };
  35133. __decorate([
  35134. BABYLON.serialize()
  35135. ], DeviceOrientationCamera.prototype, "angularSensibility", void 0);
  35136. __decorate([
  35137. BABYLON.serialize()
  35138. ], DeviceOrientationCamera.prototype, "moveSensibility", void 0);
  35139. return DeviceOrientationCamera;
  35140. })(BABYLON.FreeCamera);
  35141. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  35142. })(BABYLON || (BABYLON = {}));
  35143. var BABYLON;
  35144. (function (BABYLON) {
  35145. var Analyser = (function () {
  35146. function Analyser(scene) {
  35147. this.SMOOTHING = 0.75;
  35148. this.FFT_SIZE = 512;
  35149. this.BARGRAPHAMPLITUDE = 256;
  35150. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  35151. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  35152. this._scene = scene;
  35153. this._audioEngine = BABYLON.Engine.audioEngine;
  35154. if (this._audioEngine.canUseWebAudio) {
  35155. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  35156. this._webAudioAnalyser.minDecibels = -140;
  35157. this._webAudioAnalyser.maxDecibels = 0;
  35158. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  35159. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  35160. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  35161. }
  35162. }
  35163. Analyser.prototype.getFrequencyBinCount = function () {
  35164. if (this._audioEngine.canUseWebAudio) {
  35165. return this._webAudioAnalyser.frequencyBinCount;
  35166. }
  35167. else {
  35168. return 0;
  35169. }
  35170. };
  35171. Analyser.prototype.getByteFrequencyData = function () {
  35172. if (this._audioEngine.canUseWebAudio) {
  35173. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  35174. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  35175. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  35176. }
  35177. return this._byteFreqs;
  35178. };
  35179. Analyser.prototype.getByteTimeDomainData = function () {
  35180. if (this._audioEngine.canUseWebAudio) {
  35181. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  35182. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  35183. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  35184. }
  35185. return this._byteTime;
  35186. };
  35187. Analyser.prototype.getFloatFrequencyData = function () {
  35188. if (this._audioEngine.canUseWebAudio) {
  35189. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  35190. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  35191. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  35192. }
  35193. return this._floatFreqs;
  35194. };
  35195. Analyser.prototype.drawDebugCanvas = function () {
  35196. var _this = this;
  35197. if (this._audioEngine.canUseWebAudio) {
  35198. if (!this._debugCanvas) {
  35199. this._debugCanvas = document.createElement("canvas");
  35200. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  35201. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  35202. this._debugCanvas.style.position = "absolute";
  35203. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  35204. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  35205. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  35206. document.body.appendChild(this._debugCanvas);
  35207. this._registerFunc = function () {
  35208. _this.drawDebugCanvas();
  35209. };
  35210. this._scene.registerBeforeRender(this._registerFunc);
  35211. }
  35212. if (this._registerFunc) {
  35213. var workingArray = this.getByteFrequencyData();
  35214. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  35215. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  35216. // Draw the frequency domain chart.
  35217. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  35218. var value = workingArray[i];
  35219. var percent = value / this.BARGRAPHAMPLITUDE;
  35220. var height = this.DEBUGCANVASSIZE.height * percent;
  35221. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  35222. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  35223. var hue = i / this.getFrequencyBinCount() * 360;
  35224. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  35225. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  35226. }
  35227. }
  35228. }
  35229. };
  35230. Analyser.prototype.stopDebugCanvas = function () {
  35231. if (this._debugCanvas) {
  35232. this._scene.unregisterBeforeRender(this._registerFunc);
  35233. this._registerFunc = null;
  35234. document.body.removeChild(this._debugCanvas);
  35235. this._debugCanvas = null;
  35236. this._debugCanvasContext = null;
  35237. }
  35238. };
  35239. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  35240. if (this._audioEngine.canUseWebAudio) {
  35241. inputAudioNode.connect(this._webAudioAnalyser);
  35242. this._webAudioAnalyser.connect(outputAudioNode);
  35243. }
  35244. };
  35245. Analyser.prototype.dispose = function () {
  35246. if (this._audioEngine.canUseWebAudio) {
  35247. this._webAudioAnalyser.disconnect();
  35248. }
  35249. };
  35250. return Analyser;
  35251. })();
  35252. BABYLON.Analyser = Analyser;
  35253. })(BABYLON || (BABYLON = {}));
  35254. var BABYLON;
  35255. (function (BABYLON) {
  35256. var AudioEngine = (function () {
  35257. function AudioEngine() {
  35258. this._audioContext = null;
  35259. this._audioContextInitialized = false;
  35260. this.canUseWebAudio = false;
  35261. this.WarnedWebAudioUnsupported = false;
  35262. this.unlocked = false;
  35263. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  35264. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  35265. this.canUseWebAudio = true;
  35266. }
  35267. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  35268. this._unlockiOSaudio();
  35269. }
  35270. else {
  35271. this.unlocked = true;
  35272. }
  35273. }
  35274. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  35275. get: function () {
  35276. if (!this._audioContextInitialized) {
  35277. this._initializeAudioContext();
  35278. }
  35279. return this._audioContext;
  35280. },
  35281. enumerable: true,
  35282. configurable: true
  35283. });
  35284. AudioEngine.prototype._unlockiOSaudio = function () {
  35285. var _this = this;
  35286. var unlockaudio = function () {
  35287. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  35288. var source = _this.audioContext.createBufferSource();
  35289. source.buffer = buffer;
  35290. source.connect(_this.audioContext.destination);
  35291. source.start(0);
  35292. setTimeout(function () {
  35293. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  35294. _this.unlocked = true;
  35295. window.removeEventListener('touchend', unlockaudio, false);
  35296. if (_this.onAudioUnlocked) {
  35297. _this.onAudioUnlocked();
  35298. }
  35299. }
  35300. }, 0);
  35301. };
  35302. window.addEventListener('touchend', unlockaudio, false);
  35303. };
  35304. AudioEngine.prototype._initializeAudioContext = function () {
  35305. try {
  35306. if (this.canUseWebAudio) {
  35307. this._audioContext = new AudioContext();
  35308. // create a global volume gain node
  35309. this.masterGain = this._audioContext.createGain();
  35310. this.masterGain.gain.value = 1;
  35311. this.masterGain.connect(this._audioContext.destination);
  35312. this._audioContextInitialized = true;
  35313. }
  35314. }
  35315. catch (e) {
  35316. this.canUseWebAudio = false;
  35317. BABYLON.Tools.Error("Web Audio: " + e.message);
  35318. }
  35319. };
  35320. AudioEngine.prototype.dispose = function () {
  35321. if (this.canUseWebAudio && this._audioContextInitialized) {
  35322. if (this._connectedAnalyser) {
  35323. this._connectedAnalyser.stopDebugCanvas();
  35324. this._connectedAnalyser.dispose();
  35325. this.masterGain.disconnect();
  35326. this.masterGain.connect(this._audioContext.destination);
  35327. this._connectedAnalyser = null;
  35328. }
  35329. this.masterGain.gain.value = 1;
  35330. }
  35331. this.WarnedWebAudioUnsupported = false;
  35332. };
  35333. AudioEngine.prototype.getGlobalVolume = function () {
  35334. if (this.canUseWebAudio && this._audioContextInitialized) {
  35335. return this.masterGain.gain.value;
  35336. }
  35337. else {
  35338. return -1;
  35339. }
  35340. };
  35341. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  35342. if (this.canUseWebAudio && this._audioContextInitialized) {
  35343. this.masterGain.gain.value = newVolume;
  35344. }
  35345. };
  35346. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  35347. if (this._connectedAnalyser) {
  35348. this._connectedAnalyser.stopDebugCanvas();
  35349. }
  35350. if (this.canUseWebAudio && this._audioContextInitialized) {
  35351. this._connectedAnalyser = analyser;
  35352. this.masterGain.disconnect();
  35353. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  35354. }
  35355. };
  35356. return AudioEngine;
  35357. })();
  35358. BABYLON.AudioEngine = AudioEngine;
  35359. })(BABYLON || (BABYLON = {}));
  35360. var BABYLON;
  35361. (function (BABYLON) {
  35362. var Sound = (function () {
  35363. /**
  35364. * Create a sound and attach it to a scene
  35365. * @param name Name of your sound
  35366. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  35367. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  35368. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  35369. */
  35370. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  35371. var _this = this;
  35372. this.autoplay = false;
  35373. this.loop = false;
  35374. this.useCustomAttenuation = false;
  35375. this.spatialSound = false;
  35376. this.refDistance = 1;
  35377. this.rolloffFactor = 1;
  35378. this.maxDistance = 100;
  35379. this.distanceModel = "linear";
  35380. this._panningModel = "equalpower";
  35381. this._playbackRate = 1;
  35382. this._streaming = false;
  35383. this._startTime = 0;
  35384. this._startOffset = 0;
  35385. this._position = BABYLON.Vector3.Zero();
  35386. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  35387. this._volume = 1;
  35388. this._isLoaded = false;
  35389. this._isReadyToPlay = false;
  35390. this.isPlaying = false;
  35391. this.isPaused = false;
  35392. this._isDirectional = false;
  35393. // Used if you'd like to create a directional sound.
  35394. // If not set, the sound will be omnidirectional
  35395. this._coneInnerAngle = 360;
  35396. this._coneOuterAngle = 360;
  35397. this._coneOuterGain = 0;
  35398. this._isOutputConnected = false;
  35399. this.name = name;
  35400. this._scene = scene;
  35401. this._readyToPlayCallback = readyToPlayCallback;
  35402. // Default custom attenuation function is a linear attenuation
  35403. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  35404. if (currentDistance < maxDistance) {
  35405. return currentVolume * (1 - currentDistance / maxDistance);
  35406. }
  35407. else {
  35408. return 0;
  35409. }
  35410. };
  35411. if (options) {
  35412. this.autoplay = options.autoplay || false;
  35413. this.loop = options.loop || false;
  35414. // if volume === 0, we need another way to check this option
  35415. if (options.volume !== undefined) {
  35416. this._volume = options.volume;
  35417. }
  35418. this.spatialSound = options.spatialSound || false;
  35419. this.maxDistance = options.maxDistance || 100;
  35420. this.useCustomAttenuation = options.useCustomAttenuation || false;
  35421. this.rolloffFactor = options.rolloffFactor || 1;
  35422. this.refDistance = options.refDistance || 1;
  35423. this.distanceModel = options.distanceModel || "linear";
  35424. this._playbackRate = options.playbackRate || 1;
  35425. this._streaming = options.streaming || false;
  35426. }
  35427. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35428. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  35429. this._soundGain.gain.value = this._volume;
  35430. this._inputAudioNode = this._soundGain;
  35431. this._ouputAudioNode = this._soundGain;
  35432. if (this.spatialSound) {
  35433. this._createSpatialParameters();
  35434. }
  35435. this._scene.mainSoundTrack.AddSound(this);
  35436. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  35437. if (urlOrArrayBuffer) {
  35438. // If it's an URL
  35439. if (typeof (urlOrArrayBuffer) === "string") {
  35440. // Loading sound using XHR2
  35441. if (!this._streaming) {
  35442. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  35443. }
  35444. else {
  35445. this._htmlAudioElement = new Audio(urlOrArrayBuffer);
  35446. this._htmlAudioElement.controls = false;
  35447. this._htmlAudioElement.loop = this.loop;
  35448. this._htmlAudioElement.crossOrigin = "anonymous";
  35449. this._htmlAudioElement.preload = "auto";
  35450. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  35451. _this._isReadyToPlay = true;
  35452. if (_this.autoplay) {
  35453. _this.play();
  35454. }
  35455. if (_this._readyToPlayCallback) {
  35456. _this._readyToPlayCallback();
  35457. }
  35458. });
  35459. document.body.appendChild(this._htmlAudioElement);
  35460. }
  35461. }
  35462. else {
  35463. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  35464. if (urlOrArrayBuffer.byteLength > 0) {
  35465. this._soundLoaded(urlOrArrayBuffer);
  35466. }
  35467. }
  35468. else {
  35469. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  35470. }
  35471. }
  35472. }
  35473. }
  35474. else {
  35475. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  35476. this._scene.mainSoundTrack.AddSound(this);
  35477. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  35478. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  35479. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  35480. }
  35481. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  35482. if (this._readyToPlayCallback) {
  35483. window.setTimeout(function () {
  35484. _this._readyToPlayCallback();
  35485. }, 1000);
  35486. }
  35487. }
  35488. }
  35489. Sound.prototype.dispose = function () {
  35490. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  35491. if (this.isPlaying) {
  35492. this.stop();
  35493. }
  35494. this._isReadyToPlay = false;
  35495. if (this.soundTrackId === -1) {
  35496. this._scene.mainSoundTrack.RemoveSound(this);
  35497. }
  35498. else {
  35499. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  35500. }
  35501. if (this._soundGain) {
  35502. this._soundGain.disconnect();
  35503. this._soundGain = null;
  35504. }
  35505. if (this._soundPanner) {
  35506. this._soundPanner.disconnect();
  35507. this._soundPanner = null;
  35508. }
  35509. if (this._soundSource) {
  35510. this._soundSource.disconnect();
  35511. this._soundSource = null;
  35512. }
  35513. this._audioBuffer = null;
  35514. if (this._htmlAudioElement) {
  35515. this._htmlAudioElement.pause();
  35516. this._htmlAudioElement.src = "";
  35517. document.body.removeChild(this._htmlAudioElement);
  35518. }
  35519. if (this._connectedMesh) {
  35520. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  35521. this._connectedMesh = null;
  35522. }
  35523. }
  35524. };
  35525. Sound.prototype._soundLoaded = function (audioData) {
  35526. var _this = this;
  35527. this._isLoaded = true;
  35528. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  35529. _this._audioBuffer = buffer;
  35530. _this._isReadyToPlay = true;
  35531. if (_this.autoplay) {
  35532. _this.play();
  35533. }
  35534. if (_this._readyToPlayCallback) {
  35535. _this._readyToPlayCallback();
  35536. }
  35537. }, function () { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name); });
  35538. };
  35539. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  35540. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35541. this._audioBuffer = audioBuffer;
  35542. this._isReadyToPlay = true;
  35543. }
  35544. };
  35545. Sound.prototype.updateOptions = function (options) {
  35546. if (options) {
  35547. this.loop = options.loop || this.loop;
  35548. this.maxDistance = options.maxDistance || this.maxDistance;
  35549. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  35550. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  35551. this.refDistance = options.refDistance || this.refDistance;
  35552. this.distanceModel = options.distanceModel || this.distanceModel;
  35553. this._playbackRate = options.playbackRate || this._playbackRate;
  35554. this._updateSpatialParameters();
  35555. if (this.isPlaying) {
  35556. if (this._streaming) {
  35557. this._htmlAudioElement.playbackRate = this._playbackRate;
  35558. }
  35559. else {
  35560. this._soundSource.playbackRate.value = this._playbackRate;
  35561. }
  35562. }
  35563. }
  35564. };
  35565. Sound.prototype._createSpatialParameters = function () {
  35566. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35567. if (this._scene.headphone) {
  35568. this._panningModel = "HRTF";
  35569. }
  35570. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  35571. this._updateSpatialParameters();
  35572. this._soundPanner.connect(this._ouputAudioNode);
  35573. this._inputAudioNode = this._soundPanner;
  35574. }
  35575. };
  35576. Sound.prototype._updateSpatialParameters = function () {
  35577. if (this.spatialSound) {
  35578. if (this.useCustomAttenuation) {
  35579. // Tricks to disable in a way embedded Web Audio attenuation
  35580. this._soundPanner.distanceModel = "linear";
  35581. this._soundPanner.maxDistance = Number.MAX_VALUE;
  35582. this._soundPanner.refDistance = 1;
  35583. this._soundPanner.rolloffFactor = 1;
  35584. this._soundPanner.panningModel = this._panningModel;
  35585. }
  35586. else {
  35587. this._soundPanner.distanceModel = this.distanceModel;
  35588. this._soundPanner.maxDistance = this.maxDistance;
  35589. this._soundPanner.refDistance = this.refDistance;
  35590. this._soundPanner.rolloffFactor = this.rolloffFactor;
  35591. this._soundPanner.panningModel = this._panningModel;
  35592. }
  35593. }
  35594. };
  35595. Sound.prototype.switchPanningModelToHRTF = function () {
  35596. this._panningModel = "HRTF";
  35597. this._switchPanningModel();
  35598. };
  35599. Sound.prototype.switchPanningModelToEqualPower = function () {
  35600. this._panningModel = "equalpower";
  35601. this._switchPanningModel();
  35602. };
  35603. Sound.prototype._switchPanningModel = function () {
  35604. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  35605. this._soundPanner.panningModel = this._panningModel;
  35606. }
  35607. };
  35608. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  35609. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35610. if (this._isOutputConnected) {
  35611. this._ouputAudioNode.disconnect();
  35612. }
  35613. this._ouputAudioNode.connect(soundTrackAudioNode);
  35614. this._isOutputConnected = true;
  35615. }
  35616. };
  35617. /**
  35618. * Transform this sound into a directional source
  35619. * @param coneInnerAngle Size of the inner cone in degree
  35620. * @param coneOuterAngle Size of the outer cone in degree
  35621. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  35622. */
  35623. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  35624. if (coneOuterAngle < coneInnerAngle) {
  35625. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  35626. return;
  35627. }
  35628. this._coneInnerAngle = coneInnerAngle;
  35629. this._coneOuterAngle = coneOuterAngle;
  35630. this._coneOuterGain = coneOuterGain;
  35631. this._isDirectional = true;
  35632. if (this.isPlaying && this.loop) {
  35633. this.stop();
  35634. this.play();
  35635. }
  35636. };
  35637. Sound.prototype.setPosition = function (newPosition) {
  35638. this._position = newPosition;
  35639. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  35640. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  35641. }
  35642. };
  35643. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  35644. this._localDirection = newLocalDirection;
  35645. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  35646. this._updateDirection();
  35647. }
  35648. };
  35649. Sound.prototype._updateDirection = function () {
  35650. var mat = this._connectedMesh.getWorldMatrix();
  35651. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  35652. direction.normalize();
  35653. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  35654. };
  35655. Sound.prototype.updateDistanceFromListener = function () {
  35656. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  35657. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  35658. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  35659. }
  35660. };
  35661. Sound.prototype.setAttenuationFunction = function (callback) {
  35662. this._customAttenuationFunction = callback;
  35663. };
  35664. /**
  35665. * Play the sound
  35666. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  35667. */
  35668. Sound.prototype.play = function (time) {
  35669. var _this = this;
  35670. if (this._isReadyToPlay && this._scene.audioEnabled) {
  35671. try {
  35672. if (this._startOffset < 0) {
  35673. time = -this._startOffset;
  35674. this._startOffset = 0;
  35675. }
  35676. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  35677. if (!this._soundSource || !this._streamingSource) {
  35678. if (this.spatialSound) {
  35679. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  35680. if (this._isDirectional) {
  35681. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  35682. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  35683. this._soundPanner.coneOuterGain = this._coneOuterGain;
  35684. if (this._connectedMesh) {
  35685. this._updateDirection();
  35686. }
  35687. else {
  35688. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  35689. }
  35690. }
  35691. }
  35692. }
  35693. if (this._streaming) {
  35694. if (!this._streamingSource) {
  35695. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  35696. this._htmlAudioElement.onended = function () { _this._onended(); };
  35697. this._htmlAudioElement.playbackRate = this._playbackRate;
  35698. }
  35699. this._streamingSource.disconnect();
  35700. this._streamingSource.connect(this._inputAudioNode);
  35701. this._htmlAudioElement.play();
  35702. }
  35703. else {
  35704. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  35705. this._soundSource.buffer = this._audioBuffer;
  35706. this._soundSource.connect(this._inputAudioNode);
  35707. this._soundSource.loop = this.loop;
  35708. this._soundSource.playbackRate.value = this._playbackRate;
  35709. this._soundSource.onended = function () { _this._onended(); };
  35710. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  35711. }
  35712. this._startTime = startTime;
  35713. this.isPlaying = true;
  35714. this.isPaused = false;
  35715. }
  35716. catch (ex) {
  35717. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  35718. }
  35719. }
  35720. };
  35721. Sound.prototype._onended = function () {
  35722. this.isPlaying = false;
  35723. if (this.onended) {
  35724. this.onended();
  35725. }
  35726. };
  35727. /**
  35728. * Stop the sound
  35729. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  35730. */
  35731. Sound.prototype.stop = function (time) {
  35732. if (this.isPlaying) {
  35733. if (this._streaming) {
  35734. this._htmlAudioElement.pause();
  35735. // Test needed for Firefox or it will generate an Invalid State Error
  35736. if (this._htmlAudioElement.currentTime > 0) {
  35737. this._htmlAudioElement.currentTime = 0;
  35738. }
  35739. }
  35740. else {
  35741. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  35742. this._soundSource.stop(stopTime);
  35743. if (!this.isPaused) {
  35744. this._startOffset = 0;
  35745. }
  35746. }
  35747. this.isPlaying = false;
  35748. }
  35749. };
  35750. Sound.prototype.pause = function () {
  35751. if (this.isPlaying) {
  35752. this.isPaused = true;
  35753. if (this._streaming) {
  35754. this._htmlAudioElement.pause();
  35755. }
  35756. else {
  35757. this.stop(0);
  35758. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  35759. }
  35760. }
  35761. };
  35762. Sound.prototype.setVolume = function (newVolume, time) {
  35763. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35764. if (time) {
  35765. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  35766. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  35767. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  35768. }
  35769. else {
  35770. this._soundGain.gain.value = newVolume;
  35771. }
  35772. }
  35773. this._volume = newVolume;
  35774. };
  35775. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  35776. this._playbackRate = newPlaybackRate;
  35777. if (this.isPlaying) {
  35778. if (this._streaming) {
  35779. this._htmlAudioElement.playbackRate = this._playbackRate;
  35780. }
  35781. else {
  35782. this._soundSource.playbackRate.value = this._playbackRate;
  35783. }
  35784. }
  35785. };
  35786. Sound.prototype.getVolume = function () {
  35787. return this._volume;
  35788. };
  35789. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  35790. var _this = this;
  35791. if (this._connectedMesh) {
  35792. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  35793. this._registerFunc = null;
  35794. }
  35795. this._connectedMesh = meshToConnectTo;
  35796. if (!this.spatialSound) {
  35797. this.spatialSound = true;
  35798. this._createSpatialParameters();
  35799. if (this.isPlaying && this.loop) {
  35800. this.stop();
  35801. this.play();
  35802. }
  35803. }
  35804. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  35805. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  35806. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  35807. };
  35808. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  35809. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  35810. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  35811. this._updateDirection();
  35812. }
  35813. };
  35814. Sound.prototype.clone = function () {
  35815. var _this = this;
  35816. if (!this._streaming) {
  35817. var setBufferAndRun = function () {
  35818. if (_this._isReadyToPlay) {
  35819. clonedSound._audioBuffer = _this.getAudioBuffer();
  35820. clonedSound._isReadyToPlay = true;
  35821. if (clonedSound.autoplay) {
  35822. clonedSound.play();
  35823. }
  35824. }
  35825. else {
  35826. window.setTimeout(setBufferAndRun, 300);
  35827. }
  35828. };
  35829. var currentOptions = {
  35830. autoplay: this.autoplay, loop: this.loop,
  35831. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  35832. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  35833. refDistance: this.refDistance, distanceModel: this.distanceModel
  35834. };
  35835. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  35836. if (this.useCustomAttenuation) {
  35837. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  35838. }
  35839. clonedSound.setPosition(this._position);
  35840. clonedSound.setPlaybackRate(this._playbackRate);
  35841. setBufferAndRun();
  35842. return clonedSound;
  35843. }
  35844. else {
  35845. return null;
  35846. }
  35847. };
  35848. Sound.prototype.getAudioBuffer = function () {
  35849. return this._audioBuffer;
  35850. };
  35851. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  35852. var soundName = parsedSound.name;
  35853. var soundUrl;
  35854. if (parsedSound.url) {
  35855. soundUrl = rootUrl + parsedSound.url;
  35856. }
  35857. else {
  35858. soundUrl = rootUrl + soundName;
  35859. }
  35860. var options = {
  35861. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  35862. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  35863. rolloffFactor: parsedSound.rolloffFactor,
  35864. refDistance: parsedSound.refDistance,
  35865. distanceModel: parsedSound.distanceModel,
  35866. playbackRate: parsedSound.playbackRate
  35867. };
  35868. var newSound;
  35869. if (!sourceSound) {
  35870. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  35871. scene._addPendingData(newSound);
  35872. }
  35873. else {
  35874. var setBufferAndRun = function () {
  35875. if (sourceSound._isReadyToPlay) {
  35876. newSound._audioBuffer = sourceSound.getAudioBuffer();
  35877. newSound._isReadyToPlay = true;
  35878. if (newSound.autoplay) {
  35879. newSound.play();
  35880. }
  35881. }
  35882. else {
  35883. window.setTimeout(setBufferAndRun, 300);
  35884. }
  35885. };
  35886. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  35887. setBufferAndRun();
  35888. }
  35889. if (parsedSound.position) {
  35890. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  35891. newSound.setPosition(soundPosition);
  35892. }
  35893. if (parsedSound.isDirectional) {
  35894. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  35895. if (parsedSound.localDirectionToMesh) {
  35896. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  35897. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  35898. }
  35899. }
  35900. if (parsedSound.connectedMeshId) {
  35901. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  35902. if (connectedMesh) {
  35903. newSound.attachToMesh(connectedMesh);
  35904. }
  35905. }
  35906. return newSound;
  35907. };
  35908. return Sound;
  35909. })();
  35910. BABYLON.Sound = Sound;
  35911. })(BABYLON || (BABYLON = {}));
  35912. var BABYLON;
  35913. (function (BABYLON) {
  35914. var SoundTrack = (function () {
  35915. function SoundTrack(scene, options) {
  35916. this.id = -1;
  35917. this._isMainTrack = false;
  35918. this._isInitialized = false;
  35919. this._scene = scene;
  35920. this.soundCollection = new Array();
  35921. this._options = options;
  35922. if (!this._isMainTrack) {
  35923. this._scene.soundTracks.push(this);
  35924. this.id = this._scene.soundTracks.length - 1;
  35925. }
  35926. }
  35927. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  35928. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35929. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  35930. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  35931. if (this._options) {
  35932. if (this._options.volume) {
  35933. this._outputAudioNode.gain.value = this._options.volume;
  35934. }
  35935. if (this._options.mainTrack) {
  35936. this._isMainTrack = this._options.mainTrack;
  35937. }
  35938. }
  35939. this._isInitialized = true;
  35940. }
  35941. };
  35942. SoundTrack.prototype.dispose = function () {
  35943. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35944. if (this._connectedAnalyser) {
  35945. this._connectedAnalyser.stopDebugCanvas();
  35946. }
  35947. while (this.soundCollection.length) {
  35948. this.soundCollection[0].dispose();
  35949. }
  35950. if (this._outputAudioNode) {
  35951. this._outputAudioNode.disconnect();
  35952. }
  35953. this._outputAudioNode = null;
  35954. }
  35955. };
  35956. SoundTrack.prototype.AddSound = function (sound) {
  35957. if (!this._isInitialized) {
  35958. this._initializeSoundTrackAudioGraph();
  35959. }
  35960. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35961. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  35962. }
  35963. if (sound.soundTrackId) {
  35964. if (sound.soundTrackId === -1) {
  35965. this._scene.mainSoundTrack.RemoveSound(sound);
  35966. }
  35967. else {
  35968. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  35969. }
  35970. }
  35971. this.soundCollection.push(sound);
  35972. sound.soundTrackId = this.id;
  35973. };
  35974. SoundTrack.prototype.RemoveSound = function (sound) {
  35975. var index = this.soundCollection.indexOf(sound);
  35976. if (index !== -1) {
  35977. this.soundCollection.splice(index, 1);
  35978. }
  35979. };
  35980. SoundTrack.prototype.setVolume = function (newVolume) {
  35981. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35982. this._outputAudioNode.gain.value = newVolume;
  35983. }
  35984. };
  35985. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  35986. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35987. for (var i = 0; i < this.soundCollection.length; i++) {
  35988. this.soundCollection[i].switchPanningModelToHRTF();
  35989. }
  35990. }
  35991. };
  35992. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  35993. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35994. for (var i = 0; i < this.soundCollection.length; i++) {
  35995. this.soundCollection[i].switchPanningModelToEqualPower();
  35996. }
  35997. }
  35998. };
  35999. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  36000. if (this._connectedAnalyser) {
  36001. this._connectedAnalyser.stopDebugCanvas();
  36002. }
  36003. this._connectedAnalyser = analyser;
  36004. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36005. this._outputAudioNode.disconnect();
  36006. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  36007. }
  36008. };
  36009. return SoundTrack;
  36010. })();
  36011. BABYLON.SoundTrack = SoundTrack;
  36012. })(BABYLON || (BABYLON = {}));
  36013. var BABYLON;
  36014. (function (BABYLON) {
  36015. var DepthRenderer = (function () {
  36016. function DepthRenderer(scene, type) {
  36017. var _this = this;
  36018. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  36019. this._viewMatrix = BABYLON.Matrix.Zero();
  36020. this._projectionMatrix = BABYLON.Matrix.Zero();
  36021. this._transformMatrix = BABYLON.Matrix.Zero();
  36022. this._worldViewProjection = BABYLON.Matrix.Zero();
  36023. this._scene = scene;
  36024. var engine = scene.getEngine();
  36025. // Render target
  36026. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  36027. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36028. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36029. this._depthMap.refreshRate = 1;
  36030. this._depthMap.renderParticles = false;
  36031. this._depthMap.renderList = null;
  36032. // set default depth value to 1.0 (far away)
  36033. this._depthMap.onClear = function (engine) {
  36034. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  36035. };
  36036. // Custom render function
  36037. var renderSubMesh = function (subMesh) {
  36038. var mesh = subMesh.getRenderingMesh();
  36039. var scene = _this._scene;
  36040. var engine = scene.getEngine();
  36041. // Culling
  36042. engine.setState(subMesh.getMaterial().backFaceCulling);
  36043. // Managing instances
  36044. var batch = mesh._getInstancesRenderList(subMesh._id);
  36045. if (batch.mustReturn) {
  36046. return;
  36047. }
  36048. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  36049. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  36050. engine.enableEffect(_this._effect);
  36051. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  36052. var material = subMesh.getMaterial();
  36053. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  36054. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  36055. // Alpha test
  36056. if (material && material.needAlphaTesting()) {
  36057. var alphaTexture = material.getAlphaTestTexture();
  36058. _this._effect.setTexture("diffuseSampler", alphaTexture);
  36059. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  36060. }
  36061. // Bones
  36062. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  36063. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  36064. }
  36065. // Draw
  36066. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  36067. }
  36068. };
  36069. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  36070. var index;
  36071. for (index = 0; index < opaqueSubMeshes.length; index++) {
  36072. renderSubMesh(opaqueSubMeshes.data[index]);
  36073. }
  36074. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  36075. renderSubMesh(alphaTestSubMeshes.data[index]);
  36076. }
  36077. };
  36078. }
  36079. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  36080. var defines = [];
  36081. var attribs = [BABYLON.VertexBuffer.PositionKind];
  36082. var mesh = subMesh.getMesh();
  36083. var scene = mesh.getScene();
  36084. var material = subMesh.getMaterial();
  36085. // Alpha test
  36086. if (material && material.needAlphaTesting()) {
  36087. defines.push("#define ALPHATEST");
  36088. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36089. attribs.push(BABYLON.VertexBuffer.UVKind);
  36090. defines.push("#define UV1");
  36091. }
  36092. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36093. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  36094. defines.push("#define UV2");
  36095. }
  36096. }
  36097. // Bones
  36098. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  36099. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  36100. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  36101. if (mesh.numBoneInfluencers > 4) {
  36102. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  36103. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  36104. }
  36105. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  36106. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  36107. }
  36108. else {
  36109. defines.push("#define NUM_BONE_INFLUENCERS 0");
  36110. }
  36111. // Instances
  36112. if (useInstances) {
  36113. defines.push("#define INSTANCES");
  36114. attribs.push("world0");
  36115. attribs.push("world1");
  36116. attribs.push("world2");
  36117. attribs.push("world3");
  36118. }
  36119. // Get correct effect
  36120. var join = defines.join("\n");
  36121. if (this._cachedDefines !== join) {
  36122. this._cachedDefines = join;
  36123. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  36124. }
  36125. return this._effect.isReady();
  36126. };
  36127. DepthRenderer.prototype.getDepthMap = function () {
  36128. return this._depthMap;
  36129. };
  36130. // Methods
  36131. DepthRenderer.prototype.dispose = function () {
  36132. this._depthMap.dispose();
  36133. };
  36134. return DepthRenderer;
  36135. })();
  36136. BABYLON.DepthRenderer = DepthRenderer;
  36137. })(BABYLON || (BABYLON = {}));
  36138. var BABYLON;
  36139. (function (BABYLON) {
  36140. var SSAORenderingPipeline = (function (_super) {
  36141. __extends(SSAORenderingPipeline, _super);
  36142. /**
  36143. * @constructor
  36144. * @param {string} name - The rendering pipeline name
  36145. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  36146. * @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 }
  36147. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  36148. */
  36149. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  36150. var _this = this;
  36151. _super.call(this, scene.getEngine(), name);
  36152. // Members
  36153. /**
  36154. * The PassPostProcess id in the pipeline that contains the original scene color
  36155. * @type {string}
  36156. */
  36157. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  36158. /**
  36159. * The SSAO PostProcess id in the pipeline
  36160. * @type {string}
  36161. */
  36162. this.SSAORenderEffect = "SSAORenderEffect";
  36163. /**
  36164. * The horizontal blur PostProcess id in the pipeline
  36165. * @type {string}
  36166. */
  36167. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  36168. /**
  36169. * The vertical blur PostProcess id in the pipeline
  36170. * @type {string}
  36171. */
  36172. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  36173. /**
  36174. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  36175. * @type {string}
  36176. */
  36177. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  36178. /**
  36179. * The output strength of the SSAO post-process. Default value is 1.0.
  36180. * @type {number}
  36181. */
  36182. this.totalStrength = 1.0;
  36183. /**
  36184. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  36185. * @type {number}
  36186. */
  36187. this.radius = 0.0001;
  36188. /**
  36189. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  36190. * Must not be equal to fallOff and superior to fallOff.
  36191. * Default value is 0.975
  36192. * @type {number}
  36193. */
  36194. this.area = 0.0075;
  36195. /**
  36196. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  36197. * Must not be equal to area and inferior to area.
  36198. * Default value is 0.0
  36199. * @type {number}
  36200. */
  36201. this.fallOff = 0.000001;
  36202. /**
  36203. * The base color of the SSAO post-process
  36204. * The final result is "base + ssao" between [0, 1]
  36205. * @type {number}
  36206. */
  36207. this.base = 0.5;
  36208. this._firstUpdate = true;
  36209. this._scene = scene;
  36210. // Set up assets
  36211. this._createRandomTexture();
  36212. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  36213. var ssaoRatio = ratio.ssaoRatio || ratio;
  36214. var combineRatio = ratio.combineRatio || ratio;
  36215. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  36216. this._createSSAOPostProcess(ssaoRatio);
  36217. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(1.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  36218. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 1.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  36219. this._createSSAOCombinePostProcess(combineRatio);
  36220. // Set up pipeline
  36221. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  36222. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  36223. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  36224. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  36225. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  36226. // Finish
  36227. scene.postProcessRenderPipelineManager.addPipeline(this);
  36228. if (cameras)
  36229. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  36230. }
  36231. // Public Methods
  36232. /**
  36233. * Returns the horizontal blur PostProcess
  36234. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  36235. */
  36236. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  36237. return this._blurHPostProcess;
  36238. };
  36239. /**
  36240. * Returns the vertical blur PostProcess
  36241. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  36242. */
  36243. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  36244. return this._blurVPostProcess;
  36245. };
  36246. /**
  36247. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  36248. */
  36249. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  36250. if (disableDepthRender === void 0) { disableDepthRender = false; }
  36251. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  36252. this._originalColorPostProcess = undefined;
  36253. this._ssaoPostProcess = undefined;
  36254. this._blurHPostProcess = undefined;
  36255. this._blurVPostProcess = undefined;
  36256. this._ssaoCombinePostProcess = undefined;
  36257. this._randomTexture.dispose();
  36258. if (disableDepthRender)
  36259. this._scene.disableDepthRenderer();
  36260. };
  36261. // Private Methods
  36262. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  36263. var _this = this;
  36264. var numSamples = 16;
  36265. var sampleSphere = [
  36266. 0.5381, 0.1856, -0.4319,
  36267. 0.1379, 0.2486, 0.4430,
  36268. 0.3371, 0.5679, -0.0057,
  36269. -0.6999, -0.0451, -0.0019,
  36270. 0.0689, -0.1598, -0.8547,
  36271. 0.0560, 0.0069, -0.1843,
  36272. -0.0146, 0.1402, 0.0762,
  36273. 0.0100, -0.1924, -0.0344,
  36274. -0.3577, -0.5301, -0.4358,
  36275. -0.3169, 0.1063, 0.0158,
  36276. 0.0103, -0.5869, 0.0046,
  36277. -0.0897, -0.4940, 0.3287,
  36278. 0.7119, -0.0154, -0.0918,
  36279. -0.0533, 0.0596, -0.5411,
  36280. 0.0352, -0.0631, 0.5460,
  36281. -0.4776, 0.2847, -0.0271
  36282. ];
  36283. var samplesFactor = 1.0 / numSamples;
  36284. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  36285. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  36286. "area", "fallOff", "base"
  36287. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples);
  36288. this._ssaoPostProcess.onApply = function (effect) {
  36289. if (_this._firstUpdate) {
  36290. effect.setArray3("sampleSphere", sampleSphere);
  36291. effect.setFloat("samplesFactor", samplesFactor);
  36292. effect.setFloat("randTextureTiles", 4.0);
  36293. _this._firstUpdate = false;
  36294. }
  36295. effect.setFloat("totalStrength", _this.totalStrength);
  36296. effect.setFloat("radius", _this.radius);
  36297. effect.setFloat("area", _this.area);
  36298. effect.setFloat("fallOff", _this.fallOff);
  36299. effect.setFloat("base", _this.base);
  36300. effect.setTexture("textureSampler", _this._depthTexture);
  36301. effect.setTexture("randomSampler", _this._randomTexture);
  36302. };
  36303. };
  36304. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  36305. var _this = this;
  36306. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  36307. this._ssaoCombinePostProcess.onApply = function (effect) {
  36308. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  36309. };
  36310. };
  36311. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  36312. var size = 512;
  36313. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  36314. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  36315. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  36316. var context = this._randomTexture.getContext();
  36317. var rand = function (min, max) {
  36318. return Math.random() * (max - min) + min;
  36319. };
  36320. var randVector = BABYLON.Vector3.Zero();
  36321. for (var x = 0; x < size; x++) {
  36322. for (var y = 0; y < size; y++) {
  36323. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  36324. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  36325. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  36326. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  36327. context.fillRect(x, y, 1, 1);
  36328. }
  36329. }
  36330. this._randomTexture.update(false);
  36331. };
  36332. return SSAORenderingPipeline;
  36333. })(BABYLON.PostProcessRenderPipeline);
  36334. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  36335. })(BABYLON || (BABYLON = {}));
  36336. var BABYLON;
  36337. (function (BABYLON) {
  36338. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  36339. var VolumetricLightScatteringPostProcess = (function (_super) {
  36340. __extends(VolumetricLightScatteringPostProcess, _super);
  36341. /**
  36342. * @constructor
  36343. * @param {string} name - The post-process name
  36344. * @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)
  36345. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  36346. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  36347. * @param {number} samples - The post-process quality, default 100
  36348. * @param {number} samplingMode - The post-process filtering mode
  36349. * @param {BABYLON.Engine} engine - The babylon engine
  36350. * @param {boolean} reusable - If the post-process is reusable
  36351. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  36352. */
  36353. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  36354. var _this = this;
  36355. if (samples === void 0) { samples = 100; }
  36356. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  36357. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  36358. this._screenCoordinates = BABYLON.Vector2.Zero();
  36359. /**
  36360. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  36361. * @type {boolean}
  36362. */
  36363. this.useCustomMeshPosition = false;
  36364. /**
  36365. * If the post-process should inverse the light scattering direction
  36366. * @type {boolean}
  36367. */
  36368. this.invert = true;
  36369. /**
  36370. * Set to true to use the diffuseColor instead of the diffuseTexture
  36371. * @type {boolean}
  36372. */
  36373. this.useDiffuseColor = false;
  36374. /**
  36375. * Array containing the excluded meshes not rendered in the internal pass
  36376. */
  36377. this.excludedMeshes = new Array();
  36378. /**
  36379. * Controls the overall intensity of the post-process
  36380. * @type {number}
  36381. */
  36382. this.exposure = 0.3;
  36383. /**
  36384. * Dissipates each sample's contribution in range [0, 1]
  36385. * @type {number}
  36386. */
  36387. this.decay = 0.96815;
  36388. /**
  36389. * Controls the overall intensity of each sample
  36390. * @type {number}
  36391. */
  36392. this.weight = 0.58767;
  36393. /**
  36394. * Controls the density of each sample
  36395. * @type {number}
  36396. */
  36397. this.density = 0.926;
  36398. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  36399. var engine = scene.getEngine();
  36400. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  36401. // Configure mesh
  36402. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  36403. // Configure
  36404. this._createPass(scene, ratio.passRatio || ratio);
  36405. this.onActivate = function (camera) {
  36406. if (!_this.isSupported) {
  36407. _this.dispose(camera);
  36408. }
  36409. _this.onActivate = null;
  36410. };
  36411. this.onApply = function (effect) {
  36412. _this._updateMeshScreenCoordinates(scene);
  36413. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  36414. effect.setFloat("exposure", _this.exposure);
  36415. effect.setFloat("decay", _this.decay);
  36416. effect.setFloat("weight", _this.weight);
  36417. effect.setFloat("density", _this.density);
  36418. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  36419. };
  36420. }
  36421. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  36422. var mesh = subMesh.getMesh();
  36423. var defines = [];
  36424. var attribs = [BABYLON.VertexBuffer.PositionKind];
  36425. var material = subMesh.getMaterial();
  36426. var needUV = false;
  36427. // Render this.mesh as default
  36428. if (mesh === this.mesh) {
  36429. if (this.useDiffuseColor) {
  36430. defines.push("#define DIFFUSE_COLOR_RENDER");
  36431. }
  36432. else if (material) {
  36433. if (material.diffuseTexture !== undefined) {
  36434. defines.push("#define BASIC_RENDER");
  36435. }
  36436. else {
  36437. defines.push("#define DIFFUSE_COLOR_RENDER");
  36438. }
  36439. }
  36440. defines.push("#define NEED_UV");
  36441. needUV = true;
  36442. }
  36443. // Alpha test
  36444. if (material) {
  36445. if (material.needAlphaTesting()) {
  36446. defines.push("#define ALPHATEST");
  36447. }
  36448. if (material.opacityTexture !== undefined) {
  36449. defines.push("#define OPACITY");
  36450. if (material.opacityTexture.getAlphaFromRGB) {
  36451. defines.push("#define OPACITYRGB");
  36452. }
  36453. if (!needUV) {
  36454. defines.push("#define NEED_UV");
  36455. }
  36456. }
  36457. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36458. attribs.push(BABYLON.VertexBuffer.UVKind);
  36459. defines.push("#define UV1");
  36460. }
  36461. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36462. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  36463. defines.push("#define UV2");
  36464. }
  36465. }
  36466. // Bones
  36467. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  36468. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  36469. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  36470. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  36471. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  36472. }
  36473. else {
  36474. defines.push("#define NUM_BONE_INFLUENCERS 0");
  36475. }
  36476. // Instances
  36477. if (useInstances) {
  36478. defines.push("#define INSTANCES");
  36479. attribs.push("world0");
  36480. attribs.push("world1");
  36481. attribs.push("world2");
  36482. attribs.push("world3");
  36483. }
  36484. // Get correct effect
  36485. var join = defines.join("\n");
  36486. if (this._cachedDefines !== join) {
  36487. this._cachedDefines = join;
  36488. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "opacityLevel", "color"], ["diffuseSampler", "opacitySampler"], join);
  36489. }
  36490. return this._volumetricLightScatteringPass.isReady();
  36491. };
  36492. /**
  36493. * Sets the new light position for light scattering effect
  36494. * @param {BABYLON.Vector3} The new custom light position
  36495. */
  36496. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  36497. this._customMeshPosition = position;
  36498. };
  36499. /**
  36500. * Returns the light position for light scattering effect
  36501. * @return {BABYLON.Vector3} The custom light position
  36502. */
  36503. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  36504. return this._customMeshPosition;
  36505. };
  36506. /**
  36507. * Disposes the internal assets and detaches the post-process from the camera
  36508. */
  36509. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  36510. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  36511. if (rttIndex !== -1) {
  36512. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  36513. }
  36514. this._volumetricLightScatteringRTT.dispose();
  36515. _super.prototype.dispose.call(this, camera);
  36516. };
  36517. /**
  36518. * Returns the render target texture used by the post-process
  36519. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  36520. */
  36521. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  36522. return this._volumetricLightScatteringRTT;
  36523. };
  36524. // Private methods
  36525. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  36526. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  36527. return true;
  36528. }
  36529. return false;
  36530. };
  36531. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  36532. var _this = this;
  36533. var engine = scene.getEngine();
  36534. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  36535. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36536. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36537. this._volumetricLightScatteringRTT.renderList = null;
  36538. this._volumetricLightScatteringRTT.renderParticles = false;
  36539. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  36540. // Custom render function for submeshes
  36541. var renderSubMesh = function (subMesh) {
  36542. var mesh = subMesh.getRenderingMesh();
  36543. if (_this._meshExcluded(mesh)) {
  36544. return;
  36545. }
  36546. var scene = mesh.getScene();
  36547. var engine = scene.getEngine();
  36548. // Culling
  36549. engine.setState(subMesh.getMaterial().backFaceCulling);
  36550. // Managing instances
  36551. var batch = mesh._getInstancesRenderList(subMesh._id);
  36552. if (batch.mustReturn) {
  36553. return;
  36554. }
  36555. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  36556. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  36557. engine.enableEffect(_this._volumetricLightScatteringPass);
  36558. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  36559. var material = subMesh.getMaterial();
  36560. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  36561. // Alpha test
  36562. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  36563. var alphaTexture = material.getAlphaTestTexture();
  36564. if ((_this.useDiffuseColor || alphaTexture === undefined) && mesh === _this.mesh) {
  36565. _this._volumetricLightScatteringPass.setColor3("color", material.diffuseColor);
  36566. }
  36567. if (material.needAlphaTesting() || (mesh === _this.mesh && alphaTexture && !_this.useDiffuseColor)) {
  36568. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  36569. if (alphaTexture) {
  36570. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  36571. }
  36572. }
  36573. if (material.opacityTexture !== undefined) {
  36574. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  36575. _this._volumetricLightScatteringPass.setFloat("opacityLevel", material.opacityTexture.level);
  36576. }
  36577. }
  36578. // Bones
  36579. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  36580. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  36581. }
  36582. // Draw
  36583. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  36584. }
  36585. };
  36586. // Render target texture callbacks
  36587. var savedSceneClearColor;
  36588. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  36589. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  36590. savedSceneClearColor = scene.clearColor;
  36591. scene.clearColor = sceneClearColor;
  36592. };
  36593. this._volumetricLightScatteringRTT.onAfterRender = function () {
  36594. scene.clearColor = savedSceneClearColor;
  36595. };
  36596. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  36597. var engine = scene.getEngine();
  36598. var index;
  36599. for (index = 0; index < opaqueSubMeshes.length; index++) {
  36600. renderSubMesh(opaqueSubMeshes.data[index]);
  36601. }
  36602. engine.setAlphaTesting(true);
  36603. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  36604. renderSubMesh(alphaTestSubMeshes.data[index]);
  36605. }
  36606. engine.setAlphaTesting(false);
  36607. if (transparentSubMeshes.length) {
  36608. // Sort sub meshes
  36609. for (index = 0; index < transparentSubMeshes.length; index++) {
  36610. var submesh = transparentSubMeshes.data[index];
  36611. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  36612. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  36613. }
  36614. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  36615. sortedArray.sort(function (a, b) {
  36616. // Alpha index first
  36617. if (a._alphaIndex > b._alphaIndex) {
  36618. return 1;
  36619. }
  36620. if (a._alphaIndex < b._alphaIndex) {
  36621. return -1;
  36622. }
  36623. // Then distance to camera
  36624. if (a._distanceToCamera < b._distanceToCamera) {
  36625. return 1;
  36626. }
  36627. if (a._distanceToCamera > b._distanceToCamera) {
  36628. return -1;
  36629. }
  36630. return 0;
  36631. });
  36632. // Render sub meshes
  36633. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  36634. for (index = 0; index < sortedArray.length; index++) {
  36635. renderSubMesh(sortedArray[index]);
  36636. }
  36637. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  36638. }
  36639. };
  36640. };
  36641. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  36642. var transform = scene.getTransformMatrix();
  36643. var meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  36644. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  36645. this._screenCoordinates.x = pos.x / this._viewPort.width;
  36646. this._screenCoordinates.y = pos.y / this._viewPort.height;
  36647. if (this.invert)
  36648. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  36649. };
  36650. // Static methods
  36651. /**
  36652. * Creates a default mesh for the Volumeric Light Scattering post-process
  36653. * @param {string} The mesh name
  36654. * @param {BABYLON.Scene} The scene where to create the mesh
  36655. * @return {BABYLON.Mesh} the default mesh
  36656. */
  36657. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  36658. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  36659. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  36660. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  36661. return mesh;
  36662. };
  36663. return VolumetricLightScatteringPostProcess;
  36664. })(BABYLON.PostProcess);
  36665. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  36666. })(BABYLON || (BABYLON = {}));
  36667. // BABYLON.JS Chromatic Aberration GLSL Shader
  36668. // Author: Olivier Guyot
  36669. // Separates very slightly R, G and B colors on the edges of the screen
  36670. // Inspired by Francois Tarlier & Martins Upitis
  36671. var BABYLON;
  36672. (function (BABYLON) {
  36673. var LensRenderingPipeline = (function (_super) {
  36674. __extends(LensRenderingPipeline, _super);
  36675. /**
  36676. * @constructor
  36677. *
  36678. * Effect parameters are as follow:
  36679. * {
  36680. * chromatic_aberration: number; // from 0 to x (1 for realism)
  36681. * edge_blur: number; // from 0 to x (1 for realism)
  36682. * distortion: number; // from 0 to x (1 for realism)
  36683. * grain_amount: number; // from 0 to 1
  36684. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  36685. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  36686. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  36687. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  36688. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  36689. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  36690. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  36691. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  36692. * }
  36693. * Note: if an effect parameter is unset, effect is disabled
  36694. *
  36695. * @param {string} name - The rendering pipeline name
  36696. * @param {object} parameters - An object containing all parameters (see above)
  36697. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  36698. * @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)
  36699. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  36700. */
  36701. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  36702. var _this = this;
  36703. if (ratio === void 0) { ratio = 1.0; }
  36704. _super.call(this, scene.getEngine(), name);
  36705. // Lens effects can be of the following:
  36706. // - chromatic aberration (slight shift of RGB colors)
  36707. // - blur on the edge of the lens
  36708. // - lens distortion
  36709. // - depth-of-field blur & highlights enhancing
  36710. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  36711. // - grain effect (noise or custom texture)
  36712. // Two additional texture samplers are needed:
  36713. // - depth map (for depth-of-field)
  36714. // - grain texture
  36715. /**
  36716. * The chromatic aberration PostProcess id in the pipeline
  36717. * @type {string}
  36718. */
  36719. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  36720. /**
  36721. * The highlights enhancing PostProcess id in the pipeline
  36722. * @type {string}
  36723. */
  36724. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  36725. /**
  36726. * The depth-of-field PostProcess id in the pipeline
  36727. * @type {string}
  36728. */
  36729. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  36730. this._scene = scene;
  36731. // Fetch texture samplers
  36732. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  36733. if (parameters.grain_texture) {
  36734. this._grainTexture = parameters.grain_texture;
  36735. }
  36736. else {
  36737. this._createGrainTexture();
  36738. }
  36739. // save parameters
  36740. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  36741. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  36742. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  36743. this._distortion = parameters.distortion ? parameters.distortion : 0;
  36744. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  36745. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  36746. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  36747. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  36748. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  36749. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  36750. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  36751. // Create effects
  36752. this._createChromaticAberrationPostProcess(ratio);
  36753. this._createHighlightsPostProcess(ratio);
  36754. this._createDepthOfFieldPostProcess(ratio / 4);
  36755. // Set up pipeline
  36756. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  36757. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  36758. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  36759. if (this._highlightsGain === -1) {
  36760. this._disableEffect(this.HighlightsEnhancingEffect, null);
  36761. }
  36762. // Finish
  36763. scene.postProcessRenderPipelineManager.addPipeline(this);
  36764. if (cameras) {
  36765. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  36766. }
  36767. }
  36768. // public methods (self explanatory)
  36769. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  36770. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  36771. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  36772. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  36773. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  36774. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  36775. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  36776. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  36777. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  36778. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  36779. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  36780. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  36781. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  36782. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  36783. };
  36784. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  36785. this._highlightsPostProcess.updateEffect();
  36786. };
  36787. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  36788. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  36789. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  36790. this._highlightsGain = amount;
  36791. };
  36792. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  36793. if (this._highlightsGain === -1) {
  36794. this._highlightsGain = 1.0;
  36795. }
  36796. this._highlightsThreshold = amount;
  36797. };
  36798. LensRenderingPipeline.prototype.disableHighlights = function () {
  36799. this._highlightsGain = -1;
  36800. };
  36801. /**
  36802. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  36803. */
  36804. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  36805. if (disableDepthRender === void 0) { disableDepthRender = false; }
  36806. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  36807. this._chromaticAberrationPostProcess = undefined;
  36808. this._highlightsPostProcess = undefined;
  36809. this._depthOfFieldPostProcess = undefined;
  36810. this._grainTexture.dispose();
  36811. if (disableDepthRender)
  36812. this._scene.disableDepthRenderer();
  36813. };
  36814. // colors shifting and distortion
  36815. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  36816. var _this = this;
  36817. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  36818. [], // samplers
  36819. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  36820. this._chromaticAberrationPostProcess.onApply = function (effect) {
  36821. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  36822. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  36823. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  36824. };
  36825. };
  36826. // highlights enhancing
  36827. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  36828. var _this = this;
  36829. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  36830. [], // samplers
  36831. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  36832. this._highlightsPostProcess.onApply = function (effect) {
  36833. effect.setFloat('gain', _this._highlightsGain);
  36834. effect.setFloat('threshold', _this._highlightsThreshold);
  36835. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  36836. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  36837. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  36838. };
  36839. };
  36840. // colors shifting and distortion
  36841. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  36842. var _this = this;
  36843. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  36844. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  36845. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  36846. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  36847. this._depthOfFieldPostProcess.onApply = function (effect) {
  36848. effect.setTexture("depthSampler", _this._depthTexture);
  36849. effect.setTexture("grainSampler", _this._grainTexture);
  36850. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  36851. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  36852. effect.setFloat('grain_amount', _this._grainAmount);
  36853. effect.setBool('blur_noise', _this._blurNoise);
  36854. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  36855. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  36856. effect.setFloat('distortion', _this._distortion);
  36857. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  36858. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  36859. effect.setFloat('aperture', _this._dofAperture);
  36860. effect.setFloat('darken', _this._dofDarken);
  36861. effect.setFloat('edge_blur', _this._edgeBlur);
  36862. effect.setBool('highlights', (_this._highlightsGain !== -1));
  36863. effect.setFloat('near', _this._scene.activeCamera.minZ);
  36864. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  36865. };
  36866. };
  36867. // creates a black and white random noise texture, 512x512
  36868. LensRenderingPipeline.prototype._createGrainTexture = function () {
  36869. var size = 512;
  36870. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  36871. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  36872. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  36873. var context = this._grainTexture.getContext();
  36874. var rand = function (min, max) {
  36875. return Math.random() * (max - min) + min;
  36876. };
  36877. var value;
  36878. for (var x = 0; x < size; x++) {
  36879. for (var y = 0; y < size; y++) {
  36880. value = Math.floor(rand(0.42, 0.58) * 255);
  36881. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  36882. context.fillRect(x, y, 1, 1);
  36883. }
  36884. }
  36885. this._grainTexture.update(false);
  36886. };
  36887. return LensRenderingPipeline;
  36888. })(BABYLON.PostProcessRenderPipeline);
  36889. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  36890. })(BABYLON || (BABYLON = {}));
  36891. //
  36892. // This post-process allows the modification of rendered colors by using
  36893. // a 'look-up table' (LUT). This effect is also called Color Grading.
  36894. //
  36895. // The object needs to be provided an url to a texture containing the color
  36896. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  36897. // Use an image editing software to tweak the LUT to match your needs.
  36898. //
  36899. // For an example of a color LUT, see here:
  36900. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  36901. // For explanations on color grading, see here:
  36902. // http://udn.epicgames.com/Three/ColorGrading.html
  36903. //
  36904. var BABYLON;
  36905. (function (BABYLON) {
  36906. var ColorCorrectionPostProcess = (function (_super) {
  36907. __extends(ColorCorrectionPostProcess, _super);
  36908. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  36909. var _this = this;
  36910. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  36911. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  36912. this._colorTableTexture.anisotropicFilteringLevel = 1;
  36913. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36914. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36915. this.onApply = function (effect) {
  36916. effect.setTexture("colorTable", _this._colorTableTexture);
  36917. };
  36918. }
  36919. return ColorCorrectionPostProcess;
  36920. })(BABYLON.PostProcess);
  36921. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  36922. })(BABYLON || (BABYLON = {}));
  36923. var BABYLON;
  36924. (function (BABYLON) {
  36925. var HDRRenderingPipeline = (function (_super) {
  36926. __extends(HDRRenderingPipeline, _super);
  36927. /**
  36928. * @constructor
  36929. * @param {string} name - The rendering pipeline name
  36930. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  36931. * @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)
  36932. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  36933. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  36934. */
  36935. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  36936. var _this = this;
  36937. if (originalPostProcess === void 0) { originalPostProcess = null; }
  36938. _super.call(this, scene.getEngine(), name);
  36939. /**
  36940. * Public members
  36941. */
  36942. // Gaussian Blur
  36943. /**
  36944. * Gaussian blur coefficient
  36945. * @type {number}
  36946. */
  36947. this.gaussCoeff = 0.3;
  36948. /**
  36949. * Gaussian blur mean
  36950. * @type {number}
  36951. */
  36952. this.gaussMean = 1.0;
  36953. /**
  36954. * Gaussian blur standard deviation
  36955. * @type {number}
  36956. */
  36957. this.gaussStandDev = 0.8;
  36958. /**
  36959. * Gaussian blur multiplier. Multiplies the blur effect
  36960. * @type {number}
  36961. */
  36962. this.gaussMultiplier = 4.0;
  36963. // HDR
  36964. /**
  36965. * Exposure, controls the overall intensity of the pipeline
  36966. * @type {number}
  36967. */
  36968. this.exposure = 1.0;
  36969. /**
  36970. * Minimum luminance that the post-process can output. Luminance is >= 0
  36971. * @type {number}
  36972. */
  36973. this.minimumLuminance = 1.0;
  36974. /**
  36975. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  36976. * @type {number}
  36977. */
  36978. this.maximumLuminance = 1e20;
  36979. /**
  36980. * Increase rate for luminance: eye adaptation speed to dark
  36981. * @type {number}
  36982. */
  36983. this.luminanceIncreaserate = 0.5;
  36984. /**
  36985. * Decrease rate for luminance: eye adaptation speed to bright
  36986. * @type {number}
  36987. */
  36988. this.luminanceDecreaseRate = 0.5;
  36989. // Bright pass
  36990. /**
  36991. * Minimum luminance needed to compute HDR
  36992. * @type {number}
  36993. */
  36994. this.brightThreshold = 0.8;
  36995. this._needUpdate = true;
  36996. this._scene = scene;
  36997. // Bright pass
  36998. this._createBrightPassPostProcess(scene, ratio);
  36999. // Down sample X4
  37000. this._createDownSampleX4PostProcess(scene, ratio);
  37001. // Create gaussian blur post-processes
  37002. this._createGaussianBlurPostProcess(scene, ratio);
  37003. // Texture adder
  37004. this._createTextureAdderPostProcess(scene, ratio);
  37005. // Luminance generator
  37006. this._createLuminanceGeneratorPostProcess(scene);
  37007. // HDR
  37008. this._createHDRPostProcess(scene, ratio);
  37009. // Pass postprocess
  37010. if (originalPostProcess === null) {
  37011. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  37012. }
  37013. else {
  37014. this._originalPostProcess = originalPostProcess;
  37015. }
  37016. // Configure pipeline
  37017. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  37018. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  37019. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  37020. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  37021. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  37022. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  37023. var addDownSamplerPostProcess = function (id) {
  37024. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  37025. };
  37026. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  37027. addDownSamplerPostProcess(i);
  37028. }
  37029. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  37030. // Finish
  37031. scene.postProcessRenderPipelineManager.addPipeline(this);
  37032. if (cameras !== null) {
  37033. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  37034. }
  37035. this.update();
  37036. }
  37037. /**
  37038. * Tells the pipeline to update its post-processes
  37039. */
  37040. HDRRenderingPipeline.prototype.update = function () {
  37041. this._needUpdate = true;
  37042. };
  37043. /**
  37044. * Returns the current calculated luminance
  37045. */
  37046. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  37047. return this._hdrCurrentLuminance;
  37048. };
  37049. /**
  37050. * Returns the currently drawn luminance
  37051. */
  37052. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  37053. return this._hdrOutputLuminance;
  37054. };
  37055. /**
  37056. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  37057. */
  37058. HDRRenderingPipeline.prototype.dispose = function () {
  37059. this._originalPostProcess = undefined;
  37060. this._brightPassPostProcess = undefined;
  37061. this._downSampleX4PostProcess = undefined;
  37062. this._guassianBlurHPostProcess = undefined;
  37063. this._guassianBlurVPostProcess = undefined;
  37064. this._textureAdderPostProcess = undefined;
  37065. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  37066. this._downSamplePostProcesses[i] = undefined;
  37067. }
  37068. this._hdrPostProcess = undefined;
  37069. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  37070. };
  37071. /**
  37072. * Creates the HDR post-process and computes the luminance adaptation
  37073. */
  37074. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  37075. var _this = this;
  37076. var hdrLastLuminance = 0.0;
  37077. this._hdrOutputLuminance = -1.0;
  37078. this._hdrCurrentLuminance = 1.0;
  37079. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  37080. this._hdrPostProcess.onApply = function (effect) {
  37081. if (_this._hdrOutputLuminance < 0.0) {
  37082. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  37083. }
  37084. else {
  37085. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  37086. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  37087. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  37088. }
  37089. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  37090. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  37091. }
  37092. else {
  37093. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  37094. }
  37095. }
  37096. _this._hdrOutputLuminance = BABYLON.MathTools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  37097. hdrLastLuminance += scene.getEngine().getDeltaTime();
  37098. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  37099. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  37100. effect.setFloat("exposure", _this.exposure);
  37101. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  37102. _this._needUpdate = false;
  37103. };
  37104. };
  37105. /**
  37106. * Texture Adder post-process
  37107. */
  37108. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  37109. var _this = this;
  37110. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  37111. this._textureAdderPostProcess.onApply = function (effect) {
  37112. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  37113. };
  37114. };
  37115. /**
  37116. * Down sample X4 post-process
  37117. */
  37118. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  37119. var _this = this;
  37120. var downSampleX4Offsets = new Array(32);
  37121. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  37122. this._downSampleX4PostProcess.onApply = function (effect) {
  37123. if (_this._needUpdate) {
  37124. var id = 0;
  37125. for (var i = -2; i < 2; i++) {
  37126. for (var j = -2; j < 2; j++) {
  37127. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  37128. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  37129. id += 2;
  37130. }
  37131. }
  37132. }
  37133. effect.setArray2("dsOffsets", downSampleX4Offsets);
  37134. };
  37135. };
  37136. /**
  37137. * Bright pass post-process
  37138. */
  37139. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  37140. var _this = this;
  37141. var brightOffsets = new Array(8);
  37142. var brightPassCallback = function (effect) {
  37143. if (_this._needUpdate) {
  37144. var sU = (1.0 / _this._brightPassPostProcess.width);
  37145. var sV = (1.0 / _this._brightPassPostProcess.height);
  37146. brightOffsets[0] = -0.5 * sU;
  37147. brightOffsets[1] = 0.5 * sV;
  37148. brightOffsets[2] = 0.5 * sU;
  37149. brightOffsets[3] = 0.5 * sV;
  37150. brightOffsets[4] = -0.5 * sU;
  37151. brightOffsets[5] = -0.5 * sV;
  37152. brightOffsets[6] = 0.5 * sU;
  37153. brightOffsets[7] = -0.5 * sV;
  37154. }
  37155. effect.setArray2("dsOffsets", brightOffsets);
  37156. effect.setFloat("brightThreshold", _this.brightThreshold);
  37157. };
  37158. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  37159. this._brightPassPostProcess.onApply = brightPassCallback;
  37160. };
  37161. /**
  37162. * Luminance generator. Creates the luminance post-process and down sample post-processes
  37163. */
  37164. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  37165. var _this = this;
  37166. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  37167. var luminanceOffsets = new Array(8);
  37168. var downSampleOffsets = new Array(18);
  37169. var halfDestPixelSize;
  37170. this._downSamplePostProcesses = new Array(lumSteps);
  37171. // Utils for luminance
  37172. var luminanceUpdateSourceOffsets = function (width, height) {
  37173. var sU = (1.0 / width);
  37174. var sV = (1.0 / height);
  37175. luminanceOffsets[0] = -0.5 * sU;
  37176. luminanceOffsets[1] = 0.5 * sV;
  37177. luminanceOffsets[2] = 0.5 * sU;
  37178. luminanceOffsets[3] = 0.5 * sV;
  37179. luminanceOffsets[4] = -0.5 * sU;
  37180. luminanceOffsets[5] = -0.5 * sV;
  37181. luminanceOffsets[6] = 0.5 * sU;
  37182. luminanceOffsets[7] = -0.5 * sV;
  37183. };
  37184. var luminanceUpdateDestOffsets = function (width, height) {
  37185. var id = 0;
  37186. for (var x = -1; x < 2; x++) {
  37187. for (var y = -1; y < 2; y++) {
  37188. downSampleOffsets[id] = (x) / width;
  37189. downSampleOffsets[id + 1] = (y) / height;
  37190. id += 2;
  37191. }
  37192. }
  37193. };
  37194. // Luminance callback
  37195. var luminanceCallback = function (effect) {
  37196. if (_this._needUpdate) {
  37197. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  37198. }
  37199. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  37200. effect.setArray2("lumOffsets", luminanceOffsets);
  37201. };
  37202. // Down sample callbacks
  37203. var downSampleCallback = function (indice) {
  37204. var i = indice;
  37205. return function (effect) {
  37206. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  37207. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  37208. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  37209. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  37210. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  37211. effect.setArray2("dsOffsets", downSampleOffsets);
  37212. };
  37213. };
  37214. var downSampleAfterRenderCallback = function (effect) {
  37215. // Unpack result
  37216. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  37217. 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);
  37218. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  37219. };
  37220. // Create luminance post-process
  37221. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  37222. 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);
  37223. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  37224. // Create down sample post-processes
  37225. for (var i = lumSteps - 2; i >= 0; i--) {
  37226. var length = Math.pow(3, i);
  37227. ratio = { width: length, height: length };
  37228. var defines = "#define DOWN_SAMPLE\n";
  37229. if (i === 0) {
  37230. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  37231. }
  37232. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  37233. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  37234. if (i === 0) {
  37235. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  37236. }
  37237. }
  37238. };
  37239. /**
  37240. * Gaussian blur post-processes. Horizontal and Vertical
  37241. */
  37242. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  37243. var _this = this;
  37244. var blurOffsetsW = new Array(9);
  37245. var blurOffsetsH = new Array(9);
  37246. var blurWeights = new Array(9);
  37247. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  37248. // Utils for gaussian blur
  37249. var calculateBlurOffsets = function (height) {
  37250. var lastOutputDimensions = {
  37251. width: scene.getEngine().getRenderWidth(),
  37252. height: scene.getEngine().getRenderHeight()
  37253. };
  37254. for (var i = 0; i < 9; i++) {
  37255. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  37256. if (height) {
  37257. blurOffsetsH[i] = value;
  37258. }
  37259. else {
  37260. blurOffsetsW[i] = value;
  37261. }
  37262. }
  37263. };
  37264. var calculateWeights = function () {
  37265. var x = 0.0;
  37266. for (var i = 0; i < 9; i++) {
  37267. x = (i - 4.0) / 4.0;
  37268. 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));
  37269. }
  37270. };
  37271. // Callback
  37272. var gaussianBlurCallback = function (height) {
  37273. return function (effect) {
  37274. if (_this._needUpdate) {
  37275. calculateWeights();
  37276. calculateBlurOffsets(height);
  37277. }
  37278. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  37279. effect.setArray("blurWeights", blurWeights);
  37280. effect.setFloat("multiplier", _this.gaussMultiplier);
  37281. };
  37282. };
  37283. // Create horizontal gaussian blur post-processes
  37284. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  37285. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  37286. // Create vertical gaussian blur post-process
  37287. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  37288. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  37289. };
  37290. // Luminance generator
  37291. HDRRenderingPipeline.LUM_STEPS = 6;
  37292. return HDRRenderingPipeline;
  37293. })(BABYLON.PostProcessRenderPipeline);
  37294. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  37295. })(BABYLON || (BABYLON = {}));
  37296. var BABYLON;
  37297. (function (BABYLON) {
  37298. var FaceAdjacencies = (function () {
  37299. function FaceAdjacencies() {
  37300. this.edges = new Array();
  37301. this.edgesConnectedCount = 0;
  37302. }
  37303. return FaceAdjacencies;
  37304. })();
  37305. var EdgesRenderer = (function () {
  37306. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  37307. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  37308. if (epsilon === void 0) { epsilon = 0.95; }
  37309. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  37310. this.edgesWidthScalerForOrthographic = 1000.0;
  37311. this.edgesWidthScalerForPerspective = 50.0;
  37312. this._linesPositions = new Array();
  37313. this._linesNormals = new Array();
  37314. this._linesIndices = new Array();
  37315. this._buffers = new Array();
  37316. this._checkVerticesInsteadOfIndices = false;
  37317. this._source = source;
  37318. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  37319. this._epsilon = epsilon;
  37320. this._prepareRessources();
  37321. this._generateEdgesLines();
  37322. }
  37323. EdgesRenderer.prototype._prepareRessources = function () {
  37324. if (this._lineShader) {
  37325. return;
  37326. }
  37327. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  37328. attributes: ["position", "normal"],
  37329. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  37330. });
  37331. this._lineShader.disableDepthWrite = true;
  37332. this._lineShader.backFaceCulling = false;
  37333. };
  37334. EdgesRenderer.prototype.dispose = function () {
  37335. this._vb0.dispose();
  37336. this._vb1.dispose();
  37337. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  37338. this._lineShader.dispose();
  37339. };
  37340. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  37341. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  37342. return 0;
  37343. }
  37344. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  37345. return 1;
  37346. }
  37347. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  37348. return 2;
  37349. }
  37350. return -1;
  37351. };
  37352. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  37353. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  37354. return 0;
  37355. }
  37356. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  37357. return 1;
  37358. }
  37359. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  37360. return 2;
  37361. }
  37362. return -1;
  37363. };
  37364. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  37365. var needToCreateLine;
  37366. if (edge === undefined) {
  37367. needToCreateLine = true;
  37368. }
  37369. else {
  37370. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  37371. needToCreateLine = dotProduct < this._epsilon;
  37372. }
  37373. if (needToCreateLine) {
  37374. var offset = this._linesPositions.length / 3;
  37375. var normal = p0.subtract(p1);
  37376. normal.normalize();
  37377. // Positions
  37378. this._linesPositions.push(p0.x);
  37379. this._linesPositions.push(p0.y);
  37380. this._linesPositions.push(p0.z);
  37381. this._linesPositions.push(p0.x);
  37382. this._linesPositions.push(p0.y);
  37383. this._linesPositions.push(p0.z);
  37384. this._linesPositions.push(p1.x);
  37385. this._linesPositions.push(p1.y);
  37386. this._linesPositions.push(p1.z);
  37387. this._linesPositions.push(p1.x);
  37388. this._linesPositions.push(p1.y);
  37389. this._linesPositions.push(p1.z);
  37390. // Normals
  37391. this._linesNormals.push(p1.x);
  37392. this._linesNormals.push(p1.y);
  37393. this._linesNormals.push(p1.z);
  37394. this._linesNormals.push(-1);
  37395. this._linesNormals.push(p1.x);
  37396. this._linesNormals.push(p1.y);
  37397. this._linesNormals.push(p1.z);
  37398. this._linesNormals.push(1);
  37399. this._linesNormals.push(p0.x);
  37400. this._linesNormals.push(p0.y);
  37401. this._linesNormals.push(p0.z);
  37402. this._linesNormals.push(-1);
  37403. this._linesNormals.push(p0.x);
  37404. this._linesNormals.push(p0.y);
  37405. this._linesNormals.push(p0.z);
  37406. this._linesNormals.push(1);
  37407. // Indices
  37408. this._linesIndices.push(offset);
  37409. this._linesIndices.push(offset + 1);
  37410. this._linesIndices.push(offset + 2);
  37411. this._linesIndices.push(offset);
  37412. this._linesIndices.push(offset + 2);
  37413. this._linesIndices.push(offset + 3);
  37414. }
  37415. };
  37416. EdgesRenderer.prototype._generateEdgesLines = function () {
  37417. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37418. var indices = this._source.getIndices();
  37419. // First let's find adjacencies
  37420. var adjacencies = new Array();
  37421. var faceNormals = new Array();
  37422. var index;
  37423. var faceAdjacencies;
  37424. // Prepare faces
  37425. for (index = 0; index < indices.length; index += 3) {
  37426. faceAdjacencies = new FaceAdjacencies();
  37427. var p0Index = indices[index];
  37428. var p1Index = indices[index + 1];
  37429. var p2Index = indices[index + 2];
  37430. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  37431. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  37432. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  37433. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  37434. faceNormal.normalize();
  37435. faceNormals.push(faceNormal);
  37436. adjacencies.push(faceAdjacencies);
  37437. }
  37438. // Scan
  37439. for (index = 0; index < adjacencies.length; index++) {
  37440. faceAdjacencies = adjacencies[index];
  37441. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  37442. var otherFaceAdjacencies = adjacencies[otherIndex];
  37443. if (faceAdjacencies.edgesConnectedCount === 3) {
  37444. break;
  37445. }
  37446. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  37447. continue;
  37448. }
  37449. var otherP0 = indices[otherIndex * 3];
  37450. var otherP1 = indices[otherIndex * 3 + 1];
  37451. var otherP2 = indices[otherIndex * 3 + 2];
  37452. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  37453. var otherEdgeIndex;
  37454. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  37455. continue;
  37456. }
  37457. switch (edgeIndex) {
  37458. case 0:
  37459. if (this._checkVerticesInsteadOfIndices) {
  37460. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  37461. }
  37462. else {
  37463. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  37464. }
  37465. break;
  37466. case 1:
  37467. if (this._checkVerticesInsteadOfIndices) {
  37468. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  37469. }
  37470. else {
  37471. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  37472. }
  37473. break;
  37474. case 2:
  37475. if (this._checkVerticesInsteadOfIndices) {
  37476. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  37477. }
  37478. else {
  37479. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  37480. }
  37481. break;
  37482. }
  37483. if (otherEdgeIndex === -1) {
  37484. continue;
  37485. }
  37486. faceAdjacencies.edges[edgeIndex] = otherIndex;
  37487. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  37488. faceAdjacencies.edgesConnectedCount++;
  37489. otherFaceAdjacencies.edgesConnectedCount++;
  37490. if (faceAdjacencies.edgesConnectedCount === 3) {
  37491. break;
  37492. }
  37493. }
  37494. }
  37495. }
  37496. // Create lines
  37497. for (index = 0; index < adjacencies.length; index++) {
  37498. // 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
  37499. var current = adjacencies[index];
  37500. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  37501. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  37502. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  37503. }
  37504. // Merge into a single mesh
  37505. var engine = this._source.getScene().getEngine();
  37506. this._vb0 = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  37507. this._vb1 = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  37508. this._buffers[BABYLON.VertexBuffer.PositionKind] = this._vb0;
  37509. this._buffers[BABYLON.VertexBuffer.NormalKind] = this._vb1;
  37510. this._ib = engine.createIndexBuffer(this._linesIndices);
  37511. this._indicesCount = this._linesIndices.length;
  37512. };
  37513. EdgesRenderer.prototype.render = function () {
  37514. if (!this._lineShader.isReady()) {
  37515. return;
  37516. }
  37517. var scene = this._source.getScene();
  37518. var engine = scene.getEngine();
  37519. this._lineShader._preBind();
  37520. // VBOs
  37521. engine.bindMultiBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  37522. scene.resetCachedMaterial();
  37523. this._lineShader.setColor4("color", this._source.edgesColor);
  37524. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  37525. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  37526. }
  37527. else {
  37528. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  37529. }
  37530. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  37531. this._lineShader.bind(this._source.getWorldMatrix());
  37532. // Draw order
  37533. engine.draw(true, 0, this._indicesCount);
  37534. this._lineShader.unbind();
  37535. engine.setDepthWrite(true);
  37536. };
  37537. return EdgesRenderer;
  37538. })();
  37539. BABYLON.EdgesRenderer = EdgesRenderer;
  37540. })(BABYLON || (BABYLON = {}));
  37541. var BABYLON;
  37542. (function (BABYLON) {
  37543. (function (TonemappingOperator) {
  37544. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  37545. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  37546. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  37547. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  37548. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  37549. var TonemappingOperator = BABYLON.TonemappingOperator;
  37550. ;
  37551. var TonemapPostProcess = (function (_super) {
  37552. __extends(TonemapPostProcess, _super);
  37553. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  37554. var _this = this;
  37555. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  37556. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  37557. _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  37558. this._operator = _operator;
  37559. this.exposureAdjustment = exposureAdjustment;
  37560. var defines = "#define ";
  37561. if (this._operator === TonemappingOperator.Hable)
  37562. defines += "HABLE_TONEMAPPING";
  37563. else if (this._operator === TonemappingOperator.Reinhard)
  37564. defines += "REINHARD_TONEMAPPING";
  37565. else if (this._operator === TonemappingOperator.HejiDawson)
  37566. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  37567. else if (this._operator === TonemappingOperator.Photographic)
  37568. defines += "PHOTOGRAPHIC_TONEMAPPING";
  37569. //sadly a second call to create the effect.
  37570. this.updateEffect(defines);
  37571. this.onApply = function (effect) {
  37572. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  37573. };
  37574. }
  37575. return TonemapPostProcess;
  37576. })(BABYLON.PostProcess);
  37577. BABYLON.TonemapPostProcess = TonemapPostProcess;
  37578. })(BABYLON || (BABYLON = {}));
  37579. var BABYLON;
  37580. (function (BABYLON) {
  37581. var ReflectionProbe = (function () {
  37582. function ReflectionProbe(name, size, scene, generateMipMaps) {
  37583. var _this = this;
  37584. if (generateMipMaps === void 0) { generateMipMaps = true; }
  37585. this.name = name;
  37586. this._viewMatrix = BABYLON.Matrix.Identity();
  37587. this._target = BABYLON.Vector3.Zero();
  37588. this._add = BABYLON.Vector3.Zero();
  37589. this.position = BABYLON.Vector3.Zero();
  37590. this._scene = scene;
  37591. this._scene.reflectionProbes.push(this);
  37592. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  37593. this._renderTargetTexture.onBeforeRender = function (faceIndex) {
  37594. switch (faceIndex) {
  37595. case 0:
  37596. _this._add.copyFromFloats(1, 0, 0);
  37597. break;
  37598. case 1:
  37599. _this._add.copyFromFloats(-1, 0, 0);
  37600. break;
  37601. case 2:
  37602. _this._add.copyFromFloats(0, -1, 0);
  37603. break;
  37604. case 3:
  37605. _this._add.copyFromFloats(0, 1, 0);
  37606. break;
  37607. case 4:
  37608. _this._add.copyFromFloats(0, 0, 1);
  37609. break;
  37610. case 5:
  37611. _this._add.copyFromFloats(0, 0, -1);
  37612. break;
  37613. }
  37614. if (_this._attachedMesh) {
  37615. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  37616. }
  37617. _this.position.addToRef(_this._add, _this._target);
  37618. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  37619. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  37620. };
  37621. this._renderTargetTexture.onAfterUnbind = function () {
  37622. scene.updateTransformMatrix(true);
  37623. };
  37624. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  37625. }
  37626. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  37627. get: function () {
  37628. return this._renderTargetTexture.refreshRate;
  37629. },
  37630. set: function (value) {
  37631. this._renderTargetTexture.refreshRate = value;
  37632. },
  37633. enumerable: true,
  37634. configurable: true
  37635. });
  37636. ReflectionProbe.prototype.getScene = function () {
  37637. return this._scene;
  37638. };
  37639. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  37640. get: function () {
  37641. return this._renderTargetTexture;
  37642. },
  37643. enumerable: true,
  37644. configurable: true
  37645. });
  37646. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  37647. get: function () {
  37648. return this._renderTargetTexture.renderList;
  37649. },
  37650. enumerable: true,
  37651. configurable: true
  37652. });
  37653. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  37654. this._attachedMesh = mesh;
  37655. };
  37656. ReflectionProbe.prototype.dispose = function () {
  37657. var index = this._scene.reflectionProbes.indexOf(this);
  37658. if (index !== -1) {
  37659. // Remove from the scene if found
  37660. this._scene.reflectionProbes.splice(index, 1);
  37661. }
  37662. if (this._renderTargetTexture) {
  37663. this._renderTargetTexture.dispose();
  37664. this._renderTargetTexture = null;
  37665. }
  37666. };
  37667. return ReflectionProbe;
  37668. })();
  37669. BABYLON.ReflectionProbe = ReflectionProbe;
  37670. })(BABYLON || (BABYLON = {}));
  37671. var BABYLON;
  37672. (function (BABYLON) {
  37673. var SolidParticle = (function () {
  37674. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape) {
  37675. this.color = new BABYLON.Color4(1, 1, 1, 1); // color
  37676. this.position = BABYLON.Vector3.Zero(); // position
  37677. this.rotation = BABYLON.Vector3.Zero(); // rotation
  37678. this.scale = new BABYLON.Vector3(1, 1, 1); // scale
  37679. this.uvs = new BABYLON.Vector4(0, 0, 1, 1); // uvs
  37680. this.velocity = BABYLON.Vector3.Zero(); // velocity
  37681. this.alive = true; // alive
  37682. this.idx = particleIndex;
  37683. this._pos = positionIndex;
  37684. this._model = model;
  37685. this.shapeId = shapeId;
  37686. this.idxInShape = idxInShape;
  37687. }
  37688. return SolidParticle;
  37689. })();
  37690. BABYLON.SolidParticle = SolidParticle;
  37691. var ModelShape = (function () {
  37692. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  37693. this.shapeID = id;
  37694. this._shape = shape;
  37695. this._shapeUV = shapeUV;
  37696. this._positionFunction = posFunction;
  37697. this._vertexFunction = vtxFunction;
  37698. }
  37699. return ModelShape;
  37700. })();
  37701. BABYLON.ModelShape = ModelShape;
  37702. })(BABYLON || (BABYLON = {}));
  37703. var BABYLON;
  37704. (function (BABYLON) {
  37705. /**
  37706. * Full documentation here : http://doc.babylonjs.com/tutorials/Solid_Particle_System
  37707. */
  37708. var SolidParticleSystem = (function () {
  37709. /**
  37710. * Creates a SPS (Solid Particle System) object.
  37711. * @param name the SPS name, this will be the underlying mesh name
  37712. * @param scene the scene in which the SPS is added
  37713. * @param options "updatable" (default true) : if the SPS must be updatable or immutable, "isPickable" (default false) : if the solid particles must be pickable
  37714. */
  37715. function SolidParticleSystem(name, scene, options) {
  37716. // public members
  37717. /**
  37718. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  37719. * Example : var p = SPS.particles[i];
  37720. */
  37721. this.particles = new Array();
  37722. /**
  37723. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  37724. */
  37725. this.nbParticles = 0;
  37726. /**
  37727. * If the particles must ever face the camera (default false). Useful for planar particles.
  37728. */
  37729. this.billboard = false;
  37730. /**
  37731. * This a counter ofr your own usage. It's not set by any SPS functions.
  37732. */
  37733. this.counter = 0;
  37734. /**
  37735. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  37736. * Please read : http://doc.babylonjs.com/tutorials/Solid_Particle_System#garbage-collector-concerns
  37737. */
  37738. this.vars = {};
  37739. this._positions = new Array();
  37740. this._indices = new Array();
  37741. this._normals = new Array();
  37742. this._colors = new Array();
  37743. this._uvs = new Array();
  37744. this._index = 0; // indices index
  37745. this._updatable = true;
  37746. this._pickable = false;
  37747. this._isVisibilityBoxLocked = false;
  37748. this._alwaysVisible = false;
  37749. this._shapeCounter = 0;
  37750. this._copy = new BABYLON.SolidParticle(null, null, null, null, null);
  37751. this._color = new BABYLON.Color4(0, 0, 0, 0);
  37752. this._computeParticleColor = true;
  37753. this._computeParticleTexture = true;
  37754. this._computeParticleRotation = true;
  37755. this._computeParticleVertex = false;
  37756. this._computeBoundingBox = false;
  37757. this._cam_axisZ = BABYLON.Vector3.Zero();
  37758. this._cam_axisY = BABYLON.Vector3.Zero();
  37759. this._cam_axisX = BABYLON.Vector3.Zero();
  37760. this._axisX = BABYLON.Axis.X;
  37761. this._axisY = BABYLON.Axis.Y;
  37762. this._axisZ = BABYLON.Axis.Z;
  37763. this._fakeCamPos = BABYLON.Vector3.Zero();
  37764. this._rotMatrix = new BABYLON.Matrix();
  37765. this._invertMatrix = new BABYLON.Matrix();
  37766. this._rotated = BABYLON.Vector3.Zero();
  37767. this._quaternion = new BABYLON.Quaternion();
  37768. this._vertex = BABYLON.Vector3.Zero();
  37769. this._normal = BABYLON.Vector3.Zero();
  37770. this._yaw = 0.0;
  37771. this._pitch = 0.0;
  37772. this._roll = 0.0;
  37773. this._halfroll = 0.0;
  37774. this._halfpitch = 0.0;
  37775. this._halfyaw = 0.0;
  37776. this._sinRoll = 0.0;
  37777. this._cosRoll = 0.0;
  37778. this._sinPitch = 0.0;
  37779. this._cosPitch = 0.0;
  37780. this._sinYaw = 0.0;
  37781. this._cosYaw = 0.0;
  37782. this._w = 0.0;
  37783. this._minimum = BABYLON.Tmp.Vector3[0];
  37784. this._maximum = BABYLON.Tmp.Vector3[1];
  37785. this.name = name;
  37786. this._scene = scene;
  37787. this._camera = scene.activeCamera;
  37788. this._pickable = options ? options.isPickable : false;
  37789. if (options && options.updatable) {
  37790. this._updatable = options.updatable;
  37791. }
  37792. else {
  37793. this._updatable = true;
  37794. }
  37795. if (this._pickable) {
  37796. this.pickedParticles = [];
  37797. }
  37798. }
  37799. /**
  37800. * Builds the SPS underlying mesh. Returns a standard Mesh.
  37801. * If no model shape was added to the SPS, the return mesh is only a single triangular plane.
  37802. */
  37803. SolidParticleSystem.prototype.buildMesh = function () {
  37804. if (this.nbParticles === 0) {
  37805. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  37806. this.addShape(triangle, 1);
  37807. triangle.dispose();
  37808. }
  37809. this._positions32 = new Float32Array(this._positions);
  37810. this._uvs32 = new Float32Array(this._uvs);
  37811. this._colors32 = new Float32Array(this._colors);
  37812. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  37813. this._normals32 = new Float32Array(this._normals);
  37814. this._fixedNormal32 = new Float32Array(this._normals);
  37815. var vertexData = new BABYLON.VertexData();
  37816. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  37817. vertexData.indices = this._indices;
  37818. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  37819. if (this._uvs32) {
  37820. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  37821. ;
  37822. }
  37823. if (this._colors32) {
  37824. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  37825. }
  37826. var mesh = new BABYLON.Mesh(this.name, this._scene);
  37827. vertexData.applyToMesh(mesh, this._updatable);
  37828. this.mesh = mesh;
  37829. this.mesh.isPickable = this._pickable;
  37830. // free memory
  37831. this._positions = null;
  37832. this._normals = null;
  37833. this._uvs = null;
  37834. this._colors = null;
  37835. if (!this._updatable) {
  37836. this.particles.length = 0;
  37837. }
  37838. return mesh;
  37839. };
  37840. /**
  37841. * Digests the mesh and generates as many solid particles in the system as wanted.
  37842. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  37843. * Thus the particles generated from digest() have their property "positiion" yet set.
  37844. * @param mesh the mesh to be digested
  37845. * @param facetNb the number of mesh facets per particle (optional, default 1), this parameter is overriden by the parameter "number" if any
  37846. * @param delta the random extra number of facets per partical (optional, default 0), each particle will have between facetNb and facetNb + delta facets
  37847. * @param number the wanted number of particles : each particle is built with mesh_total_facets / number facets (optional)
  37848. */
  37849. SolidParticleSystem.prototype.digest = function (mesh, options) {
  37850. var size = (options && options.facetNb) || 1;
  37851. var number = (options && options.number);
  37852. var delta = (options && options.delta) || 0;
  37853. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37854. var meshInd = mesh.getIndices();
  37855. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37856. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  37857. var f = 0; // facet counter
  37858. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  37859. // compute size from number
  37860. if (number) {
  37861. number = (number > totalFacets) ? totalFacets : number;
  37862. size = Math.round(totalFacets / number);
  37863. delta = 0;
  37864. }
  37865. else {
  37866. size = (size > totalFacets) ? totalFacets : size;
  37867. }
  37868. var facetPos = []; // submesh positions
  37869. var facetInd = []; // submesh indices
  37870. var facetUV = []; // submesh UV
  37871. var facetCol = []; // submesh colors
  37872. var barycenter = BABYLON.Tmp.Vector3[0];
  37873. var rand;
  37874. var sizeO = size;
  37875. while (f < totalFacets) {
  37876. size = sizeO + Math.floor((1 + delta) * Math.random());
  37877. if (f > totalFacets - size) {
  37878. size = totalFacets - f;
  37879. }
  37880. // reset temp arrays
  37881. facetPos.length = 0;
  37882. facetInd.length = 0;
  37883. facetUV.length = 0;
  37884. facetCol.length = 0;
  37885. // iterate over "size" facets
  37886. var fi = 0;
  37887. for (var j = f * 3; j < (f + size) * 3; j++) {
  37888. facetInd.push(fi);
  37889. var i = meshInd[j];
  37890. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  37891. if (meshUV) {
  37892. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  37893. }
  37894. if (meshCol) {
  37895. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  37896. }
  37897. fi++;
  37898. }
  37899. // create a model shape for each single particle
  37900. var idx = this.nbParticles;
  37901. var shape = this._posToShape(facetPos);
  37902. var shapeUV = this._uvsToShapeUV(facetUV);
  37903. // compute the barycenter of the shape
  37904. var v;
  37905. for (v = 0; v < shape.length; v++) {
  37906. barycenter.addInPlace(shape[v]);
  37907. }
  37908. barycenter.scaleInPlace(1 / shape.length);
  37909. // shift the shape from its barycenter to the origin
  37910. for (v = 0; v < shape.length; v++) {
  37911. shape[v].subtractInPlace(barycenter);
  37912. }
  37913. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  37914. // add the particle in the SPS
  37915. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, idx, 0, null);
  37916. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, 0);
  37917. // initialize the particle position
  37918. this.particles[this.nbParticles].position.addInPlace(barycenter);
  37919. this._index += shape.length;
  37920. idx++;
  37921. this.nbParticles++;
  37922. this._shapeCounter++;
  37923. f += size;
  37924. }
  37925. };
  37926. //reset copy
  37927. SolidParticleSystem.prototype._resetCopy = function () {
  37928. this._copy.position.x = 0;
  37929. this._copy.position.y = 0;
  37930. this._copy.position.z = 0;
  37931. this._copy.rotation.x = 0;
  37932. this._copy.rotation.y = 0;
  37933. this._copy.rotation.z = 0;
  37934. this._copy.quaternion = null;
  37935. this._copy.scale.x = 1;
  37936. this._copy.scale.y = 1;
  37937. this._copy.scale.z = 1;
  37938. this._copy.uvs.x = 0;
  37939. this._copy.uvs.y = 0;
  37940. this._copy.uvs.z = 1;
  37941. this._copy.uvs.w = 1;
  37942. this._copy.color = null;
  37943. };
  37944. // _meshBuilder : inserts the shape model in the global SPS mesh
  37945. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, idx, idxInShape, options) {
  37946. var i;
  37947. var u = 0;
  37948. var c = 0;
  37949. this._resetCopy();
  37950. if (options && options.positionFunction) {
  37951. options.positionFunction(this._copy, idx, idxInShape);
  37952. }
  37953. if (this._copy.quaternion) {
  37954. this._quaternion.x = this._copy.quaternion.x;
  37955. this._quaternion.y = this._copy.quaternion.y;
  37956. this._quaternion.z = this._copy.quaternion.z;
  37957. this._quaternion.w = this._copy.quaternion.w;
  37958. }
  37959. else {
  37960. this._yaw = this._copy.rotation.y;
  37961. this._pitch = this._copy.rotation.x;
  37962. this._roll = this._copy.rotation.z;
  37963. this._quaternionRotationYPR();
  37964. }
  37965. this._quaternionToRotationMatrix();
  37966. for (i = 0; i < shape.length; i++) {
  37967. this._vertex.x = shape[i].x;
  37968. this._vertex.y = shape[i].y;
  37969. this._vertex.z = shape[i].z;
  37970. if (options && options.vertexFunction) {
  37971. options.vertexFunction(this._copy, this._vertex, i);
  37972. }
  37973. this._vertex.x *= this._copy.scale.x;
  37974. this._vertex.y *= this._copy.scale.y;
  37975. this._vertex.z *= this._copy.scale.z;
  37976. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  37977. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  37978. if (meshUV) {
  37979. 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);
  37980. u += 2;
  37981. }
  37982. if (this._copy.color) {
  37983. this._color = this._copy.color;
  37984. }
  37985. else if (meshCol && meshCol[c]) {
  37986. this._color.r = meshCol[c];
  37987. this._color.g = meshCol[c + 1];
  37988. this._color.b = meshCol[c + 2];
  37989. this._color.a = meshCol[c + 3];
  37990. }
  37991. else {
  37992. this._color.r = 1;
  37993. this._color.g = 1;
  37994. this._color.b = 1;
  37995. this._color.a = 1;
  37996. }
  37997. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  37998. c += 4;
  37999. }
  38000. for (i = 0; i < meshInd.length; i++) {
  38001. indices.push(p + meshInd[i]);
  38002. }
  38003. if (this._pickable) {
  38004. var nbfaces = meshInd.length / 3;
  38005. for (i = 0; i < nbfaces; i++) {
  38006. this.pickedParticles.push({ idx: idx, faceId: i });
  38007. }
  38008. }
  38009. };
  38010. // returns a shape array from positions array
  38011. SolidParticleSystem.prototype._posToShape = function (positions) {
  38012. var shape = [];
  38013. for (var i = 0; i < positions.length; i += 3) {
  38014. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  38015. }
  38016. return shape;
  38017. };
  38018. // returns a shapeUV array from a Vector4 uvs
  38019. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  38020. var shapeUV = [];
  38021. if (uvs) {
  38022. for (var i = 0; i < uvs.length; i++)
  38023. shapeUV.push(uvs[i]);
  38024. }
  38025. return shapeUV;
  38026. };
  38027. // adds a new particle object in the particles array
  38028. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape) {
  38029. this.particles.push(new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape));
  38030. };
  38031. /**
  38032. * Adds some particles to the SPS from the model shape.
  38033. * Please read the doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#create-an-immutable-sps
  38034. * @param mesh any Mesh object that will be used as a model for the solid particles.
  38035. * @param nb the number of particles to be created from this model
  38036. * @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
  38037. */
  38038. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  38039. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38040. var meshInd = mesh.getIndices();
  38041. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  38042. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  38043. var shape = this._posToShape(meshPos);
  38044. var shapeUV = this._uvsToShapeUV(meshUV);
  38045. var posfunc = options ? options.positionFunction : null;
  38046. var vtxfunc = options ? options.vertexFunction : null;
  38047. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  38048. // particles
  38049. var idx = this.nbParticles;
  38050. for (var i = 0; i < nb; i++) {
  38051. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, idx, i, options);
  38052. if (this._updatable) {
  38053. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, i);
  38054. }
  38055. this._index += shape.length;
  38056. idx++;
  38057. }
  38058. this.nbParticles += nb;
  38059. this._shapeCounter++;
  38060. return this._shapeCounter - 1;
  38061. };
  38062. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  38063. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  38064. this._resetCopy();
  38065. if (particle._model._positionFunction) {
  38066. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  38067. }
  38068. if (this._copy.quaternion) {
  38069. this._quaternion.x = this._copy.quaternion.x;
  38070. this._quaternion.y = this._copy.quaternion.y;
  38071. this._quaternion.z = this._copy.quaternion.z;
  38072. this._quaternion.w = this._copy.quaternion.w;
  38073. }
  38074. else {
  38075. this._yaw = this._copy.rotation.y;
  38076. this._pitch = this._copy.rotation.x;
  38077. this._roll = this._copy.rotation.z;
  38078. this._quaternionRotationYPR();
  38079. }
  38080. this._quaternionToRotationMatrix();
  38081. this._shape = particle._model._shape;
  38082. for (var pt = 0; pt < this._shape.length; pt++) {
  38083. this._vertex.x = this._shape[pt].x;
  38084. this._vertex.y = this._shape[pt].y;
  38085. this._vertex.z = this._shape[pt].z;
  38086. if (particle._model._vertexFunction) {
  38087. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  38088. }
  38089. this._vertex.x *= this._copy.scale.x;
  38090. this._vertex.y *= this._copy.scale.y;
  38091. this._vertex.z *= this._copy.scale.z;
  38092. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  38093. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  38094. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  38095. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  38096. }
  38097. particle.position.x = 0;
  38098. particle.position.y = 0;
  38099. particle.position.z = 0;
  38100. particle.rotation.x = 0;
  38101. particle.rotation.y = 0;
  38102. particle.rotation.z = 0;
  38103. particle.quaternion = null;
  38104. particle.scale.x = 1;
  38105. particle.scale.y = 1;
  38106. particle.scale.z = 1;
  38107. };
  38108. /**
  38109. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  38110. */
  38111. SolidParticleSystem.prototype.rebuildMesh = function () {
  38112. for (var p = 0; p < this.particles.length; p++) {
  38113. this._rebuildParticle(this.particles[p]);
  38114. }
  38115. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  38116. };
  38117. /**
  38118. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  38119. * This method calls updateParticle() for each particles of the SPS.
  38120. * For an animated SPS, it is usually called within the render loop.
  38121. * @param start (default 0) the particle index in the particle array where to start to compute the particle property values
  38122. * @param end (default nbParticle - 1) the particle index in the particle array where to stop to compute the particle property values
  38123. * @param update (default true) if the mesh must be finally updated on this call after all the particle computations.
  38124. */
  38125. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  38126. if (start === void 0) { start = 0; }
  38127. if (end === void 0) { end = this.nbParticles - 1; }
  38128. if (update === void 0) { update = true; }
  38129. if (!this._updatable) {
  38130. return;
  38131. }
  38132. // custom beforeUpdate
  38133. this.beforeUpdateParticles(start, end, update);
  38134. this._cam_axisX.x = 1;
  38135. this._cam_axisX.y = 0;
  38136. this._cam_axisX.z = 0;
  38137. this._cam_axisY.x = 0;
  38138. this._cam_axisY.y = 1;
  38139. this._cam_axisY.z = 0;
  38140. this._cam_axisZ.x = 0;
  38141. this._cam_axisZ.y = 0;
  38142. this._cam_axisZ.z = 1;
  38143. // if the particles will always face the camera
  38144. if (this.billboard) {
  38145. // compute a fake camera position : un-rotate the camera position by the current mesh rotation
  38146. this._yaw = this.mesh.rotation.y;
  38147. this._pitch = this.mesh.rotation.x;
  38148. this._roll = this.mesh.rotation.z;
  38149. this._quaternionRotationYPR();
  38150. this._quaternionToRotationMatrix();
  38151. this._rotMatrix.invertToRef(this._invertMatrix);
  38152. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._fakeCamPos);
  38153. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the cam-mesh axis (_cam_axisZ)
  38154. (this._fakeCamPos).subtractToRef(this.mesh.position, this._cam_axisZ);
  38155. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  38156. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._cam_axisY, this._cam_axisX);
  38157. this._cam_axisY.normalize();
  38158. this._cam_axisX.normalize();
  38159. this._cam_axisZ.normalize();
  38160. }
  38161. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  38162. var idx = 0;
  38163. var index = 0;
  38164. var colidx = 0;
  38165. var colorIndex = 0;
  38166. var uvidx = 0;
  38167. var uvIndex = 0;
  38168. if (this._computeBoundingBox) {
  38169. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  38170. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  38171. }
  38172. // particle loop
  38173. end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
  38174. for (var p = start; p <= end; p++) {
  38175. this._particle = this.particles[p];
  38176. this._shape = this._particle._model._shape;
  38177. this._shapeUV = this._particle._model._shapeUV;
  38178. // call to custom user function to update the particle properties
  38179. this.updateParticle(this._particle);
  38180. // particle rotation matrix
  38181. if (this.billboard) {
  38182. this._particle.rotation.x = 0.0;
  38183. this._particle.rotation.y = 0.0;
  38184. }
  38185. if (this._computeParticleRotation) {
  38186. if (this._particle.quaternion) {
  38187. this._quaternion.x = this._particle.quaternion.x;
  38188. this._quaternion.y = this._particle.quaternion.y;
  38189. this._quaternion.z = this._particle.quaternion.z;
  38190. this._quaternion.w = this._particle.quaternion.w;
  38191. }
  38192. else {
  38193. this._yaw = this._particle.rotation.y;
  38194. this._pitch = this._particle.rotation.x;
  38195. this._roll = this._particle.rotation.z;
  38196. this._quaternionRotationYPR();
  38197. }
  38198. this._quaternionToRotationMatrix();
  38199. }
  38200. for (var pt = 0; pt < this._shape.length; pt++) {
  38201. idx = index + pt * 3;
  38202. colidx = colorIndex + pt * 4;
  38203. uvidx = uvIndex + pt * 2;
  38204. this._vertex.x = this._shape[pt].x;
  38205. this._vertex.y = this._shape[pt].y;
  38206. this._vertex.z = this._shape[pt].z;
  38207. if (this._computeParticleVertex) {
  38208. this.updateParticleVertex(this._particle, this._vertex, pt);
  38209. }
  38210. // positions
  38211. this._vertex.x *= this._particle.scale.x;
  38212. this._vertex.y *= this._particle.scale.y;
  38213. this._vertex.z *= this._particle.scale.z;
  38214. 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];
  38215. 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;
  38216. 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;
  38217. 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;
  38218. 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;
  38219. 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;
  38220. 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;
  38221. if (this._computeBoundingBox) {
  38222. if (this._positions32[idx] < this._minimum.x) {
  38223. this._minimum.x = this._positions32[idx];
  38224. }
  38225. if (this._positions32[idx] > this._maximum.x) {
  38226. this._maximum.x = this._positions32[idx];
  38227. }
  38228. if (this._positions32[idx + 1] < this._minimum.y) {
  38229. this._minimum.y = this._positions32[idx + 1];
  38230. }
  38231. if (this._positions32[idx + 1] > this._maximum.y) {
  38232. this._maximum.y = this._positions32[idx + 1];
  38233. }
  38234. if (this._positions32[idx + 2] < this._minimum.z) {
  38235. this._minimum.z = this._positions32[idx + 2];
  38236. }
  38237. if (this._positions32[idx + 2] > this._maximum.z) {
  38238. this._maximum.z = this._positions32[idx + 2];
  38239. }
  38240. }
  38241. // normals : if the particles can't be morphed then just rotate the normals
  38242. if (!this._computeParticleVertex && !this.billboard) {
  38243. this._normal.x = this._fixedNormal32[idx];
  38244. this._normal.y = this._fixedNormal32[idx + 1];
  38245. this._normal.z = this._fixedNormal32[idx + 2];
  38246. 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];
  38247. 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;
  38248. 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;
  38249. 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;
  38250. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  38251. 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;
  38252. 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;
  38253. }
  38254. if (this._computeParticleColor) {
  38255. this._colors32[colidx] = this._particle.color.r;
  38256. this._colors32[colidx + 1] = this._particle.color.g;
  38257. this._colors32[colidx + 2] = this._particle.color.b;
  38258. this._colors32[colidx + 3] = this._particle.color.a;
  38259. }
  38260. if (this._computeParticleTexture) {
  38261. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  38262. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  38263. }
  38264. }
  38265. index = idx + 3;
  38266. colorIndex = colidx + 4;
  38267. uvIndex = uvidx + 2;
  38268. }
  38269. if (update) {
  38270. if (this._computeParticleColor) {
  38271. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  38272. }
  38273. if (this._computeParticleTexture) {
  38274. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  38275. }
  38276. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  38277. if (!this.mesh.areNormalsFrozen) {
  38278. if (this._computeParticleVertex || this.billboard) {
  38279. // recompute the normals only if the particles can be morphed, update then the normal reference array
  38280. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32);
  38281. for (var i = 0; i < this._normals32.length; i++) {
  38282. this._fixedNormal32[i] = this._normals32[i];
  38283. }
  38284. }
  38285. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  38286. }
  38287. }
  38288. if (this._computeBoundingBox) {
  38289. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  38290. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  38291. }
  38292. this.afterUpdateParticles(start, end, update);
  38293. };
  38294. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  38295. this._halfroll = this._roll * 0.5;
  38296. this._halfpitch = this._pitch * 0.5;
  38297. this._halfyaw = this._yaw * 0.5;
  38298. this._sinRoll = Math.sin(this._halfroll);
  38299. this._cosRoll = Math.cos(this._halfroll);
  38300. this._sinPitch = Math.sin(this._halfpitch);
  38301. this._cosPitch = Math.cos(this._halfpitch);
  38302. this._sinYaw = Math.sin(this._halfyaw);
  38303. this._cosYaw = Math.cos(this._halfyaw);
  38304. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  38305. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  38306. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  38307. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  38308. };
  38309. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  38310. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  38311. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  38312. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  38313. this._rotMatrix.m[3] = 0;
  38314. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  38315. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  38316. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  38317. this._rotMatrix.m[7] = 0;
  38318. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  38319. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  38320. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  38321. this._rotMatrix.m[11] = 0;
  38322. this._rotMatrix.m[12] = 0;
  38323. this._rotMatrix.m[13] = 0;
  38324. this._rotMatrix.m[14] = 0;
  38325. this._rotMatrix.m[15] = 1.0;
  38326. };
  38327. /**
  38328. * Disposes the SPS
  38329. */
  38330. SolidParticleSystem.prototype.dispose = function () {
  38331. this.mesh.dispose();
  38332. this.vars = null;
  38333. // drop references to internal big arrays for the GC
  38334. this._positions = null;
  38335. this._indices = null;
  38336. this._normals = null;
  38337. this._uvs = null;
  38338. this._colors = null;
  38339. this._positions32 = null;
  38340. this._normals32 = null;
  38341. this._fixedNormal32 = null;
  38342. this._uvs32 = null;
  38343. this._colors32 = null;
  38344. this.pickedParticles = null;
  38345. };
  38346. /**
  38347. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  38348. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  38349. */
  38350. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  38351. if (!this._isVisibilityBoxLocked) {
  38352. this.mesh.refreshBoundingInfo();
  38353. }
  38354. };
  38355. /** Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  38356. * @param size the size (float) of the visibility box
  38357. * note : this doesn't lock the SPS mesh bounding box.
  38358. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  38359. */
  38360. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  38361. var vis = size / 2;
  38362. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  38363. };
  38364. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  38365. // getter and setter
  38366. /**
  38367. * True if the SPS is set as always visible
  38368. */
  38369. get: function () {
  38370. return this._alwaysVisible;
  38371. },
  38372. /**
  38373. * Sets the SPS as always visible or not
  38374. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  38375. */
  38376. set: function (val) {
  38377. this._alwaysVisible = val;
  38378. this.mesh.alwaysSelectAsActiveMesh = val;
  38379. },
  38380. enumerable: true,
  38381. configurable: true
  38382. });
  38383. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  38384. /**
  38385. * True if the SPS visibility box is locked. The underlying mesh bounding box is then not updatable any more.
  38386. */
  38387. get: function () {
  38388. return this._isVisibilityBoxLocked;
  38389. },
  38390. /**
  38391. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  38392. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  38393. */
  38394. set: function (val) {
  38395. this._isVisibilityBoxLocked = val;
  38396. this.mesh.getBoundingInfo().isLocked = val;
  38397. },
  38398. enumerable: true,
  38399. configurable: true
  38400. });
  38401. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  38402. // getters
  38403. get: function () {
  38404. return this._computeParticleRotation;
  38405. },
  38406. // Optimizer setters
  38407. /**
  38408. * Tells to setParticles() to compute the particle rotations or not.
  38409. * Default value : true. The SPS is faster when it's set to false.
  38410. * Note : the particle rotations aren't stored values, so setting computeParticleRotation to false will prevents the particle to rotate.
  38411. */
  38412. set: function (val) {
  38413. this._computeParticleRotation = val;
  38414. },
  38415. enumerable: true,
  38416. configurable: true
  38417. });
  38418. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  38419. get: function () {
  38420. return this._computeParticleColor;
  38421. },
  38422. /**
  38423. * Tells to setParticles() to compute the particle colors or not.
  38424. * Default value : true. The SPS is faster when it's set to false.
  38425. * Note : the particle colors are stored values, so setting computeParticleColor to false will keep yet the last colors set.
  38426. */
  38427. set: function (val) {
  38428. this._computeParticleColor = val;
  38429. },
  38430. enumerable: true,
  38431. configurable: true
  38432. });
  38433. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  38434. get: function () {
  38435. return this._computeParticleTexture;
  38436. },
  38437. /**
  38438. * Tells to setParticles() to compute the particle textures or not.
  38439. * Default value : true. The SPS is faster when it's set to false.
  38440. * Note : the particle textures are stored values, so setting computeParticleTexture to false will keep yet the last colors set.
  38441. */
  38442. set: function (val) {
  38443. this._computeParticleTexture = val;
  38444. },
  38445. enumerable: true,
  38446. configurable: true
  38447. });
  38448. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  38449. get: function () {
  38450. return this._computeParticleVertex;
  38451. },
  38452. /**
  38453. * Tells to setParticles() to call the vertex function for each vertex of each particle, or not.
  38454. * Default value : false. The SPS is faster when it's set to false.
  38455. * Note : the particle custom vertex positions aren't stored values.
  38456. */
  38457. set: function (val) {
  38458. this._computeParticleVertex = val;
  38459. },
  38460. enumerable: true,
  38461. configurable: true
  38462. });
  38463. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  38464. get: function () {
  38465. return this._computeBoundingBox;
  38466. },
  38467. /**
  38468. * Tells to setParticles() to compute or not the mesh bounding box when computing the particle positions.
  38469. */
  38470. set: function (val) {
  38471. this._computeBoundingBox = val;
  38472. },
  38473. enumerable: true,
  38474. configurable: true
  38475. });
  38476. // =======================================================================
  38477. // Particle behavior logic
  38478. // these following methods may be overwritten by the user to fit his needs
  38479. /**
  38480. * This function does nothing. It may be overwritten to set all the particles first values.
  38481. * The SPS doesn't call this function, you may have to call it by your own.
  38482. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  38483. */
  38484. SolidParticleSystem.prototype.initParticles = function () {
  38485. };
  38486. /**
  38487. * This function does nothing. It may be overwritten to recycle a particle.
  38488. * The SPS doesn't call this function, you may have to call it by your own.
  38489. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  38490. */
  38491. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  38492. return particle;
  38493. };
  38494. /**
  38495. * Updates a particle : this function should be overwritten by the user.
  38496. * It is called on each particle by setParticles(). This is the place to code each particle behavior.
  38497. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  38498. * ex : just set a particle position or velocity and recycle conditions
  38499. */
  38500. SolidParticleSystem.prototype.updateParticle = function (particle) {
  38501. return particle;
  38502. };
  38503. /**
  38504. * Updates a vertex of a particle : it can be overwritten by the user.
  38505. * This will be called on each vertex particle by setParticles() if computeParticleVertex is set to true only.
  38506. * @param particle the current particle
  38507. * @param vertex the current index of the current particle
  38508. * @param pt the index of the current vertex in the particle shape
  38509. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#update-each-particle-shape
  38510. * ex : just set a vertex particle position
  38511. */
  38512. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  38513. return vertex;
  38514. };
  38515. /**
  38516. * This will be called before any other treatment by setParticles() and will be passed three parameters.
  38517. * This does nothing and may be overwritten by the user.
  38518. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  38519. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  38520. * @param update the boolean update value actually passed to setParticles()
  38521. */
  38522. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  38523. };
  38524. /**
  38525. * This will be called by setParticles() after all the other treatments and just before the actual mesh update.
  38526. * This will be passed three parameters.
  38527. * This does nothing and may be overwritten by the user.
  38528. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  38529. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  38530. * @param update the boolean update value actually passed to setParticles()
  38531. */
  38532. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  38533. };
  38534. return SolidParticleSystem;
  38535. })();
  38536. BABYLON.SolidParticleSystem = SolidParticleSystem;
  38537. })(BABYLON || (BABYLON = {}));
  38538. var BABYLON;
  38539. (function (BABYLON) {
  38540. // We're mainly based on the logic defined into the FreeCamera code
  38541. var UniversalCamera = (function (_super) {
  38542. __extends(UniversalCamera, _super);
  38543. function UniversalCamera(name, position, scene) {
  38544. var _this = this;
  38545. _super.call(this, name, position, scene);
  38546. this.gamepadAngularSensibility = 200;
  38547. this.gamepadMoveSensibility = 40;
  38548. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  38549. }
  38550. UniversalCamera.prototype._onNewGameConnected = function (gamepad) {
  38551. // Only the first gamepad can control the camera
  38552. if (gamepad.index === 0) {
  38553. this.gamepad = gamepad;
  38554. }
  38555. };
  38556. UniversalCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  38557. _super.prototype.attachControl.call(this, canvas, false);
  38558. };
  38559. UniversalCamera.prototype.detachControl = function (canvas) {
  38560. _super.prototype.detachControl.call(this, canvas);
  38561. };
  38562. UniversalCamera.prototype._checkInputs = function () {
  38563. if (this.gamepad) {
  38564. var LSValues = this.gamepad.leftStick;
  38565. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  38566. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  38567. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  38568. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  38569. var RSValues = this.gamepad.rightStick;
  38570. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  38571. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  38572. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  38573. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  38574. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  38575. var speed = this._computeLocalCameraSpeed() * 50.0;
  38576. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  38577. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  38578. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  38579. }
  38580. _super.prototype._checkInputs.call(this);
  38581. };
  38582. UniversalCamera.prototype.dispose = function () {
  38583. this._gamepads.dispose();
  38584. _super.prototype.dispose.call(this);
  38585. };
  38586. UniversalCamera.prototype.getTypeName = function () {
  38587. return "UniversalCamera";
  38588. };
  38589. __decorate([
  38590. BABYLON.serialize()
  38591. ], UniversalCamera.prototype, "gamepadAngularSensibility", void 0);
  38592. __decorate([
  38593. BABYLON.serialize()
  38594. ], UniversalCamera.prototype, "gamepadMoveSensibility", void 0);
  38595. return UniversalCamera;
  38596. })(BABYLON.TouchCamera);
  38597. BABYLON.UniversalCamera = UniversalCamera;
  38598. })(BABYLON || (BABYLON = {}));
  38599. var BABYLON;
  38600. (function (BABYLON) {
  38601. var Gamepads = (function () {
  38602. function Gamepads(ongamedpadconnected) {
  38603. var _this = this;
  38604. this.babylonGamepads = [];
  38605. this.oneGamepadConnected = false;
  38606. this.isMonitoring = false;
  38607. this.gamepadEventSupported = 'GamepadEvent' in window;
  38608. this.gamepadSupportAvailable = (navigator.getGamepads ||
  38609. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  38610. this._callbackGamepadConnected = ongamedpadconnected;
  38611. if (this.gamepadSupportAvailable) {
  38612. // Checking if the gamepad connected event is supported (like in Firefox)
  38613. if (this.gamepadEventSupported) {
  38614. window.addEventListener('gamepadconnected', function (evt) {
  38615. _this._onGamepadConnected(evt);
  38616. }, false);
  38617. window.addEventListener('gamepaddisconnected', function (evt) {
  38618. _this._onGamepadDisconnected(evt);
  38619. }, false);
  38620. }
  38621. else {
  38622. this._startMonitoringGamepads();
  38623. }
  38624. }
  38625. }
  38626. Gamepads.prototype.dispose = function () {
  38627. if (Gamepads.gamepadDOMInfo) {
  38628. document.body.removeChild(Gamepads.gamepadDOMInfo);
  38629. }
  38630. };
  38631. Gamepads.prototype._onGamepadConnected = function (evt) {
  38632. var newGamepad = this._addNewGamepad(evt.gamepad);
  38633. if (this._callbackGamepadConnected)
  38634. this._callbackGamepadConnected(newGamepad);
  38635. this._startMonitoringGamepads();
  38636. };
  38637. Gamepads.prototype._addNewGamepad = function (gamepad) {
  38638. if (!this.oneGamepadConnected) {
  38639. this.oneGamepadConnected = true;
  38640. if (Gamepads.gamepadDOMInfo) {
  38641. document.body.removeChild(Gamepads.gamepadDOMInfo);
  38642. Gamepads.gamepadDOMInfo = null;
  38643. }
  38644. }
  38645. var newGamepad;
  38646. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  38647. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  38648. }
  38649. else {
  38650. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  38651. }
  38652. this.babylonGamepads.push(newGamepad);
  38653. return newGamepad;
  38654. };
  38655. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  38656. // Remove the gamepad from the list of gamepads to monitor.
  38657. for (var i in this.babylonGamepads) {
  38658. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  38659. this.babylonGamepads.splice(+i, 1);
  38660. break;
  38661. }
  38662. }
  38663. // If no gamepads are left, stop the polling loop.
  38664. if (this.babylonGamepads.length == 0) {
  38665. this._stopMonitoringGamepads();
  38666. }
  38667. };
  38668. Gamepads.prototype._startMonitoringGamepads = function () {
  38669. if (!this.isMonitoring) {
  38670. this.isMonitoring = true;
  38671. this._checkGamepadsStatus();
  38672. }
  38673. };
  38674. Gamepads.prototype._stopMonitoringGamepads = function () {
  38675. this.isMonitoring = false;
  38676. };
  38677. Gamepads.prototype._checkGamepadsStatus = function () {
  38678. var _this = this;
  38679. // updating gamepad objects
  38680. this._updateGamepadObjects();
  38681. for (var i in this.babylonGamepads) {
  38682. this.babylonGamepads[i].update();
  38683. }
  38684. if (this.isMonitoring) {
  38685. if (window.requestAnimationFrame) {
  38686. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  38687. }
  38688. else if (window.mozRequestAnimationFrame) {
  38689. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  38690. }
  38691. else if (window.webkitRequestAnimationFrame) {
  38692. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  38693. }
  38694. }
  38695. };
  38696. // This function is called only on Chrome, which does not yet support
  38697. // connection/disconnection events, but requires you to monitor
  38698. // an array for changes.
  38699. Gamepads.prototype._updateGamepadObjects = function () {
  38700. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  38701. for (var i = 0; i < gamepads.length; i++) {
  38702. if (gamepads[i]) {
  38703. if (!(gamepads[i].index in this.babylonGamepads)) {
  38704. var newGamepad = this._addNewGamepad(gamepads[i]);
  38705. if (this._callbackGamepadConnected) {
  38706. this._callbackGamepadConnected(newGamepad);
  38707. }
  38708. }
  38709. else {
  38710. this.babylonGamepads[i].browserGamepad = gamepads[i];
  38711. }
  38712. }
  38713. }
  38714. };
  38715. return Gamepads;
  38716. })();
  38717. BABYLON.Gamepads = Gamepads;
  38718. var StickValues = (function () {
  38719. function StickValues(x, y) {
  38720. this.x = x;
  38721. this.y = y;
  38722. }
  38723. return StickValues;
  38724. })();
  38725. BABYLON.StickValues = StickValues;
  38726. var Gamepad = (function () {
  38727. function Gamepad(id, index, browserGamepad) {
  38728. this.id = id;
  38729. this.index = index;
  38730. this.browserGamepad = browserGamepad;
  38731. if (this.browserGamepad.axes.length >= 2) {
  38732. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  38733. }
  38734. if (this.browserGamepad.axes.length >= 4) {
  38735. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  38736. }
  38737. }
  38738. Gamepad.prototype.onleftstickchanged = function (callback) {
  38739. this._onleftstickchanged = callback;
  38740. };
  38741. Gamepad.prototype.onrightstickchanged = function (callback) {
  38742. this._onrightstickchanged = callback;
  38743. };
  38744. Object.defineProperty(Gamepad.prototype, "leftStick", {
  38745. get: function () {
  38746. return this._leftStick;
  38747. },
  38748. set: function (newValues) {
  38749. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  38750. this._onleftstickchanged(newValues);
  38751. }
  38752. this._leftStick = newValues;
  38753. },
  38754. enumerable: true,
  38755. configurable: true
  38756. });
  38757. Object.defineProperty(Gamepad.prototype, "rightStick", {
  38758. get: function () {
  38759. return this._rightStick;
  38760. },
  38761. set: function (newValues) {
  38762. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  38763. this._onrightstickchanged(newValues);
  38764. }
  38765. this._rightStick = newValues;
  38766. },
  38767. enumerable: true,
  38768. configurable: true
  38769. });
  38770. Gamepad.prototype.update = function () {
  38771. if (this._leftStick) {
  38772. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  38773. }
  38774. if (this._rightStick) {
  38775. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  38776. }
  38777. };
  38778. return Gamepad;
  38779. })();
  38780. BABYLON.Gamepad = Gamepad;
  38781. var GenericPad = (function (_super) {
  38782. __extends(GenericPad, _super);
  38783. function GenericPad(id, index, gamepad) {
  38784. _super.call(this, id, index, gamepad);
  38785. this.id = id;
  38786. this.index = index;
  38787. this.gamepad = gamepad;
  38788. this._buttons = new Array(gamepad.buttons.length);
  38789. }
  38790. GenericPad.prototype.onbuttondown = function (callback) {
  38791. this._onbuttondown = callback;
  38792. };
  38793. GenericPad.prototype.onbuttonup = function (callback) {
  38794. this._onbuttonup = callback;
  38795. };
  38796. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  38797. if (newValue !== currentValue) {
  38798. if (this._onbuttondown && newValue === 1) {
  38799. this._onbuttondown(buttonIndex);
  38800. }
  38801. if (this._onbuttonup && newValue === 0) {
  38802. this._onbuttonup(buttonIndex);
  38803. }
  38804. }
  38805. return newValue;
  38806. };
  38807. GenericPad.prototype.update = function () {
  38808. _super.prototype.update.call(this);
  38809. for (var index = 0; index < this._buttons.length; index++) {
  38810. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  38811. }
  38812. };
  38813. return GenericPad;
  38814. })(Gamepad);
  38815. BABYLON.GenericPad = GenericPad;
  38816. (function (Xbox360Button) {
  38817. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  38818. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  38819. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  38820. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  38821. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  38822. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  38823. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  38824. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  38825. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  38826. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  38827. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  38828. var Xbox360Button = BABYLON.Xbox360Button;
  38829. (function (Xbox360Dpad) {
  38830. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  38831. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  38832. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  38833. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  38834. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  38835. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  38836. var Xbox360Pad = (function (_super) {
  38837. __extends(Xbox360Pad, _super);
  38838. function Xbox360Pad() {
  38839. _super.apply(this, arguments);
  38840. this._leftTrigger = 0;
  38841. this._rightTrigger = 0;
  38842. this._buttonA = 0;
  38843. this._buttonB = 0;
  38844. this._buttonX = 0;
  38845. this._buttonY = 0;
  38846. this._buttonBack = 0;
  38847. this._buttonStart = 0;
  38848. this._buttonLB = 0;
  38849. this._buttonRB = 0;
  38850. this._buttonLeftStick = 0;
  38851. this._buttonRightStick = 0;
  38852. this._dPadUp = 0;
  38853. this._dPadDown = 0;
  38854. this._dPadLeft = 0;
  38855. this._dPadRight = 0;
  38856. }
  38857. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  38858. this._onlefttriggerchanged = callback;
  38859. };
  38860. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  38861. this._onrighttriggerchanged = callback;
  38862. };
  38863. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  38864. get: function () {
  38865. return this._leftTrigger;
  38866. },
  38867. set: function (newValue) {
  38868. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  38869. this._onlefttriggerchanged(newValue);
  38870. }
  38871. this._leftTrigger = newValue;
  38872. },
  38873. enumerable: true,
  38874. configurable: true
  38875. });
  38876. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  38877. get: function () {
  38878. return this._rightTrigger;
  38879. },
  38880. set: function (newValue) {
  38881. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  38882. this._onrighttriggerchanged(newValue);
  38883. }
  38884. this._rightTrigger = newValue;
  38885. },
  38886. enumerable: true,
  38887. configurable: true
  38888. });
  38889. Xbox360Pad.prototype.onbuttondown = function (callback) {
  38890. this._onbuttondown = callback;
  38891. };
  38892. Xbox360Pad.prototype.onbuttonup = function (callback) {
  38893. this._onbuttonup = callback;
  38894. };
  38895. Xbox360Pad.prototype.ondpaddown = function (callback) {
  38896. this._ondpaddown = callback;
  38897. };
  38898. Xbox360Pad.prototype.ondpadup = function (callback) {
  38899. this._ondpadup = callback;
  38900. };
  38901. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  38902. if (newValue !== currentValue) {
  38903. if (this._onbuttondown && newValue === 1) {
  38904. this._onbuttondown(buttonType);
  38905. }
  38906. if (this._onbuttonup && newValue === 0) {
  38907. this._onbuttonup(buttonType);
  38908. }
  38909. }
  38910. return newValue;
  38911. };
  38912. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  38913. if (newValue !== currentValue) {
  38914. if (this._ondpaddown && newValue === 1) {
  38915. this._ondpaddown(buttonType);
  38916. }
  38917. if (this._ondpadup && newValue === 0) {
  38918. this._ondpadup(buttonType);
  38919. }
  38920. }
  38921. return newValue;
  38922. };
  38923. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  38924. get: function () {
  38925. return this._buttonA;
  38926. },
  38927. set: function (value) {
  38928. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  38929. },
  38930. enumerable: true,
  38931. configurable: true
  38932. });
  38933. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  38934. get: function () {
  38935. return this._buttonB;
  38936. },
  38937. set: function (value) {
  38938. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  38939. },
  38940. enumerable: true,
  38941. configurable: true
  38942. });
  38943. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  38944. get: function () {
  38945. return this._buttonX;
  38946. },
  38947. set: function (value) {
  38948. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  38949. },
  38950. enumerable: true,
  38951. configurable: true
  38952. });
  38953. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  38954. get: function () {
  38955. return this._buttonY;
  38956. },
  38957. set: function (value) {
  38958. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  38959. },
  38960. enumerable: true,
  38961. configurable: true
  38962. });
  38963. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  38964. get: function () {
  38965. return this._buttonStart;
  38966. },
  38967. set: function (value) {
  38968. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  38969. },
  38970. enumerable: true,
  38971. configurable: true
  38972. });
  38973. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  38974. get: function () {
  38975. return this._buttonBack;
  38976. },
  38977. set: function (value) {
  38978. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  38979. },
  38980. enumerable: true,
  38981. configurable: true
  38982. });
  38983. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  38984. get: function () {
  38985. return this._buttonLB;
  38986. },
  38987. set: function (value) {
  38988. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  38989. },
  38990. enumerable: true,
  38991. configurable: true
  38992. });
  38993. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  38994. get: function () {
  38995. return this._buttonRB;
  38996. },
  38997. set: function (value) {
  38998. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  38999. },
  39000. enumerable: true,
  39001. configurable: true
  39002. });
  39003. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  39004. get: function () {
  39005. return this._buttonLeftStick;
  39006. },
  39007. set: function (value) {
  39008. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  39009. },
  39010. enumerable: true,
  39011. configurable: true
  39012. });
  39013. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  39014. get: function () {
  39015. return this._buttonRightStick;
  39016. },
  39017. set: function (value) {
  39018. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  39019. },
  39020. enumerable: true,
  39021. configurable: true
  39022. });
  39023. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  39024. get: function () {
  39025. return this._dPadUp;
  39026. },
  39027. set: function (value) {
  39028. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  39029. },
  39030. enumerable: true,
  39031. configurable: true
  39032. });
  39033. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  39034. get: function () {
  39035. return this._dPadDown;
  39036. },
  39037. set: function (value) {
  39038. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  39039. },
  39040. enumerable: true,
  39041. configurable: true
  39042. });
  39043. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  39044. get: function () {
  39045. return this._dPadLeft;
  39046. },
  39047. set: function (value) {
  39048. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  39049. },
  39050. enumerable: true,
  39051. configurable: true
  39052. });
  39053. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  39054. get: function () {
  39055. return this._dPadRight;
  39056. },
  39057. set: function (value) {
  39058. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  39059. },
  39060. enumerable: true,
  39061. configurable: true
  39062. });
  39063. Xbox360Pad.prototype.update = function () {
  39064. _super.prototype.update.call(this);
  39065. this.buttonA = this.browserGamepad.buttons[0].value;
  39066. this.buttonB = this.browserGamepad.buttons[1].value;
  39067. this.buttonX = this.browserGamepad.buttons[2].value;
  39068. this.buttonY = this.browserGamepad.buttons[3].value;
  39069. this.buttonLB = this.browserGamepad.buttons[4].value;
  39070. this.buttonRB = this.browserGamepad.buttons[5].value;
  39071. this.leftTrigger = this.browserGamepad.buttons[6].value;
  39072. this.rightTrigger = this.browserGamepad.buttons[7].value;
  39073. this.buttonBack = this.browserGamepad.buttons[8].value;
  39074. this.buttonStart = this.browserGamepad.buttons[9].value;
  39075. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  39076. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  39077. this.dPadUp = this.browserGamepad.buttons[12].value;
  39078. this.dPadDown = this.browserGamepad.buttons[13].value;
  39079. this.dPadLeft = this.browserGamepad.buttons[14].value;
  39080. this.dPadRight = this.browserGamepad.buttons[15].value;
  39081. };
  39082. return Xbox360Pad;
  39083. })(Gamepad);
  39084. BABYLON.Xbox360Pad = Xbox360Pad;
  39085. })(BABYLON || (BABYLON = {}));
  39086. var BABYLON;
  39087. (function (BABYLON) {
  39088. // We're mainly based on the logic defined into the FreeCamera code
  39089. var GamepadCamera = (function (_super) {
  39090. __extends(GamepadCamera, _super);
  39091. function GamepadCamera(name, position, scene) {
  39092. BABYLON.Tools.Warn("Deprecated. Please use Universal Camera instead.");
  39093. _super.call(this, name, position, scene);
  39094. }
  39095. GamepadCamera.prototype.getTypeName = function () {
  39096. return "GamepadCamera";
  39097. };
  39098. return GamepadCamera;
  39099. })(BABYLON.UniversalCamera);
  39100. BABYLON.GamepadCamera = GamepadCamera;
  39101. })(BABYLON || (BABYLON = {}));
  39102. var BABYLON;
  39103. (function (BABYLON) {
  39104. var AnaglyphFreeCamera = (function (_super) {
  39105. __extends(AnaglyphFreeCamera, _super);
  39106. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  39107. _super.call(this, name, position, scene);
  39108. this.interaxialDistance = interaxialDistance;
  39109. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  39110. }
  39111. AnaglyphFreeCamera.prototype.getTypeName = function () {
  39112. return "AnaglyphFreeCamera";
  39113. };
  39114. return AnaglyphFreeCamera;
  39115. })(BABYLON.FreeCamera);
  39116. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  39117. var AnaglyphArcRotateCamera = (function (_super) {
  39118. __extends(AnaglyphArcRotateCamera, _super);
  39119. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  39120. _super.call(this, name, alpha, beta, radius, target, scene);
  39121. this.interaxialDistance = interaxialDistance;
  39122. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  39123. }
  39124. AnaglyphArcRotateCamera.prototype.getTypeName = function () {
  39125. return "AnaglyphArcRotateCamera";
  39126. };
  39127. return AnaglyphArcRotateCamera;
  39128. })(BABYLON.ArcRotateCamera);
  39129. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  39130. var AnaglyphGamepadCamera = (function (_super) {
  39131. __extends(AnaglyphGamepadCamera, _super);
  39132. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  39133. _super.call(this, name, position, scene);
  39134. this.interaxialDistance = interaxialDistance;
  39135. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  39136. }
  39137. AnaglyphGamepadCamera.prototype.getTypeName = function () {
  39138. return "AnaglyphGamepadCamera";
  39139. };
  39140. return AnaglyphGamepadCamera;
  39141. })(BABYLON.GamepadCamera);
  39142. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  39143. var AnaglyphUniversalCamera = (function (_super) {
  39144. __extends(AnaglyphUniversalCamera, _super);
  39145. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  39146. _super.call(this, name, position, scene);
  39147. this.interaxialDistance = interaxialDistance;
  39148. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  39149. }
  39150. AnaglyphUniversalCamera.prototype.getTypeName = function () {
  39151. return "AnaglyphUniversalCamera";
  39152. };
  39153. return AnaglyphUniversalCamera;
  39154. })(BABYLON.UniversalCamera);
  39155. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  39156. var StereoscopicFreeCamera = (function (_super) {
  39157. __extends(StereoscopicFreeCamera, _super);
  39158. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  39159. _super.call(this, name, position, scene);
  39160. this.interaxialDistance = interaxialDistance;
  39161. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  39162. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  39163. }
  39164. StereoscopicFreeCamera.prototype.getTypeName = function () {
  39165. return "StereoscopicFreeCamera";
  39166. };
  39167. return StereoscopicFreeCamera;
  39168. })(BABYLON.FreeCamera);
  39169. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  39170. var StereoscopicArcRotateCamera = (function (_super) {
  39171. __extends(StereoscopicArcRotateCamera, _super);
  39172. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  39173. _super.call(this, name, alpha, beta, radius, target, scene);
  39174. this.interaxialDistance = interaxialDistance;
  39175. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  39176. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  39177. }
  39178. StereoscopicArcRotateCamera.prototype.getTypeName = function () {
  39179. return "StereoscopicArcRotateCamera";
  39180. };
  39181. return StereoscopicArcRotateCamera;
  39182. })(BABYLON.ArcRotateCamera);
  39183. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  39184. var StereoscopicGamepadCamera = (function (_super) {
  39185. __extends(StereoscopicGamepadCamera, _super);
  39186. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  39187. _super.call(this, name, position, scene);
  39188. this.interaxialDistance = interaxialDistance;
  39189. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  39190. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  39191. }
  39192. StereoscopicGamepadCamera.prototype.getTypeName = function () {
  39193. return "StereoscopicGamepadCamera";
  39194. };
  39195. return StereoscopicGamepadCamera;
  39196. })(BABYLON.GamepadCamera);
  39197. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  39198. var StereoscopicUniversalCamera = (function (_super) {
  39199. __extends(StereoscopicUniversalCamera, _super);
  39200. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  39201. _super.call(this, name, position, scene);
  39202. this.interaxialDistance = interaxialDistance;
  39203. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  39204. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  39205. }
  39206. StereoscopicUniversalCamera.prototype.getTypeName = function () {
  39207. return "StereoscopicUniversalCamera";
  39208. };
  39209. return StereoscopicUniversalCamera;
  39210. })(BABYLON.UniversalCamera);
  39211. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  39212. })(BABYLON || (BABYLON = {}));
  39213. //_______________________________________________________________
  39214. // Extracted from CubeMapGen:
  39215. // https://code.google.com/archive/p/cubemapgen/
  39216. //
  39217. // Following https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  39218. //_______________________________________________________________
  39219. var BABYLON;
  39220. (function (BABYLON) {
  39221. var Internals;
  39222. (function (Internals) {
  39223. var CMGBoundinBox = (function () {
  39224. function CMGBoundinBox() {
  39225. this.min = new BABYLON.Vector3(0, 0, 0);
  39226. this.max = new BABYLON.Vector3(0, 0, 0);
  39227. this.clear();
  39228. }
  39229. CMGBoundinBox.prototype.clear = function () {
  39230. this.min.x = CMGBoundinBox.MAX;
  39231. this.min.y = CMGBoundinBox.MAX;
  39232. this.min.z = CMGBoundinBox.MAX;
  39233. this.max.x = CMGBoundinBox.MIN;
  39234. this.max.y = CMGBoundinBox.MIN;
  39235. this.max.z = CMGBoundinBox.MIN;
  39236. };
  39237. CMGBoundinBox.prototype.augment = function (x, y, z) {
  39238. this.min.x = Math.min(this.min.x, x);
  39239. this.min.y = Math.min(this.min.y, y);
  39240. this.min.z = Math.min(this.min.z, z);
  39241. this.max.x = Math.max(this.max.x, x);
  39242. this.max.y = Math.max(this.max.y, y);
  39243. this.max.z = Math.max(this.max.z, z);
  39244. };
  39245. CMGBoundinBox.prototype.clampMin = function (x, y, z) {
  39246. this.min.x = Math.max(this.min.x, x);
  39247. this.min.y = Math.max(this.min.y, y);
  39248. this.min.z = Math.max(this.min.z, z);
  39249. };
  39250. CMGBoundinBox.prototype.clampMax = function (x, y, z) {
  39251. this.max.x = Math.min(this.max.x, x);
  39252. this.max.y = Math.min(this.max.y, y);
  39253. this.max.z = Math.min(this.max.z, z);
  39254. };
  39255. CMGBoundinBox.prototype.empty = function () {
  39256. if ((this.min.x > this.max.y) ||
  39257. (this.min.y > this.max.y) ||
  39258. (this.min.z > this.max.y)) {
  39259. return true;
  39260. }
  39261. else {
  39262. return false;
  39263. }
  39264. };
  39265. CMGBoundinBox.MAX = Number.MAX_VALUE;
  39266. CMGBoundinBox.MIN = Number.MIN_VALUE;
  39267. return CMGBoundinBox;
  39268. })();
  39269. var PMREMGenerator = (function () {
  39270. function PMREMGenerator(input, inputSize, outputSize, maxNumMipLevels, numChannels, isFloat, specularPower, cosinePowerDropPerMip, excludeBase, fixup) {
  39271. this.input = input;
  39272. this.inputSize = inputSize;
  39273. this.outputSize = outputSize;
  39274. this.maxNumMipLevels = maxNumMipLevels;
  39275. this.numChannels = numChannels;
  39276. this.isFloat = isFloat;
  39277. this.specularPower = specularPower;
  39278. this.cosinePowerDropPerMip = cosinePowerDropPerMip;
  39279. this.excludeBase = excludeBase;
  39280. this.fixup = fixup;
  39281. this._outputSurface = [];
  39282. this._numMipLevels = 0;
  39283. }
  39284. PMREMGenerator.prototype.filterCubeMap = function () {
  39285. // Init cubemap processor
  39286. this.init();
  39287. // Filters the cubemap
  39288. this.filterCubeMapMipChain();
  39289. // Returns the filtered mips.
  39290. return this._outputSurface;
  39291. };
  39292. PMREMGenerator.prototype.init = function () {
  39293. var i;
  39294. var j;
  39295. var mipLevelSize;
  39296. //if nax num mip levels is set to 0, set it to generate the entire mip chain
  39297. if (this.maxNumMipLevels == 0) {
  39298. this.maxNumMipLevels = PMREMGenerator.CP_MAX_MIPLEVELS;
  39299. }
  39300. //first miplevel size
  39301. mipLevelSize = this.outputSize;
  39302. //Iterate over mip chain, and init ArrayBufferView for mip-chain
  39303. for (j = 0; j < this.maxNumMipLevels; j++) {
  39304. this._outputSurface.length++;
  39305. this._outputSurface[j] = [];
  39306. //Iterate over faces for output images
  39307. for (i = 0; i < 6; i++) {
  39308. this._outputSurface[j].length++;
  39309. // Initializes a new array for the output.
  39310. if (this.isFloat) {
  39311. this._outputSurface[j][i] = new Float32Array(mipLevelSize * mipLevelSize * this.numChannels);
  39312. }
  39313. else {
  39314. this._outputSurface[j][i] = new Uint32Array(mipLevelSize * mipLevelSize * this.numChannels);
  39315. }
  39316. }
  39317. //next mip level is half size
  39318. mipLevelSize >>= 1;
  39319. this._numMipLevels++;
  39320. //terminate if mip chain becomes too small
  39321. if (mipLevelSize == 0) {
  39322. this.maxNumMipLevels = j;
  39323. return;
  39324. }
  39325. }
  39326. };
  39327. //--------------------------------------------------------------------------------------
  39328. //Cube map filtering and mip chain generation.
  39329. // the cube map filtereing is specified using a number of parameters:
  39330. // Filtering per miplevel is specified using 2D cone angle (in degrees) that
  39331. // indicates the region of the hemisphere to filter over for each tap.
  39332. //
  39333. // Note that the top mip level is also a filtered version of the original input images
  39334. // as well in order to create mip chains for diffuse environment illumination.
  39335. // The cone angle for the top level is specified by a_BaseAngle. This can be used to
  39336. // generate mipchains used to store the resutls of preintegration across the hemisphere.
  39337. //
  39338. // Then the mip angle used to genreate the next level of the mip chain from the first level
  39339. // is a_InitialMipAngle
  39340. //
  39341. // The angle for the subsequent levels of the mip chain are specified by their parents
  39342. // filtering angle and a per-level scale and bias
  39343. // newAngle = oldAngle * a_MipAnglePerLevelScale;
  39344. //
  39345. //--------------------------------------------------------------------------------------
  39346. PMREMGenerator.prototype.filterCubeMapMipChain = function () {
  39347. // First, take count of the lighting model to modify SpecularPower
  39348. // var refSpecularPower = (a_MCO.LightingModel == CP_LIGHTINGMODEL_BLINN || a_MCO.LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? a_MCO.SpecularPower / GetSpecularPowerFactorToMatchPhong(a_MCO.SpecularPower) : a_MCO.SpecularPower;
  39349. // var refSpecularPower = this.specularPower; // Only Phong BRDF yet. This explains the line below using this.specularpower.
  39350. //Cone angle start (for generating subsequent mip levels)
  39351. var currentSpecularPower = this.specularPower;
  39352. //Build filter lookup tables based on the source miplevel size
  39353. this.precomputeFilterLookupTables(this.inputSize);
  39354. // Note that we need to filter the first level before generating mipmap
  39355. // So LevelIndex == 0 is base filtering hen LevelIndex > 0 is mipmap generation
  39356. for (var levelIndex = 0; levelIndex < this._numMipLevels; levelIndex++) {
  39357. // TODO : Write a function to copy and scale the base mipmap in output
  39358. // I am just lazy here and just put a high specular power value, and do some if.
  39359. if (this.excludeBase && (levelIndex == 0)) {
  39360. // If we don't want to process the base mipmap, just put a very high specular power (this allow to handle scale of the texture).
  39361. currentSpecularPower = 100000.0;
  39362. }
  39363. // Special case for cosine power mipmap chain. For quality requirement, we always process the current mipmap from the top mipmap
  39364. var srcCubeImage = this.input;
  39365. var dstCubeImage = this._outputSurface[levelIndex];
  39366. var dstSize = this.outputSize >> levelIndex;
  39367. // Compute required angle.
  39368. var angle = this.getBaseFilterAngle(currentSpecularPower);
  39369. // filter cube surfaces
  39370. this.filterCubeSurfaces(srcCubeImage, this.inputSize, dstCubeImage, dstSize, angle, currentSpecularPower);
  39371. // fix seams
  39372. if (this.fixup) {
  39373. this.fixupCubeEdges(dstCubeImage, dstSize);
  39374. }
  39375. // Decrease the specular power to generate the mipmap chain
  39376. // TODO : Use another method for Exclude (see first comment at start of the function
  39377. if (this.excludeBase && (levelIndex == 0)) {
  39378. currentSpecularPower = this.specularPower;
  39379. }
  39380. currentSpecularPower *= this.cosinePowerDropPerMip;
  39381. }
  39382. };
  39383. //--------------------------------------------------------------------------------------
  39384. // This function return the BaseFilterAngle require by PMREMGenerator to its FilterExtends
  39385. // It allow to optimize the texel to access base on the specular power.
  39386. //--------------------------------------------------------------------------------------
  39387. PMREMGenerator.prototype.getBaseFilterAngle = function (cosinePower) {
  39388. // We want to find the alpha such that:
  39389. // cos(alpha)^cosinePower = epsilon
  39390. // That's: acos(epsilon^(1/cosinePower))
  39391. var threshold = 0.000001; // Empirical threshold (Work perfectly, didn't check for a more big number, may get some performance and still god approximation)
  39392. var angle = 180.0;
  39393. angle = Math.acos(Math.pow(threshold, 1.0 / cosinePower));
  39394. angle *= 180.0 / Math.PI; // Convert to degree
  39395. angle *= 2.0; // * 2.0f because PMREMGenerator divide by 2 later
  39396. return angle;
  39397. };
  39398. //--------------------------------------------------------------------------------------
  39399. //Builds the following lookup tables prior to filtering:
  39400. // -normalizer cube map
  39401. // -tap weight lookup table
  39402. //
  39403. //--------------------------------------------------------------------------------------
  39404. PMREMGenerator.prototype.precomputeFilterLookupTables = function (srcCubeMapWidth) {
  39405. var srcTexelAngle;
  39406. var iCubeFace;
  39407. //clear pre-existing normalizer cube map
  39408. this._normCubeMap = [];
  39409. //Normalized vectors per cubeface and per-texel solid angle
  39410. this.buildNormalizerSolidAngleCubemap(srcCubeMapWidth);
  39411. };
  39412. //--------------------------------------------------------------------------------------
  39413. //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component
  39414. //
  39415. //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into
  39416. //
  39417. //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range.
  39418. // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS
  39419. // below
  39420. //--------------------------------------------------------------------------------------
  39421. PMREMGenerator.prototype.buildNormalizerSolidAngleCubemap = function (size) {
  39422. var iCubeFace;
  39423. var u;
  39424. var v;
  39425. //iterate over cube faces
  39426. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  39427. //First three channels for norm cube, and last channel for solid angle
  39428. this._normCubeMap.push(new Float32Array(size * size * 4));
  39429. //fast texture walk, build normalizer cube map
  39430. var facesData = this.input[iCubeFace];
  39431. for (v = 0; v < size; v++) {
  39432. for (u = 0; u < size; u++) {
  39433. var vect = this.texelCoordToVect(iCubeFace, u, v, size, this.fixup);
  39434. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 0] = vect.x;
  39435. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 1] = vect.y;
  39436. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 2] = vect.z;
  39437. var solidAngle = this.texelCoordSolidAngle(iCubeFace, u, v, size);
  39438. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 4] = solidAngle;
  39439. }
  39440. }
  39441. }
  39442. };
  39443. //--------------------------------------------------------------------------------------
  39444. // Convert cubemap face texel coordinates and face idx to 3D vector
  39445. // note the U and V coords are integer coords and range from 0 to size-1
  39446. // this routine can be used to generate a normalizer cube map
  39447. //--------------------------------------------------------------------------------------
  39448. // SL BEGIN
  39449. PMREMGenerator.prototype.texelCoordToVect = function (faceIdx, u, v, size, fixup) {
  39450. var nvcU;
  39451. var nvcV;
  39452. var tempVec;
  39453. // Change from original AMD code
  39454. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  39455. // + 0.5f is for texel center addressing
  39456. nvcU = (2.0 * (u + 0.5) / size) - 1.0;
  39457. nvcV = (2.0 * (v + 0.5) / size) - 1.0;
  39458. // warp fixup
  39459. if (fixup && size > 1) {
  39460. // Code from Nvtt : http://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvtt/CubeSurface.cpp
  39461. var a = Math.pow(size, 2.0) / Math.pow(size - 1, 3.0);
  39462. nvcU = a * Math.pow(nvcU, 3) + nvcU;
  39463. nvcV = a * Math.pow(nvcV, 3) + nvcV;
  39464. }
  39465. // Get current vector
  39466. // generate x,y,z vector (xform 2d NVC coord to 3D vector)
  39467. // U contribution
  39468. var UVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  39469. PMREMGenerator._vectorTemp.x = UVec[0] * nvcU;
  39470. PMREMGenerator._vectorTemp.y = UVec[1] * nvcU;
  39471. PMREMGenerator._vectorTemp.z = UVec[2] * nvcU;
  39472. // V contribution and Sum
  39473. var VVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  39474. PMREMGenerator._vectorTemp.x += VVec[0] * nvcV;
  39475. PMREMGenerator._vectorTemp.y += VVec[1] * nvcV;
  39476. PMREMGenerator._vectorTemp.z += VVec[2] * nvcV;
  39477. //add face axis
  39478. var faceAxis = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_FACEAXIS];
  39479. PMREMGenerator._vectorTemp.x += faceAxis[0];
  39480. PMREMGenerator._vectorTemp.y += faceAxis[1];
  39481. PMREMGenerator._vectorTemp.z += faceAxis[2];
  39482. //normalize vector
  39483. PMREMGenerator._vectorTemp.normalize();
  39484. return PMREMGenerator._vectorTemp;
  39485. };
  39486. //--------------------------------------------------------------------------------------
  39487. // Convert 3D vector to cubemap face texel coordinates and face idx
  39488. // note the U and V coords are integer coords and range from 0 to size-1
  39489. // this routine can be used to generate a normalizer cube map
  39490. //
  39491. // returns face IDX and texel coords
  39492. //--------------------------------------------------------------------------------------
  39493. // SL BEGIN
  39494. /*
  39495. Mapping Texture Coordinates to Cube Map Faces
  39496. Because there are multiple faces, the mapping of texture coordinates to positions on cube map faces
  39497. is more complicated than the other texturing targets. The EXT_texture_cube_map extension is purposefully
  39498. designed to be consistent with DirectX 7's cube map arrangement. This is also consistent with the cube
  39499. map arrangement in Pixar's RenderMan package.
  39500. For cube map texturing, the (s,t,r) texture coordinates are treated as a direction vector (rx,ry,rz)
  39501. emanating from the center of a cube. (The q coordinate can be ignored since it merely scales the vector
  39502. without affecting the direction.) At texture application time, the interpolated per-fragment (s,t,r)
  39503. selects one of the cube map face's 2D mipmap sets based on the largest magnitude coordinate direction
  39504. the major axis direction). The target column in the table below explains how the major axis direction
  39505. maps to the 2D image of a particular cube map target.
  39506. major axis
  39507. direction target sc tc ma
  39508. ---------- --------------------------------- --- --- ---
  39509. +rx GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT -rz -ry rx
  39510. -rx GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT +rz -ry rx
  39511. +ry GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT +rx +rz ry
  39512. -ry GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT +rx -rz ry
  39513. +rz GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT +rx -ry rz
  39514. -rz GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT -rx -ry rz
  39515. Using the sc, tc, and ma determined by the major axis direction as specified in the table above,
  39516. an updated (s,t) is calculated as follows
  39517. s = ( sc/|ma| + 1 ) / 2
  39518. t = ( tc/|ma| + 1 ) / 2
  39519. If |ma| is zero or very nearly zero, the results of the above two equations need not be defined
  39520. (though the result may not lead to GL interruption or termination). Once the cube map face's 2D mipmap
  39521. set and (s,t) is determined, texture fetching and filtering proceeds like standard OpenGL 2D texturing.
  39522. */
  39523. // Note this method return U and V in range from 0 to size-1
  39524. // SL END
  39525. // Store the information in vector3 for convenience (faceindex, u, v)
  39526. PMREMGenerator.prototype.vectToTexelCoord = function (x, y, z, size) {
  39527. var maxCoord;
  39528. var faceIdx;
  39529. //absolute value 3
  39530. var absX = Math.abs(x);
  39531. var absY = Math.abs(y);
  39532. var absZ = Math.abs(z);
  39533. if (absX >= absY && absX >= absZ) {
  39534. maxCoord = absX;
  39535. if (x >= 0) {
  39536. faceIdx = PMREMGenerator.CP_FACE_X_POS;
  39537. }
  39538. else {
  39539. faceIdx = PMREMGenerator.CP_FACE_X_NEG;
  39540. }
  39541. }
  39542. else if (absY >= absX && absY >= absZ) {
  39543. maxCoord = absY;
  39544. if (y >= 0) {
  39545. faceIdx = PMREMGenerator.CP_FACE_Y_POS;
  39546. }
  39547. else {
  39548. faceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  39549. }
  39550. }
  39551. else {
  39552. maxCoord = absZ;
  39553. if (z >= 0) {
  39554. faceIdx = PMREMGenerator.CP_FACE_Z_POS;
  39555. }
  39556. else {
  39557. faceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  39558. }
  39559. }
  39560. //divide through by max coord so face vector lies on cube face
  39561. var scale = 1 / maxCoord;
  39562. x *= scale;
  39563. y *= scale;
  39564. z *= scale;
  39565. var temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  39566. var nvcU = temp[0] * x + temp[1] * y + temp[2] * z;
  39567. temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  39568. var nvcV = temp[0] * x + temp[1] * y + temp[2] * z;
  39569. // Modify original AMD code to return value from 0 to Size - 1
  39570. var u = Math.floor((size - 1) * 0.5 * (nvcU + 1.0));
  39571. var v = Math.floor((size - 1) * 0.5 * (nvcV + 1.0));
  39572. PMREMGenerator._vectorTemp.x = faceIdx;
  39573. PMREMGenerator._vectorTemp.y = u;
  39574. PMREMGenerator._vectorTemp.z = v;
  39575. return PMREMGenerator._vectorTemp;
  39576. };
  39577. //--------------------------------------------------------------------------------------
  39578. //Original code from Ignacio CastaÒo
  39579. // This formula is from Manne ÷hrstrˆm's thesis.
  39580. // Take two coordiantes in the range [-1, 1] that define a portion of a
  39581. // cube face and return the area of the projection of that portion on the
  39582. // surface of the sphere.
  39583. //--------------------------------------------------------------------------------------
  39584. PMREMGenerator.prototype.areaElement = function (x, y) {
  39585. return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
  39586. };
  39587. PMREMGenerator.prototype.texelCoordSolidAngle = function (faceIdx, u, v, size) {
  39588. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  39589. // (+ 0.5f is for texel center addressing)
  39590. u = (2.0 * (u + 0.5) / size) - 1.0;
  39591. v = (2.0 * (v + 0.5) / size) - 1.0;
  39592. // Shift from a demi texel, mean 1.0f / a_Size with U and V in [-1..1]
  39593. var invResolution = 1.0 / size;
  39594. // U and V are the -1..1 texture coordinate on the current face.
  39595. // Get projected area for this texel
  39596. var x0 = u - invResolution;
  39597. var y0 = v - invResolution;
  39598. var x1 = u + invResolution;
  39599. var y1 = v + invResolution;
  39600. var solidAngle = this.areaElement(x0, y0) - this.areaElement(x0, y1) - this.areaElement(x1, y0) + this.areaElement(x1, y1);
  39601. return solidAngle;
  39602. };
  39603. //--------------------------------------------------------------------------------------
  39604. //The key to the speed of these filtering routines is to quickly define a per-face
  39605. // bounding box of pixels which enclose all the taps in the filter kernel efficiently.
  39606. // Later these pixels are selectively processed based on their dot products to see if
  39607. // they reside within the filtering cone.
  39608. //
  39609. //This is done by computing the smallest per-texel angle to get a conservative estimate
  39610. // of the number of texels needed to be covered in width and height order to filter the
  39611. // region. the bounding box for the center taps face is defined first, and if the
  39612. // filtereing region bleeds onto the other faces, bounding boxes for the other faces are
  39613. // defined next
  39614. //--------------------------------------------------------------------------------------
  39615. PMREMGenerator.prototype.filterCubeSurfaces = function (srcCubeMap, srcSize, dstCubeMap, dstSize, filterConeAngle, specularPower) {
  39616. // note that pixels within these regions may be rejected
  39617. // based on the anlge
  39618. var iCubeFace;
  39619. var u;
  39620. var v;
  39621. // bounding box per face to specify region to process
  39622. var filterExtents = [];
  39623. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  39624. filterExtents.push(new CMGBoundinBox());
  39625. }
  39626. // min angle a src texel can cover (in degrees)
  39627. var srcTexelAngle = (180.0 / (Math.PI) * Math.atan2(1.0, srcSize));
  39628. // angle about center tap to define filter cone
  39629. // filter angle is 1/2 the cone angle
  39630. var filterAngle = filterConeAngle / 2.0;
  39631. //ensure filter angle is larger than a texel
  39632. if (filterAngle < srcTexelAngle) {
  39633. filterAngle = srcTexelAngle;
  39634. }
  39635. //ensure filter cone is always smaller than the hemisphere
  39636. if (filterAngle > 90.0) {
  39637. filterAngle = 90.0;
  39638. }
  39639. // the maximum number of texels in 1D the filter cone angle will cover
  39640. // used to determine bounding box size for filter extents
  39641. var filterSize = Math.ceil(filterAngle / srcTexelAngle);
  39642. // ensure conservative region always covers at least one texel
  39643. if (filterSize < 1) {
  39644. filterSize = 1;
  39645. }
  39646. // dotProdThresh threshold based on cone angle to determine whether or not taps
  39647. // reside within the cone angle
  39648. var dotProdThresh = Math.cos((Math.PI / 180.0) * filterAngle);
  39649. // process required faces
  39650. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  39651. //iterate over dst cube map face texel
  39652. for (v = 0; v < dstSize; v++) {
  39653. for (u = 0; u < dstSize; u++) {
  39654. //get center tap direction
  39655. var centerTapDir = this.texelCoordToVect(iCubeFace, u, v, dstSize, this.fixup).clone();
  39656. //clear old per-face filter extents
  39657. this.clearFilterExtents(filterExtents);
  39658. //define per-face filter extents
  39659. this.determineFilterExtents(centerTapDir, srcSize, filterSize, filterExtents);
  39660. //perform filtering of src faces using filter extents
  39661. var vect = this.processFilterExtents(centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower);
  39662. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 0] = vect.x;
  39663. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 1] = vect.y;
  39664. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 2] = vect.z;
  39665. }
  39666. }
  39667. }
  39668. };
  39669. //--------------------------------------------------------------------------------------
  39670. //Clear filter extents for the 6 cube map faces
  39671. //--------------------------------------------------------------------------------------
  39672. PMREMGenerator.prototype.clearFilterExtents = function (filterExtents) {
  39673. for (var iCubeFaces = 0; iCubeFaces < 6; iCubeFaces++) {
  39674. filterExtents[iCubeFaces].clear();
  39675. }
  39676. };
  39677. //--------------------------------------------------------------------------------------
  39678. //Define per-face bounding box filter extents
  39679. //
  39680. // These define conservative texel regions in each of the faces the filter can possibly
  39681. // process. When the pixels in the regions are actually processed, the dot product
  39682. // between the tap vector and the center tap vector is used to determine the weight of
  39683. // the tap and whether or not the tap is within the cone.
  39684. //
  39685. //--------------------------------------------------------------------------------------
  39686. PMREMGenerator.prototype.determineFilterExtents = function (centerTapDir, srcSize, bboxSize, filterExtents) {
  39687. //neighboring face and bleed over amount, and width of BBOX for
  39688. // left, right, top, and bottom edges of this face
  39689. var bleedOverAmount = [0, 0, 0, 0];
  39690. var bleedOverBBoxMin = [0, 0, 0, 0];
  39691. var bleedOverBBoxMax = [0, 0, 0, 0];
  39692. var neighborFace;
  39693. var neighborEdge;
  39694. var oppositeFaceIdx;
  39695. //get face idx, and u, v info from center tap dir
  39696. var result = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize);
  39697. var faceIdx = result.x;
  39698. var u = result.y;
  39699. var v = result.z;
  39700. //define bbox size within face
  39701. filterExtents[faceIdx].augment(u - bboxSize, v - bboxSize, 0);
  39702. filterExtents[faceIdx].augment(u + bboxSize, v + bboxSize, 0);
  39703. filterExtents[faceIdx].clampMin(0, 0, 0);
  39704. filterExtents[faceIdx].clampMax(srcSize - 1, srcSize - 1, 0);
  39705. //u and v extent in face corresponding to center tap
  39706. var minU = filterExtents[faceIdx].min.x;
  39707. var minV = filterExtents[faceIdx].min.y;
  39708. var maxU = filterExtents[faceIdx].max.x;
  39709. var maxV = filterExtents[faceIdx].max.y;
  39710. //bleed over amounts for face across u=0 edge (left)
  39711. bleedOverAmount[0] = (bboxSize - u);
  39712. bleedOverBBoxMin[0] = minV;
  39713. bleedOverBBoxMax[0] = maxV;
  39714. //bleed over amounts for face across u=1 edge (right)
  39715. bleedOverAmount[1] = (u + bboxSize) - (srcSize - 1);
  39716. bleedOverBBoxMin[1] = minV;
  39717. bleedOverBBoxMax[1] = maxV;
  39718. //bleed over to face across v=0 edge (up)
  39719. bleedOverAmount[2] = (bboxSize - v);
  39720. bleedOverBBoxMin[2] = minU;
  39721. bleedOverBBoxMax[2] = maxU;
  39722. //bleed over to face across v=1 edge (down)
  39723. bleedOverAmount[3] = (v + bboxSize) - (srcSize - 1);
  39724. bleedOverBBoxMin[3] = minU;
  39725. bleedOverBBoxMax[3] = maxU;
  39726. //compute bleed over regions in neighboring faces
  39727. for (var i = 0; i < 4; i++) {
  39728. if (bleedOverAmount[i] > 0) {
  39729. neighborFace = PMREMGenerator._sgCubeNgh[faceIdx][i][0];
  39730. neighborEdge = PMREMGenerator._sgCubeNgh[faceIdx][i][1];
  39731. //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to
  39732. // be flipped: the cases are
  39733. // if a left edge mates with a left or bottom edge on the neighbor
  39734. // if a top edge mates with a top or right edge on the neighbor
  39735. // if a right edge mates with a right or top edge on the neighbor
  39736. // if a bottom edge mates with a bottom or left edge on the neighbor
  39737. //Seeing as the edges are enumerated as follows
  39738. // left =0
  39739. // right =1
  39740. // top =2
  39741. // bottom =3
  39742. //
  39743. // so if the edge enums are the same, or the sum of the enums == 3,
  39744. // the bbox needs to be flipped
  39745. if ((i == neighborEdge) || ((i + neighborEdge) == 3)) {
  39746. bleedOverBBoxMin[i] = (srcSize - 1) - bleedOverBBoxMin[i];
  39747. bleedOverBBoxMax[i] = (srcSize - 1) - bleedOverBBoxMax[i];
  39748. }
  39749. //The way the bounding box is extended onto the neighboring face
  39750. // depends on which edge of neighboring face abuts with this one
  39751. switch (PMREMGenerator._sgCubeNgh[faceIdx][i][1]) {
  39752. case PMREMGenerator.CP_EDGE_LEFT:
  39753. filterExtents[neighborFace].augment(0, bleedOverBBoxMin[i], 0);
  39754. filterExtents[neighborFace].augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  39755. break;
  39756. case PMREMGenerator.CP_EDGE_RIGHT:
  39757. filterExtents[neighborFace].augment((srcSize - 1), bleedOverBBoxMin[i], 0);
  39758. filterExtents[neighborFace].augment((srcSize - 1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  39759. break;
  39760. case PMREMGenerator.CP_EDGE_TOP:
  39761. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], 0, 0);
  39762. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0);
  39763. break;
  39764. case PMREMGenerator.CP_EDGE_BOTTOM:
  39765. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], (srcSize - 1), 0);
  39766. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], (srcSize - 1) - bleedOverAmount[i], 0);
  39767. break;
  39768. }
  39769. //clamp filter extents in non-center tap faces to remain within surface
  39770. filterExtents[neighborFace].clampMin(0, 0, 0);
  39771. filterExtents[neighborFace].clampMax(srcSize - 1, srcSize - 1, 0);
  39772. }
  39773. //If the bleed over amount bleeds past the adjacent face onto the opposite face
  39774. // from the center tap face, then process the opposite face entirely for now.
  39775. //Note that the cases in which this happens, what usually happens is that
  39776. // more than one edge bleeds onto the opposite face, and the bounding box
  39777. // encompasses the entire cube map face.
  39778. if (bleedOverAmount[i] > srcSize) {
  39779. //determine opposite face
  39780. switch (faceIdx) {
  39781. case PMREMGenerator.CP_FACE_X_POS:
  39782. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_NEG;
  39783. break;
  39784. case PMREMGenerator.CP_FACE_X_NEG:
  39785. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_POS;
  39786. break;
  39787. case PMREMGenerator.CP_FACE_Y_POS:
  39788. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  39789. break;
  39790. case PMREMGenerator.CP_FACE_Y_NEG:
  39791. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_POS;
  39792. break;
  39793. case PMREMGenerator.CP_FACE_Z_POS:
  39794. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  39795. break;
  39796. case PMREMGenerator.CP_FACE_Z_NEG:
  39797. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_POS;
  39798. break;
  39799. default:
  39800. break;
  39801. }
  39802. //just encompass entire face for now
  39803. filterExtents[oppositeFaceIdx].augment(0, 0, 0);
  39804. filterExtents[oppositeFaceIdx].augment((srcSize - 1), (srcSize - 1), 0);
  39805. }
  39806. }
  39807. };
  39808. //--------------------------------------------------------------------------------------
  39809. //ProcessFilterExtents
  39810. // Process bounding box in each cube face
  39811. //
  39812. //--------------------------------------------------------------------------------------
  39813. PMREMGenerator.prototype.processFilterExtents = function (centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower) {
  39814. //accumulators are 64-bit floats in order to have the precision needed
  39815. // over a summation of a large number of pixels
  39816. var dstAccum = [0, 0, 0, 0];
  39817. var weightAccum = 0;
  39818. var k = 0;
  39819. var nSrcChannels = this.numChannels;
  39820. // norm cube map and srcCubeMap have same face width
  39821. var faceWidth = srcSize;
  39822. //amount to add to pointer to move to next scanline in images
  39823. var normCubePitch = faceWidth * 4; // 4 channels in normCubeMap.
  39824. var srcCubePitch = faceWidth * this.numChannels; // numChannels correponds to the cubemap number of channel
  39825. var IsPhongBRDF = 1; // Only works in Phong BRDF yet.
  39826. //(a_LightingModel == CP_LIGHTINGMODEL_PHONG_BRDF || a_LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? 1 : 0; // This value will be added to the specular power
  39827. // iterate over cubefaces
  39828. for (var iFaceIdx = 0; iFaceIdx < 6; iFaceIdx++) {
  39829. //if bbox is non empty
  39830. if (!filterExtents[iFaceIdx].empty()) {
  39831. var uStart = filterExtents[iFaceIdx].min.x;
  39832. var vStart = filterExtents[iFaceIdx].min.y;
  39833. var uEnd = filterExtents[iFaceIdx].max.x;
  39834. var vEnd = filterExtents[iFaceIdx].max.y;
  39835. var startIndexNormCubeMap = (4 * ((vStart * faceWidth) + uStart));
  39836. var startIndexSrcCubeMap = (this.numChannels * ((vStart * faceWidth) + uStart));
  39837. //note that <= is used to ensure filter extents always encompass at least one pixel if bbox is non empty
  39838. for (var v = vStart; v <= vEnd; v++) {
  39839. var normCubeRowWalk = 0;
  39840. var srcCubeRowWalk = 0;
  39841. for (var u = uStart; u <= uEnd; u++) {
  39842. //pointer to direction in cube map associated with texel
  39843. var texelVectX = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 0];
  39844. var texelVectY = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 1];
  39845. var texelVectZ = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 2];
  39846. //check dot product to see if texel is within cone
  39847. var tapDotProd = texelVectX * centerTapDir.x +
  39848. texelVectY * centerTapDir.y +
  39849. texelVectZ * centerTapDir.z;
  39850. if (tapDotProd >= dotProdThresh && tapDotProd > 0.0) {
  39851. //solid angle stored in 4th channel of normalizer/solid angle cube map
  39852. var weight = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 3];
  39853. // Here we decide if we use a Phong/Blinn or a Phong/Blinn BRDF.
  39854. // Phong/Blinn BRDF is just the Phong/Blinn model multiply by the cosine of the lambert law
  39855. // so just adding one to specularpower do the trick.
  39856. weight *= Math.pow(tapDotProd, (specularPower + IsPhongBRDF));
  39857. //iterate over channels
  39858. for (k = 0; k < nSrcChannels; k++) {
  39859. dstAccum[k] += weight * srcCubeMap[iFaceIdx][startIndexSrcCubeMap + srcCubeRowWalk];
  39860. srcCubeRowWalk++;
  39861. }
  39862. weightAccum += weight; //accumulate weight
  39863. }
  39864. else {
  39865. //step across source pixel
  39866. srcCubeRowWalk += nSrcChannels;
  39867. }
  39868. normCubeRowWalk += 4; // 4 channels per norm cube map.
  39869. }
  39870. startIndexNormCubeMap += normCubePitch;
  39871. startIndexSrcCubeMap += srcCubePitch;
  39872. }
  39873. }
  39874. }
  39875. //divide through by weights if weight is non zero
  39876. if (weightAccum != 0.0) {
  39877. PMREMGenerator._vectorTemp.x = (dstAccum[0] / weightAccum);
  39878. PMREMGenerator._vectorTemp.y = (dstAccum[1] / weightAccum);
  39879. PMREMGenerator._vectorTemp.z = (dstAccum[2] / weightAccum);
  39880. if (this.numChannels > 3) {
  39881. PMREMGenerator._vectorTemp.w = (dstAccum[3] / weightAccum);
  39882. }
  39883. }
  39884. else {
  39885. // otherwise sample nearest
  39886. // get face idx and u, v texel coordinate in face
  39887. var coord = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize).clone();
  39888. PMREMGenerator._vectorTemp.x = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 0];
  39889. PMREMGenerator._vectorTemp.y = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 1];
  39890. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 2];
  39891. if (this.numChannels > 3) {
  39892. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 3];
  39893. }
  39894. }
  39895. return PMREMGenerator._vectorTemp;
  39896. };
  39897. //--------------------------------------------------------------------------------------
  39898. // Fixup cube edges
  39899. //
  39900. // average texels on cube map faces across the edges
  39901. // WARP/BENT Method Only.
  39902. //--------------------------------------------------------------------------------------
  39903. PMREMGenerator.prototype.fixupCubeEdges = function (cubeMap, cubeMapSize) {
  39904. var k;
  39905. var j;
  39906. var i;
  39907. var iFace;
  39908. var iCorner = 0;
  39909. var cornerNumPtrs = [0, 0, 0, 0, 0, 0, 0, 0]; //indexed by corner and face idx
  39910. var faceCornerStartIndicies = [[], [], [], []]; //corner pointers for face keeping track of the face they belong to.
  39911. // note that if functionality to filter across the three texels for each corner, then
  39912. //indexed by corner and face idx. the array contains the face the start points belongs to.
  39913. var cornerPtr = [
  39914. [[], [], []],
  39915. [[], [], []],
  39916. [[], [], []],
  39917. [[], [], []],
  39918. [[], [], []],
  39919. [[], [], []],
  39920. [[], [], []],
  39921. [[], [], []]
  39922. ];
  39923. //if there is no fixup, or fixup width = 0, do nothing
  39924. if (cubeMapSize < 1) {
  39925. return;
  39926. }
  39927. //special case 1x1 cubemap, average face colors
  39928. if (cubeMapSize == 1) {
  39929. //iterate over channels
  39930. for (k = 0; k < this.numChannels; k++) {
  39931. var accum = 0.0;
  39932. //iterate over faces to accumulate face colors
  39933. for (iFace = 0; iFace < 6; iFace++) {
  39934. accum += cubeMap[iFace][k];
  39935. }
  39936. //compute average over 6 face colors
  39937. accum /= 6.0;
  39938. //iterate over faces to distribute face colors
  39939. for (iFace = 0; iFace < 6; iFace++) {
  39940. cubeMap[iFace][k] = accum;
  39941. }
  39942. }
  39943. return;
  39944. }
  39945. //iterate over faces to collect list of corner texel pointers
  39946. for (iFace = 0; iFace < 6; iFace++) {
  39947. //the 4 corner pointers for this face
  39948. faceCornerStartIndicies[0] = [iFace, 0];
  39949. faceCornerStartIndicies[1] = [iFace, ((cubeMapSize - 1) * this.numChannels)];
  39950. faceCornerStartIndicies[2] = [iFace, ((cubeMapSize) * (cubeMapSize - 1) * this.numChannels)];
  39951. faceCornerStartIndicies[3] = [iFace, ((((cubeMapSize) * (cubeMapSize - 1)) + (cubeMapSize - 1)) * this.numChannels)];
  39952. //iterate over face corners to collect cube corner pointers
  39953. for (iCorner = 0; iCorner < 4; iCorner++) {
  39954. var corner = PMREMGenerator._sgCubeCornerList[iFace][iCorner];
  39955. cornerPtr[corner][cornerNumPtrs[corner]] = faceCornerStartIndicies[iCorner];
  39956. cornerNumPtrs[corner]++;
  39957. }
  39958. }
  39959. //iterate over corners to average across corner tap values
  39960. for (iCorner = 0; iCorner < 8; iCorner++) {
  39961. for (k = 0; k < this.numChannels; k++) {
  39962. var cornerTapAccum = 0.0;
  39963. //iterate over corner texels and average results
  39964. for (i = 0; i < 3; i++) {
  39965. cornerTapAccum += cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k]; // Get in the cube map face the start point + channel.
  39966. }
  39967. //divide by 3 to compute average of corner tap values
  39968. cornerTapAccum *= (1.0 / 3.0);
  39969. //iterate over corner texels and average results
  39970. for (i = 0; i < 3; i++) {
  39971. cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k] = cornerTapAccum;
  39972. }
  39973. }
  39974. }
  39975. //iterate over the twelve edges of the cube to average across edges
  39976. for (i = 0; i < 12; i++) {
  39977. var face = PMREMGenerator._sgCubeEdgeList[i][0];
  39978. var edge = PMREMGenerator._sgCubeEdgeList[i][1];
  39979. var neighborFace = PMREMGenerator._sgCubeNgh[face][edge][0];
  39980. var neighborEdge = PMREMGenerator._sgCubeNgh[face][edge][1];
  39981. var edgeStartIndex = 0; // a_CubeMap[face].m_ImgData;
  39982. var neighborEdgeStartIndex = 0; // a_CubeMap[neighborFace].m_ImgData;
  39983. var edgeWalk = 0;
  39984. var neighborEdgeWalk = 0;
  39985. //Determine walking pointers based on edge type
  39986. // e.g. CP_EDGE_LEFT, CP_EDGE_RIGHT, CP_EDGE_TOP, CP_EDGE_BOTTOM
  39987. switch (edge) {
  39988. case PMREMGenerator.CP_EDGE_LEFT:
  39989. // no change to faceEdgeStartPtr
  39990. edgeWalk = this.numChannels * cubeMapSize;
  39991. break;
  39992. case PMREMGenerator.CP_EDGE_RIGHT:
  39993. edgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  39994. edgeWalk = this.numChannels * cubeMapSize;
  39995. break;
  39996. case PMREMGenerator.CP_EDGE_TOP:
  39997. // no change to faceEdgeStartPtr
  39998. edgeWalk = this.numChannels;
  39999. break;
  40000. case PMREMGenerator.CP_EDGE_BOTTOM:
  40001. edgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  40002. edgeWalk = this.numChannels;
  40003. break;
  40004. }
  40005. //For certain types of edge abutments, the neighbor edge walk needs to
  40006. // be flipped: the cases are
  40007. // if a left edge mates with a left or bottom edge on the neighbor
  40008. // if a top edge mates with a top or right edge on the neighbor
  40009. // if a right edge mates with a right or top edge on the neighbor
  40010. // if a bottom edge mates with a bottom or left edge on the neighbor
  40011. //Seeing as the edges are enumerated as follows
  40012. // left =0
  40013. // right =1
  40014. // top =2
  40015. // bottom =3
  40016. //
  40017. //If the edge enums are the same, or the sum of the enums == 3,
  40018. // the neighbor edge walk needs to be flipped
  40019. if ((edge == neighborEdge) || ((edge + neighborEdge) == 3)) {
  40020. switch (neighborEdge) {
  40021. case PMREMGenerator.CP_EDGE_LEFT:
  40022. neighborEdgeStartIndex += (cubeMapSize - 1) * (cubeMapSize) * this.numChannels;
  40023. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  40024. break;
  40025. case PMREMGenerator.CP_EDGE_RIGHT:
  40026. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  40027. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  40028. break;
  40029. case PMREMGenerator.CP_EDGE_TOP:
  40030. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  40031. neighborEdgeWalk = -this.numChannels;
  40032. break;
  40033. case PMREMGenerator.CP_EDGE_BOTTOM:
  40034. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  40035. neighborEdgeWalk = -this.numChannels;
  40036. break;
  40037. }
  40038. }
  40039. else {
  40040. //swapped direction neighbor edge walk
  40041. switch (neighborEdge) {
  40042. case PMREMGenerator.CP_EDGE_LEFT:
  40043. //no change to neighborEdgeStartPtr for this case since it points
  40044. // to the upper left corner already
  40045. neighborEdgeWalk = this.numChannels * cubeMapSize;
  40046. break;
  40047. case PMREMGenerator.CP_EDGE_RIGHT:
  40048. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  40049. neighborEdgeWalk = this.numChannels * cubeMapSize;
  40050. break;
  40051. case PMREMGenerator.CP_EDGE_TOP:
  40052. //no change to neighborEdgeStartPtr for this case since it points
  40053. // to the upper left corner already
  40054. neighborEdgeWalk = this.numChannels;
  40055. break;
  40056. case PMREMGenerator.CP_EDGE_BOTTOM:
  40057. neighborEdgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  40058. neighborEdgeWalk = this.numChannels;
  40059. break;
  40060. }
  40061. }
  40062. //Perform edge walk, to average across the 12 edges and smoothly propagate change to
  40063. //nearby neighborhood
  40064. //step ahead one texel on edge
  40065. edgeStartIndex += edgeWalk;
  40066. neighborEdgeStartIndex += neighborEdgeWalk;
  40067. // note that this loop does not process the corner texels, since they have already been
  40068. // averaged across faces across earlier
  40069. for (j = 1; j < (cubeMapSize - 1); j++) {
  40070. //for each set of taps along edge, average them
  40071. // and rewrite the results into the edges
  40072. for (k = 0; k < this.numChannels; k++) {
  40073. var edgeTap = cubeMap[face][edgeStartIndex + k];
  40074. var neighborEdgeTap = cubeMap[neighborFace][neighborEdgeStartIndex + k];
  40075. //compute average of tap intensity values
  40076. var avgTap = 0.5 * (edgeTap + neighborEdgeTap);
  40077. //propagate average of taps to edge taps
  40078. cubeMap[face][edgeStartIndex + k] = avgTap;
  40079. cubeMap[neighborFace][neighborEdgeStartIndex + k] = avgTap;
  40080. }
  40081. edgeStartIndex += edgeWalk;
  40082. neighborEdgeStartIndex += neighborEdgeWalk;
  40083. }
  40084. }
  40085. };
  40086. PMREMGenerator.CP_MAX_MIPLEVELS = 16;
  40087. PMREMGenerator.CP_UDIR = 0;
  40088. PMREMGenerator.CP_VDIR = 1;
  40089. PMREMGenerator.CP_FACEAXIS = 2;
  40090. //used to index cube faces
  40091. PMREMGenerator.CP_FACE_X_POS = 0;
  40092. PMREMGenerator.CP_FACE_X_NEG = 1;
  40093. PMREMGenerator.CP_FACE_Y_POS = 2;
  40094. PMREMGenerator.CP_FACE_Y_NEG = 3;
  40095. PMREMGenerator.CP_FACE_Z_POS = 4;
  40096. PMREMGenerator.CP_FACE_Z_NEG = 5;
  40097. //used to index image edges
  40098. // NOTE.. the actual number corresponding to the edge is important
  40099. // do not change these, or the code will break
  40100. //
  40101. // CP_EDGE_LEFT is u = 0
  40102. // CP_EDGE_RIGHT is u = width-1
  40103. // CP_EDGE_TOP is v = 0
  40104. // CP_EDGE_BOTTOM is v = height-1
  40105. PMREMGenerator.CP_EDGE_LEFT = 0;
  40106. PMREMGenerator.CP_EDGE_RIGHT = 1;
  40107. PMREMGenerator.CP_EDGE_TOP = 2;
  40108. PMREMGenerator.CP_EDGE_BOTTOM = 3;
  40109. //corners of CUBE map (P or N specifys if it corresponds to the
  40110. // positive or negative direction each of X, Y, and Z
  40111. PMREMGenerator.CP_CORNER_NNN = 0;
  40112. PMREMGenerator.CP_CORNER_NNP = 1;
  40113. PMREMGenerator.CP_CORNER_NPN = 2;
  40114. PMREMGenerator.CP_CORNER_NPP = 3;
  40115. PMREMGenerator.CP_CORNER_PNN = 4;
  40116. PMREMGenerator.CP_CORNER_PNP = 5;
  40117. PMREMGenerator.CP_CORNER_PPN = 6;
  40118. PMREMGenerator.CP_CORNER_PPP = 7;
  40119. PMREMGenerator._vectorTemp = new BABYLON.Vector4(0, 0, 0, 0);
  40120. //3x2 matrices that map cube map indexing vectors in 3d
  40121. // (after face selection and divide through by the
  40122. // _ABSOLUTE VALUE_ of the max coord)
  40123. // into NVC space
  40124. //Note this currently assumes the D3D cube face ordering and orientation
  40125. PMREMGenerator._sgFace2DMapping = [
  40126. //XPOS face
  40127. [[0, 0, -1],
  40128. [0, -1, 0],
  40129. [1, 0, 0]],
  40130. //XNEG face
  40131. [[0, 0, 1],
  40132. [0, -1, 0],
  40133. [-1, 0, 0]],
  40134. //YPOS face
  40135. [[1, 0, 0],
  40136. [0, 0, 1],
  40137. [0, 1, 0]],
  40138. //YNEG face
  40139. [[1, 0, 0],
  40140. [0, 0, -1],
  40141. [0, -1, 0]],
  40142. //ZPOS face
  40143. [[1, 0, 0],
  40144. [0, -1, 0],
  40145. [0, 0, 1]],
  40146. //ZNEG face
  40147. [[-1, 0, 0],
  40148. [0, -1, 0],
  40149. [0, 0, -1]],
  40150. ];
  40151. //------------------------------------------------------------------------------
  40152. // D3D cube map face specification
  40153. // mapping from 3D x,y,z cube map lookup coordinates
  40154. // to 2D within face u,v coordinates
  40155. //
  40156. // --------------------> U direction
  40157. // | (within-face texture space)
  40158. // | _____
  40159. // | | |
  40160. // | | +Y |
  40161. // | _____|_____|_____ _____
  40162. // | | | | | |
  40163. // | | -X | +Z | +X | -Z |
  40164. // | |_____|_____|_____|_____|
  40165. // | | |
  40166. // | | -Y |
  40167. // | |_____|
  40168. // |
  40169. // v V direction
  40170. // (within-face texture space)
  40171. //------------------------------------------------------------------------------
  40172. //Information about neighbors and how texture coorrdinates change across faces
  40173. // in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0,
  40174. // u=1, v=0, v=1 in the 2D coordinate system of the particular face.
  40175. //Note this currently assumes the D3D cube face ordering and orientation
  40176. PMREMGenerator._sgCubeNgh = [
  40177. //XPOS face
  40178. [[PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_RIGHT],
  40179. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_LEFT],
  40180. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_RIGHT],
  40181. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_RIGHT]],
  40182. //XNEG face
  40183. [[PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  40184. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_LEFT],
  40185. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_LEFT],
  40186. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_LEFT]],
  40187. //YPOS face
  40188. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  40189. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  40190. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  40191. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP]],
  40192. //YNEG face
  40193. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  40194. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  40195. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  40196. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]],
  40197. //ZPOS face
  40198. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  40199. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  40200. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  40201. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_TOP]],
  40202. //ZNEG face
  40203. [[PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  40204. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  40205. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_TOP],
  40206. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_BOTTOM]]
  40207. ];
  40208. //The 12 edges of the cubemap, (entries are used to index into the neighbor table)
  40209. // this table is used to average over the edges.
  40210. PMREMGenerator._sgCubeEdgeList = [
  40211. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  40212. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  40213. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  40214. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  40215. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  40216. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  40217. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  40218. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  40219. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP],
  40220. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  40221. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  40222. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]
  40223. ];
  40224. //Information about which of the 8 cube corners are correspond to the
  40225. // the 4 corners in each cube face
  40226. // the order is upper left, upper right, lower left, lower right
  40227. PMREMGenerator._sgCubeCornerList = [
  40228. [PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_PNN],
  40229. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_NNP],
  40230. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP],
  40231. [PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_PNN],
  40232. [PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP],
  40233. [PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PNN, PMREMGenerator.CP_CORNER_NNN] // ZNEG face
  40234. ];
  40235. return PMREMGenerator;
  40236. })();
  40237. Internals.PMREMGenerator = PMREMGenerator;
  40238. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  40239. })(BABYLON || (BABYLON = {}));
  40240. var BABYLON;
  40241. (function (BABYLON) {
  40242. var Internals;
  40243. (function (Internals) {
  40244. var FileFaceOrientation = (function () {
  40245. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  40246. this.name = name;
  40247. this.worldAxisForNormal = worldAxisForNormal;
  40248. this.worldAxisForFileX = worldAxisForFileX;
  40249. this.worldAxisForFileY = worldAxisForFileY;
  40250. }
  40251. return FileFaceOrientation;
  40252. })();
  40253. ;
  40254. var CubeMapToSphericalPolynomialTools = (function () {
  40255. function CubeMapToSphericalPolynomialTools() {
  40256. }
  40257. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  40258. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  40259. var totalSolidAngle = 0.0;
  40260. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  40261. var du = 2.0 / cubeInfo.size;
  40262. var dv = du;
  40263. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  40264. var minUV = du * 0.5 - 1.0;
  40265. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  40266. var fileFace = this.FileFaces[faceIndex];
  40267. var dataArray = cubeInfo[fileFace.name];
  40268. var v = minUV;
  40269. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  40270. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  40271. // Because SP is still linear, so summation is fine in that basis.
  40272. for (var y = 0; y < cubeInfo.size; y++) {
  40273. var u = minUV;
  40274. for (var x = 0; x < cubeInfo.size; x++) {
  40275. // World direction (not normalised)
  40276. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  40277. worldDirection.normalize();
  40278. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  40279. if (1) {
  40280. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  40281. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  40282. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  40283. var color = new BABYLON.Color3(r, g, b);
  40284. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  40285. }
  40286. else {
  40287. if (faceIndex == 0) {
  40288. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  40289. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  40290. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  40291. }
  40292. else if (faceIndex == 1) {
  40293. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  40294. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  40295. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  40296. }
  40297. else if (faceIndex == 2) {
  40298. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  40299. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  40300. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  40301. }
  40302. else if (faceIndex == 3) {
  40303. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  40304. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  40305. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  40306. }
  40307. else if (faceIndex == 4) {
  40308. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  40309. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  40310. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  40311. }
  40312. else if (faceIndex == 5) {
  40313. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  40314. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  40315. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  40316. }
  40317. 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]);
  40318. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  40319. }
  40320. totalSolidAngle += deltaSolidAngle;
  40321. u += du;
  40322. }
  40323. v += dv;
  40324. }
  40325. }
  40326. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  40327. var correction = correctSolidAngle / totalSolidAngle;
  40328. sphericalHarmonics.scale(correction);
  40329. // Additionally scale by pi -- audit needed
  40330. sphericalHarmonics.scale(1.0 / Math.PI);
  40331. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  40332. };
  40333. CubeMapToSphericalPolynomialTools.FileFaces = [
  40334. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  40335. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  40336. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  40337. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  40338. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  40339. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  40340. ];
  40341. return CubeMapToSphericalPolynomialTools;
  40342. })();
  40343. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  40344. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  40345. })(BABYLON || (BABYLON = {}));
  40346. var BABYLON;
  40347. (function (BABYLON) {
  40348. var Internals;
  40349. (function (Internals) {
  40350. var PanoramaToCubeMapTools = (function () {
  40351. function PanoramaToCubeMapTools() {
  40352. }
  40353. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  40354. if (!float32Array) {
  40355. throw "ConvertPanoramaToCubemap: input cannot be null";
  40356. }
  40357. if (float32Array.length != inputWidth * inputHeight * 3) {
  40358. throw "ConvertPanoramaToCubemap: input size is wrong";
  40359. }
  40360. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  40361. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  40362. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  40363. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  40364. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  40365. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  40366. return {
  40367. front: textureFront,
  40368. back: textureBack,
  40369. left: textureLeft,
  40370. right: textureRight,
  40371. up: textureUp,
  40372. down: textureDown,
  40373. size: size
  40374. };
  40375. };
  40376. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  40377. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  40378. var textureArray = new Float32Array(buffer);
  40379. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  40380. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  40381. var dy = 1 / texSize;
  40382. var fy = 0;
  40383. for (var y = 0; y < texSize; y++) {
  40384. var xv1 = faceData[0];
  40385. var xv2 = faceData[2];
  40386. for (var x = 0; x < texSize; x++) {
  40387. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  40388. v.normalize();
  40389. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  40390. // 3 channels per pixels
  40391. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  40392. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  40393. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  40394. xv1 = xv1.add(rotDX1);
  40395. xv2 = xv2.add(rotDX2);
  40396. }
  40397. fy += dy;
  40398. }
  40399. return textureArray;
  40400. };
  40401. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  40402. var theta = Math.atan2(vDir.z, vDir.x);
  40403. var phi = Math.acos(vDir.y);
  40404. while (theta < -Math.PI)
  40405. theta += 2 * Math.PI;
  40406. while (theta > Math.PI)
  40407. theta -= 2 * Math.PI;
  40408. var dx = theta / Math.PI;
  40409. var dy = phi / Math.PI;
  40410. // recenter.
  40411. dx = dx * 0.5 + 0.5;
  40412. var px = Math.round(dx * inputWidth);
  40413. if (px < 0)
  40414. px = 0;
  40415. else if (px >= inputWidth)
  40416. px = inputWidth - 1;
  40417. var py = Math.round(dy * inputHeight);
  40418. if (py < 0)
  40419. py = 0;
  40420. else if (py >= inputHeight)
  40421. py = inputHeight - 1;
  40422. var inputY = (inputHeight - py - 1);
  40423. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  40424. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  40425. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  40426. return {
  40427. r: r,
  40428. g: g,
  40429. b: b
  40430. };
  40431. };
  40432. PanoramaToCubeMapTools.FACE_FRONT = [
  40433. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  40434. new BABYLON.Vector3(1.0, -1.0, -1.0),
  40435. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  40436. new BABYLON.Vector3(1.0, 1.0, -1.0)
  40437. ];
  40438. PanoramaToCubeMapTools.FACE_BACK = [
  40439. new BABYLON.Vector3(1.0, -1.0, 1.0),
  40440. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  40441. new BABYLON.Vector3(1.0, 1.0, 1.0),
  40442. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  40443. ];
  40444. PanoramaToCubeMapTools.FACE_RIGHT = [
  40445. new BABYLON.Vector3(1.0, -1.0, -1.0),
  40446. new BABYLON.Vector3(1.0, -1.0, 1.0),
  40447. new BABYLON.Vector3(1.0, 1.0, -1.0),
  40448. new BABYLON.Vector3(1.0, 1.0, 1.0)
  40449. ];
  40450. PanoramaToCubeMapTools.FACE_LEFT = [
  40451. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  40452. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  40453. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  40454. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  40455. ];
  40456. PanoramaToCubeMapTools.FACE_DOWN = [
  40457. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  40458. new BABYLON.Vector3(1.0, 1.0, -1.0),
  40459. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  40460. new BABYLON.Vector3(1.0, 1.0, 1.0)
  40461. ];
  40462. PanoramaToCubeMapTools.FACE_UP = [
  40463. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  40464. new BABYLON.Vector3(1.0, -1.0, 1.0),
  40465. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  40466. new BABYLON.Vector3(1.0, -1.0, -1.0)
  40467. ];
  40468. return PanoramaToCubeMapTools;
  40469. })();
  40470. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  40471. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  40472. })(BABYLON || (BABYLON = {}));
  40473. var BABYLON;
  40474. (function (BABYLON) {
  40475. var Internals;
  40476. (function (Internals) {
  40477. ;
  40478. var HDRTools = (function () {
  40479. function HDRTools() {
  40480. }
  40481. HDRTools.Ldexp = function (mantissa, exponent) {
  40482. if (exponent > 1023) {
  40483. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  40484. }
  40485. if (exponent < -1074) {
  40486. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  40487. }
  40488. return mantissa * Math.pow(2, exponent);
  40489. };
  40490. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  40491. if (exponent > 0) {
  40492. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  40493. float32array[index + 0] = red * exponent;
  40494. float32array[index + 1] = green * exponent;
  40495. float32array[index + 2] = blue * exponent;
  40496. }
  40497. else {
  40498. float32array[index + 0] = 0;
  40499. float32array[index + 1] = 0;
  40500. float32array[index + 2] = 0;
  40501. }
  40502. };
  40503. HDRTools.readStringLine = function (uint8array, startIndex) {
  40504. var line = "";
  40505. var character = "";
  40506. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  40507. character = String.fromCharCode(uint8array[i]);
  40508. if (character == "\n") {
  40509. break;
  40510. }
  40511. line += character;
  40512. }
  40513. return line;
  40514. };
  40515. /* minimal header reading. modify if you want to parse more information */
  40516. HDRTools.RGBE_ReadHeader = function (uint8array) {
  40517. var height = 0;
  40518. var width = 0;
  40519. var line = this.readStringLine(uint8array, 0);
  40520. if (line[0] != '#' || line[1] != '?') {
  40521. throw "Bad HDR Format.";
  40522. }
  40523. var endOfHeader = false;
  40524. var findFormat = false;
  40525. var lineIndex = 0;
  40526. do {
  40527. lineIndex += (line.length + 1);
  40528. line = this.readStringLine(uint8array, lineIndex);
  40529. if (line == "FORMAT=32-bit_rle_rgbe") {
  40530. findFormat = true;
  40531. }
  40532. else if (line.length == 0) {
  40533. endOfHeader = true;
  40534. }
  40535. } while (!endOfHeader);
  40536. if (!findFormat) {
  40537. throw "HDR Bad header format, unsupported FORMAT";
  40538. }
  40539. lineIndex += (line.length + 1);
  40540. line = this.readStringLine(uint8array, lineIndex);
  40541. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  40542. var match = sizeRegexp.exec(line);
  40543. // TODO. Support +Y and -X if needed.
  40544. if (match.length < 3) {
  40545. throw "HDR Bad header format, no size";
  40546. }
  40547. width = parseInt(match[2]);
  40548. height = parseInt(match[1]);
  40549. if (width < 8 || width > 0x7fff) {
  40550. throw "HDR Bad header format, unsupported size";
  40551. }
  40552. lineIndex += (line.length + 1);
  40553. return {
  40554. height: height,
  40555. width: width,
  40556. dataPosition: lineIndex
  40557. };
  40558. };
  40559. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  40560. var uint8array = new Uint8Array(buffer);
  40561. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  40562. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  40563. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  40564. return cubeMapData;
  40565. };
  40566. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  40567. // Keep for multi format supports.
  40568. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  40569. };
  40570. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  40571. var num_scanlines = hdrInfo.height;
  40572. var scanline_width = hdrInfo.width;
  40573. var a, b, c, d, count;
  40574. var dataIndex = hdrInfo.dataPosition;
  40575. var index = 0, endIndex = 0, i = 0;
  40576. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  40577. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  40578. // 3 channels of 4 bytes per pixel in float.
  40579. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  40580. var resultArray = new Float32Array(resultBuffer);
  40581. // read in each successive scanline
  40582. while (num_scanlines > 0) {
  40583. a = uint8array[dataIndex++];
  40584. b = uint8array[dataIndex++];
  40585. c = uint8array[dataIndex++];
  40586. d = uint8array[dataIndex++];
  40587. if (a != 2 || b != 2 || (c & 0x80)) {
  40588. // this file is not run length encoded
  40589. throw "HDR Bad header format, not RLE";
  40590. }
  40591. if (((c << 8) | d) != scanline_width) {
  40592. throw "HDR Bad header format, wrong scan line width";
  40593. }
  40594. index = 0;
  40595. // read each of the four channels for the scanline into the buffer
  40596. for (i = 0; i < 4; i++) {
  40597. endIndex = (i + 1) * scanline_width;
  40598. while (index < endIndex) {
  40599. a = uint8array[dataIndex++];
  40600. b = uint8array[dataIndex++];
  40601. if (a > 128) {
  40602. // a run of the same value
  40603. count = a - 128;
  40604. if ((count == 0) || (count > endIndex - index)) {
  40605. throw "HDR Bad Format, bad scanline data (run)";
  40606. }
  40607. while (count-- > 0) {
  40608. scanLineArray[index++] = b;
  40609. }
  40610. }
  40611. else {
  40612. // a non-run
  40613. count = a;
  40614. if ((count == 0) || (count > endIndex - index)) {
  40615. throw "HDR Bad Format, bad scanline data (non-run)";
  40616. }
  40617. scanLineArray[index++] = b;
  40618. if (--count > 0) {
  40619. for (var j = 0; j < count; j++) {
  40620. scanLineArray[index++] = uint8array[dataIndex++];
  40621. }
  40622. }
  40623. }
  40624. }
  40625. }
  40626. // now convert data from buffer into floats
  40627. for (i = 0; i < scanline_width; i++) {
  40628. a = scanLineArray[i];
  40629. b = scanLineArray[i + scanline_width];
  40630. c = scanLineArray[i + 2 * scanline_width];
  40631. d = scanLineArray[i + 3 * scanline_width];
  40632. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  40633. }
  40634. num_scanlines--;
  40635. }
  40636. return resultArray;
  40637. };
  40638. return HDRTools;
  40639. })();
  40640. Internals.HDRTools = HDRTools;
  40641. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  40642. })(BABYLON || (BABYLON = {}));
  40643. var BABYLON;
  40644. (function (BABYLON) {
  40645. var HDRCubeTexture = (function (_super) {
  40646. __extends(HDRCubeTexture, _super);
  40647. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  40648. if (noMipmap === void 0) { noMipmap = false; }
  40649. if (generateHarmonics === void 0) { generateHarmonics = true; }
  40650. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  40651. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  40652. _super.call(this, scene);
  40653. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  40654. this._useInGammaSpace = false;
  40655. this._generateHarmonics = true;
  40656. this.sphericalPolynomial = null;
  40657. this.isPMREM = false;
  40658. this.name = url;
  40659. this.url = url;
  40660. this._noMipmap = noMipmap;
  40661. this.hasAlpha = false;
  40662. this._size = size;
  40663. this._useInGammaSpace = useInGammaSpace;
  40664. this._usePMREMGenerator = usePMREMGenerator && scene.getEngine().getCaps().textureLOD;
  40665. this.isPMREM = this._usePMREMGenerator;
  40666. if (!url) {
  40667. return;
  40668. }
  40669. this._texture = this._getFromCache(url, noMipmap);
  40670. if (!this._texture) {
  40671. if (!scene.useDelayedTextureLoading) {
  40672. this.loadTexture();
  40673. }
  40674. else {
  40675. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  40676. }
  40677. }
  40678. this.isCube = true;
  40679. this._textureMatrix = BABYLON.Matrix.Identity();
  40680. }
  40681. HDRCubeTexture.prototype.loadTexture = function () {
  40682. var _this = this;
  40683. var callback = function (buffer) {
  40684. // Extract the raw linear data.
  40685. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  40686. // Generate harmonics if needed.
  40687. if (_this._generateHarmonics) {
  40688. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  40689. }
  40690. var results = [];
  40691. var byteArray = null;
  40692. // Create uintarray fallback.
  40693. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  40694. // 3 channels of 1 bytes per pixel in bytes.
  40695. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  40696. byteArray = new Uint8Array(byteBuffer);
  40697. }
  40698. // Push each faces.
  40699. for (var j = 0; j < 6; j++) {
  40700. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  40701. // If special cases.
  40702. if (_this._useInGammaSpace || byteArray) {
  40703. for (var i = 0; i < _this._size * _this._size; i++) {
  40704. // Put in gamma space if requested.
  40705. if (_this._useInGammaSpace) {
  40706. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  40707. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  40708. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  40709. }
  40710. // Convert to int texture for fallback.
  40711. if (byteArray) {
  40712. // R
  40713. byteArray[(i * 3) + 0] = dataFace[(i * 3) + 0] * 255;
  40714. byteArray[(i * 3) + 0] = Math.min(255, byteArray[(i * 3) + 0]);
  40715. // G
  40716. byteArray[(i * 3) + 1] = dataFace[(i * 3) + 1] * 255;
  40717. byteArray[(i * 3) + 1] = Math.min(255, byteArray[(i * 3) + 1]);
  40718. // B
  40719. byteArray[(i * 3) + 2] = dataFace[(i * 3) + 2] * 255;
  40720. byteArray[(i * 3) + 2] = Math.min(255, byteArray[(i * 3) + 2]);
  40721. }
  40722. }
  40723. }
  40724. results.push(dataFace);
  40725. }
  40726. return results;
  40727. };
  40728. var mipmapGenerator = null;
  40729. if (!this._noMipmap && this._usePMREMGenerator) {
  40730. mipmapGenerator = function (data) {
  40731. var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
  40732. return generator.filterCubeMap();
  40733. };
  40734. }
  40735. this._texture = this.getScene().getEngine().createRawCubeTexture(this.url, this.getScene(), this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, BABYLON.Engine.TEXTURETYPE_FLOAT, this._noMipmap, callback, mipmapGenerator);
  40736. };
  40737. HDRCubeTexture.prototype.clone = function () {
  40738. var newTexture = new HDRCubeTexture(this.url, this.getScene(), this._size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  40739. // Base texture
  40740. newTexture.level = this.level;
  40741. newTexture.wrapU = this.wrapU;
  40742. newTexture.wrapV = this.wrapV;
  40743. newTexture.coordinatesIndex = this.coordinatesIndex;
  40744. newTexture.coordinatesMode = this.coordinatesMode;
  40745. return newTexture;
  40746. };
  40747. // Methods
  40748. HDRCubeTexture.prototype.delayLoad = function () {
  40749. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  40750. return;
  40751. }
  40752. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  40753. this._texture = this._getFromCache(this.url, this._noMipmap);
  40754. if (!this._texture) {
  40755. this.loadTexture();
  40756. }
  40757. };
  40758. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  40759. return this._textureMatrix;
  40760. };
  40761. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  40762. var texture = null;
  40763. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  40764. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, texture.generateHarmonics, texture.useInGammaSpace, texture.usePMREMGenerator);
  40765. texture.name = parsedTexture.name;
  40766. texture.hasAlpha = parsedTexture.hasAlpha;
  40767. texture.level = parsedTexture.level;
  40768. texture.coordinatesMode = parsedTexture.coordinatesMode;
  40769. }
  40770. return texture;
  40771. };
  40772. HDRCubeTexture.prototype.serialize = function () {
  40773. if (!this.name) {
  40774. return null;
  40775. }
  40776. var serializationObject = {};
  40777. serializationObject.name = this.name;
  40778. serializationObject.hasAlpha = this.hasAlpha;
  40779. serializationObject.isCube = true;
  40780. serializationObject.level = this.level;
  40781. serializationObject.size = this._size;
  40782. serializationObject.coordinatesMode = this.coordinatesMode;
  40783. serializationObject.useInGammaSpace = this._useInGammaSpace;
  40784. serializationObject.generateHarmonics = this._generateHarmonics;
  40785. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  40786. return serializationObject;
  40787. };
  40788. HDRCubeTexture._facesMapping = [
  40789. "right",
  40790. "up",
  40791. "front",
  40792. "left",
  40793. "down",
  40794. "back"
  40795. ];
  40796. return HDRCubeTexture;
  40797. })(BABYLON.BaseTexture);
  40798. BABYLON.HDRCubeTexture = HDRCubeTexture;
  40799. })(BABYLON || (BABYLON = {}));
  40800. var BABYLON;
  40801. (function (BABYLON) {
  40802. var Debug;
  40803. (function (Debug) {
  40804. /**
  40805. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  40806. */
  40807. var SkeletonViewer = (function () {
  40808. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  40809. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  40810. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  40811. this.skeleton = skeleton;
  40812. this.mesh = mesh;
  40813. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  40814. this.renderingGroupId = renderingGroupId;
  40815. this.color = BABYLON.Color3.White();
  40816. this._debugLines = [];
  40817. this._isEnabled = false;
  40818. this._scene = scene;
  40819. this.update();
  40820. this._renderFunction = this.update.bind(this);
  40821. }
  40822. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  40823. get: function () {
  40824. return this._isEnabled;
  40825. },
  40826. set: function (value) {
  40827. if (this._isEnabled === value) {
  40828. return;
  40829. }
  40830. this._isEnabled = value;
  40831. if (value) {
  40832. this._scene.registerBeforeRender(this._renderFunction);
  40833. }
  40834. else {
  40835. this._scene.unregisterBeforeRender(this._renderFunction);
  40836. }
  40837. },
  40838. enumerable: true,
  40839. configurable: true
  40840. });
  40841. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  40842. if (x === void 0) { x = 0; }
  40843. if (y === void 0) { y = 0; }
  40844. if (z === void 0) { z = 0; }
  40845. var tmat = BABYLON.Tmp.Matrix[0];
  40846. var parentBone = bone.getParent();
  40847. tmat.copyFrom(bone.getLocalMatrix());
  40848. if (x !== 0 || y !== 0 || z !== 0) {
  40849. var tmat2 = BABYLON.Tmp.Matrix[1];
  40850. BABYLON.Matrix.IdentityToRef(tmat2);
  40851. tmat2.m[12] = x;
  40852. tmat2.m[13] = y;
  40853. tmat2.m[14] = z;
  40854. tmat2.multiplyToRef(tmat, tmat);
  40855. }
  40856. if (parentBone) {
  40857. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  40858. }
  40859. tmat.multiplyToRef(meshMat, tmat);
  40860. position.x = tmat.m[12];
  40861. position.y = tmat.m[13];
  40862. position.z = tmat.m[14];
  40863. };
  40864. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  40865. var len = bones.length;
  40866. for (var i = 0; i < len; i++) {
  40867. var bone = bones[i];
  40868. var points = this._debugLines[i];
  40869. if (!points) {
  40870. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  40871. this._debugLines[i] = points;
  40872. }
  40873. this._getBonePosition(points[0], bone, meshMat);
  40874. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  40875. }
  40876. };
  40877. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  40878. var len = bones.length;
  40879. var boneNum = 0;
  40880. for (var i = len - 1; i >= 0; i--) {
  40881. var childBone = bones[i];
  40882. var parentBone = childBone.getParent();
  40883. if (!parentBone) {
  40884. continue;
  40885. }
  40886. var points = this._debugLines[boneNum];
  40887. if (!points) {
  40888. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  40889. this._debugLines[boneNum] = points;
  40890. }
  40891. this._getBonePosition(points[0], childBone, meshMat);
  40892. this._getBonePosition(points[1], parentBone, meshMat);
  40893. boneNum++;
  40894. }
  40895. };
  40896. SkeletonViewer.prototype.update = function () {
  40897. if (this.autoUpdateBonesMatrices) {
  40898. this._updateBoneMatrix(this.skeleton.bones[0]);
  40899. }
  40900. if (this.skeleton.bones[0].length === undefined) {
  40901. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  40902. }
  40903. else {
  40904. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  40905. }
  40906. if (!this._debugMesh) {
  40907. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  40908. this._debugMesh.renderingGroupId = this.renderingGroupId;
  40909. }
  40910. else {
  40911. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  40912. }
  40913. this._debugMesh.color = this.color;
  40914. };
  40915. SkeletonViewer.prototype._updateBoneMatrix = function (bone) {
  40916. if (bone.getParent()) {
  40917. bone.getLocalMatrix().multiplyToRef(bone.getParent().getAbsoluteTransform(), bone.getAbsoluteTransform());
  40918. }
  40919. var children = bone.children;
  40920. var len = children.length;
  40921. for (var i = 0; i < len; i++) {
  40922. this._updateBoneMatrix(children[i]);
  40923. }
  40924. };
  40925. SkeletonViewer.prototype.dispose = function () {
  40926. if (this._debugMesh) {
  40927. this.isEnabled = false;
  40928. this._debugMesh.dispose();
  40929. this._debugMesh = null;
  40930. }
  40931. };
  40932. return SkeletonViewer;
  40933. })();
  40934. Debug.SkeletonViewer = SkeletonViewer;
  40935. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  40936. })(BABYLON || (BABYLON = {}));
  40937. BABYLON.Effect.ShadersStore={"anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\nfloat luminance=dot(texture2D(textureSampler,vUV).rgb,vec3(0.3,0.59,0.11));\ngl_FragColor=vec4(luminance,luminance,luminance,1.0);\n}","blurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\nbaseColor+=texture2D(textureSampler,start+texelOffset)*weights[i];\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\nif (chromatic_aberration>0.0) {\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*radius*17.0/screen_width;\nfloat ref_shiftY=chromatic_aberration*radius*17.0/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\n}\ngl_FragColor=original;\n}","colorPixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","colorVertexShader":"\nattribute vec3 position;\n\nuniform mat4 worldViewProjection;\nvoid main(void) {\ngl_Position=worldViewProjection*vec4(position,1.0);\n}","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D texture,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(texture,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(texture,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","defaultPixelShader":"#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<helperFunctions>\n\n#include<lightFragmentDeclaration>[0]\n#include<lightFragmentDeclaration>[1]\n#include<lightFragmentDeclaration>[2]\n#include<lightFragmentDeclaration>[3]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#include<reflectionFunction>\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#ifdef DIFFUSE\nvec2 diffuseUV=vDiffuseUV;\n#endif\n#include<bumpFragment>\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,diffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV).rgb*vAmbientInfos.y;\n#endif\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#include<lightFragment>[0]\n#include<lightFragment>[1]\n#include<lightFragment>[2]\n#include<lightFragment>[3]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV).rgb*vLightmapInfos.y;\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#include<logDepthFragment>\n#include<fogFragment>\ngl_FragColor=color;\n}","defaultVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#include<pointCloudVertexDeclaration>\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef LIGHTMAP\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform float far;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=(gl_FragCoord.z/gl_FragCoord.w)/far;\ngl_FragColor=vec4(depth,depth*depth,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","fxaaPixelShader":"#define FXAA_REDUCE_MIN (1.0/128.0)\n#define FXAA_REDUCE_MUL (1.0/8.0)\n#define FXAA_SPAN_MAX 8.0\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvoid main(){\nvec2 localTexelSize=texelSize;\nvec4 rgbNW=texture2D(textureSampler,(vUV+vec2(-1.0,-1.0)*localTexelSize));\nvec4 rgbNE=texture2D(textureSampler,(vUV+vec2(1.0,-1.0)*localTexelSize));\nvec4 rgbSW=texture2D(textureSampler,(vUV+vec2(-1.0,1.0)*localTexelSize));\nvec4 rgbSE=texture2D(textureSampler,(vUV+vec2(1.0,1.0)*localTexelSize));\nvec4 rgbM=texture2D(textureSampler,vUV);\nvec4 luma=vec4(0.299,0.587,0.114,1.0);\nfloat lumaNW=dot(rgbNW,luma);\nfloat lumaNE=dot(rgbNE,luma);\nfloat lumaSW=dot(rgbSW,luma);\nfloat lumaSE=dot(rgbSE,luma);\nfloat lumaM=dot(rgbM,luma);\nfloat lumaMin=min(lumaM,min(min(lumaNW,lumaNE),min(lumaSW,lumaSE)));\nfloat lumaMax=max(lumaM,max(max(lumaNW,lumaNE),max(lumaSW,lumaSE)));\nvec2 dir=vec2(-((lumaNW+lumaNE)-(lumaSW+lumaSE)),((lumaNW+lumaSW)-(lumaNE+lumaSE)));\nfloat dirReduce=max(\n(lumaNW+lumaNE+lumaSW+lumaSE)*(0.25*FXAA_REDUCE_MUL),\nFXAA_REDUCE_MIN);\nfloat rcpDirMin=1.0/(min(abs(dir.x),abs(dir.y))+dirReduce);\ndir=min(vec2(FXAA_SPAN_MAX,FXAA_SPAN_MAX),\nmax(vec2(-FXAA_SPAN_MAX,-FXAA_SPAN_MAX),\ndir*rcpDirMin))*localTexelSize;\nvec4 rgbA=0.5*(\ntexture2D(textureSampler,vUV+dir*(1.0/3.0-0.5)) +\ntexture2D(textureSampler,vUV+dir*(2.0/3.0-0.5)));\nvec4 rgbB=rgbA*0.5+0.25*(\ntexture2D(textureSampler,vUV+dir*-0.5) +\ntexture2D(textureSampler,vUV+dir*0.5));\nfloat lumaB=dot(rgbB,luma);\nif ((lumaB<lumaMin) || (lumaB>lumaMax)) {\ngl_FragColor=rgbA;\n}\nelse {\ngl_FragColor=rgbB;\n}\n}","hdrPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\nuniform float blurOffsets[9];\nuniform float blurWeights[9];\nuniform float multiplier;\nvoid main(void) {\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfor (int i=0; i<9; i++) {\n#ifdef GAUSSIAN_BLUR_H\ncolor+=(texture2D(textureSampler,vUV+vec2(blurOffsets[i]*multiplier,0.0))*blurWeights[i]);\n#else\ncolor+=(texture2D(textureSampler,vUV+vec2(0.0,blurOffsets[i]*multiplier))*blurWeights[i]);\n#endif\n}\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nvoid main() {\nvec4 sum=texture2D(textureSampler,vUV)+texture2D(otherSampler,vUV);\nsum.a=clamp(sum.a,0.0,1.0);\ngl_FragColor=sum;\n}\n#endif\n#if defined(LUMINANCE_GENERATOR)\nuniform vec2 lumOffsets[4];\nvoid main() {\nfloat average=0.0;\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfloat maximum=-1e20;\nfor (int i=0; i<4; i++) {\ncolor=texture2D(textureSampler,vUV+lumOffsets[i]);\nfloat GreyValue=length(color.rgb);\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLE\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main() {\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++) {\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifndef FINAL_DOWN_SAMPLE\ngl_FragColor=vec4(average,average,0.0,1.0);\n#else\ngl_FragColor=pack(average);\n#endif\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main() {\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main() {\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(HDR)\nuniform sampler2D otherSampler;\nuniform float exposure;\nuniform float avgLuminance;\nvoid main() {\nvec4 color=texture2D(textureSampler,vUV)+texture2D(otherSampler,vUV);\nvec4 adjustedColor=color/avgLuminance*exposure;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","legacydefaultPixelShader":"#define MAP_PROJECTION 4.\n\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<lightFragmentDeclaration>[0]\n#include<lightFragmentDeclaration>[1]\n#include<lightFragmentDeclaration>[2]\n#include<lightFragmentDeclaration>[3]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef REFLECTION\nvarying vec3 vReflectionUVW;\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\nuniform vec2 vReflectionInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n#include<clipPlaneFragmentDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 normalW=normalize(vNormalW);\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV).rgb*vAmbientInfos.y;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\nfloat glossiness=0.;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\nglossiness=vSpecularColor.a;\n#endif\nfloat shadow=1.;\n#include<lightFragment>[0]\n#include<lightFragment>[1]\n#include<lightFragment>[2]\n#include<lightFragment>[3]\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n\nfloat alpha=vDiffuseColor.a;\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nspecularColor=texture2D(specularSampler,vSpecularUV).rgb*vSpecularInfos.y;\n#endif\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor,alpha);\n#include<fogFragment>\ngl_FragColor=color;\n}","legacydefaultVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>\n#ifdef REFLECTION\nuniform vec3 vEyePosition;\nvarying vec3 vReflectionUVW;\nuniform mat4 reflectionMatrix;\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 coords=vec3(view*vec4(worldNormal,0.0));\nreturn vec3(reflectionMatrix*vec4(coords,1.0));\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn position;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef REFLECTION\nvReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),vNormalW);\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","outlinePixelShader":"uniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}\n","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\n\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\nvUV=offset;\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","postprocessVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","shadowMapPixelShader":"vec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n\nvec2 packHalf(float depth) \n{ \nconst vec2 bitOffset=vec2(1.0/255.,0.);\nvec2 color=vec2(depth,fract(depth*255.));\nreturn color-(color.yy*bitOffset);\n}\nvarying vec4 vPosition;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef CUBEMAP\nuniform vec3 lightPosition;\nuniform vec2 depthValues;\n#endif\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#ifdef CUBEMAP\nvec3 directionToLight=vPosition.xyz-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\n#else\nfloat depth=vPosition.z/vPosition.w;\ndepth=depth*0.5+0.5;\n#endif\n#ifdef VSM\nfloat moment1=depth;\nfloat moment2=moment1*moment1;\ngl_FragColor=vec4(packHalf(moment1),packHalf(moment2));\n#else\ngl_FragColor=pack(depth);\n#endif\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nfFogDistance=viewPos.z;\n#endif\n}","ssaoPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvarying vec2 vUV;\nvec3 normalFromDepth(float depth,vec2 coords) {\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 sample=texture2D(lightScatteringSampler,tc)*0.4;\nsample*=illuminationDecay*weight;\ncolor+=sample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\nuniform sampler2D diffuseSampler;\n#endif\n#if defined(DIFFUSE_COLOR_RENDER)\nuniform vec3 color;\n#endif\n#if defined(OPACITY)\nuniform sampler2D opacitySampler;\nuniform float opacityLevel;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\n#endif\n#ifdef ALPHATEST\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\n#ifdef OPACITY\nvec4 opacityColor=texture2D(opacitySampler,vUV);\nfloat alpha=1.0;\n#ifdef OPACITYRGB\nopacityColor.rgb=opacityColor.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityColor.x+opacityColor.y+opacityColor.z)*opacityLevel;\n#else\nalpha*=opacityColor.a*opacityLevel;\n#endif\n#if defined(BASIC_RENDER)\ngl_FragColor=vec4(diffuseColor.rgb,alpha);\n#elif defined(DIFFUSE_COLOR_RENDER)\ngl_FragColor=vec4(color.rgb,alpha);\n#else\ngl_FragColor=vec4(0.0,0.0,0.0,alpha);\n#endif\ngl_FragColor.a=alpha;\n#else\n#if defined(BASIC_RENDER)\ngl_FragColor=diffuseColor;\n#elif defined(DIFFUSE_COLOR_RENDER)\ngl_FragColor=vec4(color.rgb,1.0);\n#else\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n#endif\n#endif\n}\n","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nelse{\ngl_FragColor=vec4(texture2D(textureSampler,tc).rgb,1.0);\n}\n}"};
  40938. BABYLON.CollisionWorker="var BABYLON;!function(t){var e=function(t,e,o,i){return t.x>o.x+i?!1:o.x-i>e.x?!1:t.y>o.y+i?!1:o.y-i>e.y?!1:t.z>o.z+i?!1:o.z-i>e.z?!1:!0},o=function(t,e,o,i){var s=e*e-4*t*o,r={root:0,found:!1};if(0>s)return r;var n=Math.sqrt(s),c=(-e-n)/(2*t),h=(-e+n)/(2*t);if(c>h){var a=h;h=c,c=a}return c>0&&i>c?(r.root=c,r.found=!0,r):h>0&&i>h?(r.root=h,r.found=!0,r):r},i=function(){function i(){this.radius=new t.Vector3(1,1,1),this.retry=0,this.basePointWorld=t.Vector3.Zero(),this.velocityWorld=t.Vector3.Zero(),this.normalizedVelocity=t.Vector3.Zero(),this._collisionPoint=t.Vector3.Zero(),this._planeIntersectionPoint=t.Vector3.Zero(),this._tempVector=t.Vector3.Zero(),this._tempVector2=t.Vector3.Zero(),this._tempVector3=t.Vector3.Zero(),this._tempVector4=t.Vector3.Zero(),this._edge=t.Vector3.Zero(),this._baseToVertex=t.Vector3.Zero(),this._destinationPoint=t.Vector3.Zero(),this._slidePlaneNormal=t.Vector3.Zero(),this._displacementVector=t.Vector3.Zero()}return i.prototype._initialize=function(e,o,i){this.velocity=o,t.Vector3.NormalizeToRef(o,this.normalizedVelocity),this.basePoint=e,e.multiplyToRef(this.radius,this.basePointWorld),o.multiplyToRef(this.radius,this.velocityWorld),this.velocityWorldLength=this.velocityWorld.length(),this.epsilon=i,this.collisionFound=!1},i.prototype._checkPointInTriangle=function(e,o,i,s,r){o.subtractToRef(e,this._tempVector),i.subtractToRef(e,this._tempVector2),t.Vector3.CrossToRef(this._tempVector,this._tempVector2,this._tempVector4);var n=t.Vector3.Dot(this._tempVector4,r);return 0>n?!1:(s.subtractToRef(e,this._tempVector3),t.Vector3.CrossToRef(this._tempVector2,this._tempVector3,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),0>n?!1:(t.Vector3.CrossToRef(this._tempVector3,this._tempVector,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),n>=0))},i.prototype._canDoCollision=function(o,i,s,r){var n=t.Vector3.Distance(this.basePointWorld,o),c=Math.max(this.radius.x,this.radius.y,this.radius.z);return n>this.velocityWorldLength+c+i?!1:e(s,r,this.basePointWorld,this.velocityWorldLength+c)?!0:!1},i.prototype._testTriangle=function(e,i,s,r,n,c){var h,a=!1;i||(i=[]),i[e]||(i[e]=new t.Plane(0,0,0,0),i[e].copyFromPoints(s,r,n));var l=i[e];if(c||l.isFrontFacingTo(this.normalizedVelocity,0)){var _=l.signedDistanceTo(this.basePoint),d=t.Vector3.Dot(l.normal,this.velocity);if(0==d){if(Math.abs(_)>=1)return;a=!0,h=0}else{h=(-1-_)/d;var V=(1-_)/d;if(h>V){var u=V;V=h,h=u}if(h>1||0>V)return;0>h&&(h=0),h>1&&(h=1)}this._collisionPoint.copyFromFloats(0,0,0);var P=!1,p=1;if(a||(this.basePoint.subtractToRef(l.normal,this._planeIntersectionPoint),this.velocity.scaleToRef(h,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,s,r,n,l.normal)&&(P=!0,p=h,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!P){var m=this.velocity.lengthSquared(),f=m;this.basePoint.subtractToRef(s,this._tempVector);var T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p);y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(s)),this.basePoint.subtractToRef(r,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(r)),this.basePoint.subtractToRef(n,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(n)),r.subtractToRef(s,this._edge),s.subtractToRef(this.basePoint,this._baseToVertex);var g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex);if(f=g*-m+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found){var D=(v*y.root-R)/g;D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),s.addToRef(this._edge,this._collisionPoint))}n.subtractToRef(r,this._edge),r.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),f=g*-m+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),r.addToRef(this._edge,this._collisionPoint))),s.subtractToRef(n,this._edge),n.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),f=g*-m+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),n.addToRef(this._edge,this._collisionPoint)))}if(P){var x=p*this.velocity.length();(!this.collisionFound||x<this.nearestDistance)&&(this.intersectionPoint?this.intersectionPoint.copyFrom(this._collisionPoint):this.intersectionPoint=this._collisionPoint.clone(),this.nearestDistance=x,this.collisionFound=!0)}}},i.prototype._collide=function(t,e,o,i,s,r,n){for(var c=i;s>c;c+=3){var h=e[o[c]-r],a=e[o[c+1]-r],l=e[o[c+2]-r];this._testTriangle(c,t,l,a,h,n)}},i.prototype._getResponse=function(e,o){e.addToRef(o,this._destinationPoint),o.scaleInPlace(this.nearestDistance/o.length()),this.basePoint.addToRef(o,e),e.subtractToRef(this.intersectionPoint,this._slidePlaneNormal),this._slidePlaneNormal.normalize(),this._slidePlaneNormal.scaleToRef(this.epsilon,this._displacementVector),e.addInPlace(this._displacementVector),this.intersectionPoint.addInPlace(this._displacementVector),this._slidePlaneNormal.scaleInPlace(t.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint,this._slidePlaneNormal,this._destinationPoint)),this._destinationPoint.subtractInPlace(this._slidePlaneNormal),this._destinationPoint.subtractToRef(this.intersectionPoint,o)},i}();t.Collider=i}(BABYLON||(BABYLON={}));var BABYLON;!function(o){o.WorkerIncluded=!0;var e=function(){function o(){this._meshes={},this._geometries={}}return o.prototype.getMeshes=function(){return this._meshes},o.prototype.getGeometries=function(){return this._geometries},o.prototype.getMesh=function(o){return this._meshes[o]},o.prototype.addMesh=function(o){this._meshes[o.uniqueId]=o},o.prototype.removeMesh=function(o){delete this._meshes[o]},o.prototype.getGeometry=function(o){return this._geometries[o]},o.prototype.addGeometry=function(o){this._geometries[o.id]=o},o.prototype.removeGeometry=function(o){delete this._geometries[o]},o}();o.CollisionCache=e;var i=function(){function e(e,i,r){this.collider=e,this._collisionCache=i,this.finalPosition=r,this.collisionsScalingMatrix=o.Matrix.Zero(),this.collisionTranformationMatrix=o.Matrix.Zero()}return e.prototype.collideWithWorld=function(o,e,i,r){var t=.01;if(this.collider.retry>=i)return void this.finalPosition.copyFrom(o);this.collider._initialize(o,e,t);for(var s,l=this._collisionCache.getMeshes(),n=Object.keys(l),a=n.length,c=0;a>c;++c)if(s=n[c],parseInt(s)!=r){var d=l[s];d.checkCollisions&&this.checkCollision(d)}return this.collider.collisionFound?((0!==e.x||0!==e.y||0!==e.z)&&this.collider._getResponse(o,e),e.length()<=t?void this.finalPosition.copyFrom(o):(this.collider.retry++,void this.collideWithWorld(o,e,i,r))):void o.addToRef(e,this.finalPosition)},e.prototype.checkCollision=function(e){if(this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))){o.Matrix.ScalingToRef(1/this.collider.radius.x,1/this.collider.radius.y,1/this.collider.radius.z,this.collisionsScalingMatrix);var i=o.Matrix.FromArray(e.worldMatrixFromCache);i.multiplyToRef(this.collisionsScalingMatrix,this.collisionTranformationMatrix),this.processCollisionsForSubMeshes(this.collisionTranformationMatrix,e)}},e.prototype.processCollisionsForSubMeshes=function(o,e){var i=e.subMeshes,r=i.length;if(!e.geometryId)return void console.log(\"no mesh geometry id\");var t=this._collisionCache.getGeometry(e.geometryId);if(!t)return void console.log(\"couldn't find geometry\",e.geometryId);for(var s=0;r>s;s++){var l=i[s];r>1&&!this.checkSubmeshCollision(l)||(this.collideForSubMesh(l,o,t),this.collider.collisionFound&&(this.collider.collidedMesh=e.uniqueId))}},e.prototype.collideForSubMesh=function(e,i,r){if(!r.positionsArray){r.positionsArray=[];for(var t=0,s=r.positions.length;s>t;t+=3){var l=o.Vector3.FromArray([r.positions[t],r.positions[t+1],r.positions[t+2]]);r.positionsArray.push(l)}}if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(i)){e._lastColliderTransformMatrix=i.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];for(var n=e.verticesStart,a=e.verticesStart+e.verticesCount,t=n;a>t;t++)e._lastColliderWorldVertices.push(o.Vector3.TransformCoordinates(r.positionsArray[t],i))}this.collider._collide(e._trianglePlanes,e._lastColliderWorldVertices,r.indices,e.indexStart,e.indexStart+e.indexCount,e.verticesStart,e.hasMaterial)},e.prototype.checkSubmeshCollision=function(e){return this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))},e}();o.CollideWorker=i;var r=function(){function r(){}return r.prototype.onInit=function(i){this._collisionCache=new e;var r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.INIT};postMessage(r,void 0)},r.prototype.onUpdate=function(e){var i=this,r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.UPDATE};try{for(var t in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(t)&&this._collisionCache.addGeometry(e.updatedGeometries[t]);for(var s in e.updatedMeshes)e.updatedMeshes.hasOwnProperty(s)&&this._collisionCache.addMesh(e.updatedMeshes[s]);e.removedGeometries.forEach(function(o){i._collisionCache.removeGeometry(o)}),e.removedMeshes.forEach(function(o){i._collisionCache.removeMesh(o)})}catch(l){r.error=o.WorkerReplyType.UNKNOWN_ERROR}postMessage(r,void 0)},r.prototype.onCollision=function(e){var r=o.Vector3.Zero(),t=new o.Collider;t.radius=o.Vector3.FromArray(e.collider.radius);var s=new i(t,this._collisionCache,r);s.collideWithWorld(o.Vector3.FromArray(e.collider.position),o.Vector3.FromArray(e.collider.velocity),e.maximumRetry,e.excludedMeshUniqueId);var l={collidedMeshUniqueId:t.collidedMesh,collisionId:e.collisionId,newPosition:r.asArray()},n={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.COLLIDE,payload:l};postMessage(n,void 0)},r}();o.CollisionDetectorTransferable=r;try{if(self&&self instanceof WorkerGlobalScope){window={},o.Collider||(importScripts(\"./babylon.collisionCoordinator.js\"),importScripts(\"./babylon.collider.js\"),importScripts(\"../Math/babylon.math.js\"));var t=new r,s=function(e){var i=e.data;switch(i.taskType){case o.WorkerTaskType.INIT:t.onInit(i.payload);break;case o.WorkerTaskType.COLLIDE:t.onCollision(i.payload);break;case o.WorkerTaskType.UPDATE:t.onUpdate(i.payload)}};self.onmessage=s}}catch(l){console.log(\"single worker init\")}}(BABYLON||(BABYLON={}));var BABYLON;!function(e){e.CollisionWorker=\"\",function(e){e[e.INIT=0]=\"INIT\",e[e.UPDATE=1]=\"UPDATE\",e[e.COLLIDE=2]=\"COLLIDE\"}(e.WorkerTaskType||(e.WorkerTaskType={}));var o=e.WorkerTaskType;!function(e){e[e.SUCCESS=0]=\"SUCCESS\",e[e.UNKNOWN_ERROR=1]=\"UNKNOWN_ERROR\"}(e.WorkerReplyType||(e.WorkerReplyType={}));var i=e.WorkerReplyType,t=function(){function t(){var r=this;this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this.onMeshUpdated=function(e){r._addUpdateMeshesList[e.uniqueId]=t.SerializeMesh(e)},this.onGeometryUpdated=function(e){r._addUpdateGeometriesList[e.id]=t.SerializeGeometry(e)},this._afterRender=function(){if(r._init&&!(0==r._toRemoveGeometryArray.length&&0==r._toRemoveMeshesArray.length&&0==Object.keys(r._addUpdateGeometriesList).length&&0==Object.keys(r._addUpdateMeshesList).length||r._runningUpdated>4)){++r._runningUpdated;var e={updatedMeshes:r._addUpdateMeshesList,updatedGeometries:r._addUpdateGeometriesList,removedGeometries:r._toRemoveGeometryArray,removedMeshes:r._toRemoveMeshesArray},i={payload:e,taskType:o.UPDATE},t=[];for(var s in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(s)&&(t.push(i.payload.updatedGeometries[s].indices.buffer),t.push(i.payload.updatedGeometries[s].normals.buffer),t.push(i.payload.updatedGeometries[s].positions.buffer));r._worker.postMessage(i,t),r._addUpdateMeshesList={},r._addUpdateGeometriesList={},r._toRemoveGeometryArray=[],r._toRemoveMeshesArray=[]}},this._onMessageFromWorker=function(t){var s=t.data;if(s.error!=i.SUCCESS)return void e.Tools.Warn(\"error returned from worker!\");switch(s.taskType){case o.INIT:r._init=!0,r._scene.meshes.forEach(function(e){r.onMeshAdded(e)}),r._scene.getGeometries().forEach(function(e){r.onGeometryAdded(e)});break;case o.UPDATE:r._runningUpdated--;break;case o.COLLIDE:r._runningCollisionTask=!1;var n=s.payload;if(!r._collisionsCallbackArray[n.collisionId])return;r._collisionsCallbackArray[n.collisionId](n.collisionId,e.Vector3.FromArray(n.newPosition),r._scene.getMeshByUniqueID(n.collidedMeshUniqueId)),r._collisionsCallbackArray[n.collisionId]=void 0}},this._collisionsCallbackArray=[],this._init=!1,this._runningUpdated=0,this._runningCollisionTask=!1,this._addUpdateMeshesList={},this._addUpdateGeometriesList={},this._toRemoveGeometryArray=[],this._toRemoveMeshesArray=[]}return t.prototype.getNewPosition=function(e,i,t,r,s,n,a){if(this._init&&!this._collisionsCallbackArray[a]&&!this._collisionsCallbackArray[a+1e5]){e.divideToRef(t.radius,this._scaledPosition),i.divideToRef(t.radius,this._scaledVelocity),this._collisionsCallbackArray[a]=n;var d={collider:{position:this._scaledPosition.asArray(),velocity:this._scaledVelocity.asArray(),radius:t.radius.asArray()},collisionId:a,excludedMeshUniqueId:s?s.uniqueId:null,maximumRetry:r},l={payload:d,taskType:o.COLLIDE};this._worker.postMessage(l)}},t.prototype.init=function(i){this._scene=i,this._scene.registerAfterRender(this._afterRender);var t=e.WorkerIncluded?e.Engine.CodeRepository+\"Collisions/babylon.collisionWorker.js\":URL.createObjectURL(new Blob([e.CollisionWorker],{type:\"application/javascript\"}));this._worker=new Worker(t),this._worker.onmessage=this._onMessageFromWorker;var r={payload:{},taskType:o.INIT};this._worker.postMessage(r)},t.prototype.destroy=function(){this._scene.unregisterAfterRender(this._afterRender),this._worker.terminate()},t.prototype.onMeshAdded=function(e){e.registerAfterWorldMatrixUpdate(this.onMeshUpdated),this.onMeshUpdated(e)},t.prototype.onMeshRemoved=function(e){this._toRemoveMeshesArray.push(e.uniqueId)},t.prototype.onGeometryAdded=function(e){e.onGeometryUpdated=this.onGeometryUpdated,this.onGeometryUpdated(e)},t.prototype.onGeometryDeleted=function(e){this._toRemoveGeometryArray.push(e.id)},t.SerializeMesh=function(o){var i=[];o.subMeshes&&(i=o.subMeshes.map(function(e,o){return{position:o,verticesStart:e.verticesStart,verticesCount:e.verticesCount,indexStart:e.indexStart,indexCount:e.indexCount,hasMaterial:!!e.getMaterial(),sphereCenter:e.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:e.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:e.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:e.getBoundingInfo().boundingBox.maximumWorld.asArray()}}));var t=null;return o instanceof e.Mesh?t=o.geometry?o.geometry.id:null:o instanceof e.InstancedMesh&&(t=o.sourceMesh&&o.sourceMesh.geometry?o.sourceMesh.geometry.id:null),{uniqueId:o.uniqueId,id:o.id,name:o.name,geometryId:t,sphereCenter:o.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:o.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:o.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:o.getBoundingInfo().boundingBox.maximumWorld.asArray(),worldMatrixFromCache:o.worldMatrixFromCache.asArray(),subMeshes:i,checkCollisions:o.checkCollisions}},t.SerializeGeometry=function(o){return{id:o.id,positions:new Float32Array(o.getVerticesData(e.VertexBuffer.PositionKind)||[]),normals:new Float32Array(o.getVerticesData(e.VertexBuffer.NormalKind)||[]),indices:new Int32Array(o.getIndices()||[])}},t}();e.CollisionCoordinatorWorker=t;var r=function(){function o(){this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this._finalPosition=e.Vector3.Zero()}return o.prototype.getNewPosition=function(e,o,i,t,r,s,n){e.divideToRef(i.radius,this._scaledPosition),o.divideToRef(i.radius,this._scaledVelocity),i.collidedMesh=null,i.retry=0,i.initialVelocity=this._scaledVelocity,i.initialPosition=this._scaledPosition,this._collideWithWorld(this._scaledPosition,this._scaledVelocity,i,t,this._finalPosition,r),this._finalPosition.multiplyInPlace(i.radius),s(n,this._finalPosition,i.collidedMesh)},o.prototype.init=function(e){this._scene=e},o.prototype.destroy=function(){},o.prototype.onMeshAdded=function(e){},o.prototype.onMeshUpdated=function(e){},o.prototype.onMeshRemoved=function(e){},o.prototype.onGeometryAdded=function(e){},o.prototype.onGeometryUpdated=function(e){},o.prototype.onGeometryDeleted=function(e){},o.prototype._collideWithWorld=function(o,i,t,r,s,n){void 0===n&&(n=null);var a=10*e.Engine.CollisionsEpsilon;if(t.retry>=r)return void s.copyFrom(o);t._initialize(o,i,a);for(var d=0;d<this._scene.meshes.length;d++){var l=this._scene.meshes[d];l.isEnabled()&&l.checkCollisions&&l.subMeshes&&l!==n&&l._checkCollision(t)}return t.collisionFound?((0!==i.x||0!==i.y||0!==i.z)&&t._getResponse(o,i),i.length()<=a?void s.copyFrom(o):(t.retry++,void this._collideWithWorld(o,i,t,r,s,n))):void o.addToRef(i,s)},o}();e.CollisionCoordinatorLegacy=r}(BABYLON||(BABYLON={}));var BABYLON;!function(t){t.ToGammaSpace=1/2.2,t.ToLinearSpace=2.2,t.Epsilon=.001;var i=function(){function t(){}return t.WithinEpsilon=function(t,i,n){void 0===n&&(n=1.401298e-45);var r=t-i;return r>=-n&&n>=r},t.ToHex=function(t){var i=t.toString(16);return 15>=t?(\"0\"+i).toUpperCase():i.toUpperCase()},t.Sign=function(t){return t=+t,0===t||isNaN(t)?t:t>0?1:-1},t.Clamp=function(t,i,n){return void 0===i&&(i=0),void 0===n&&(n=1),Math.min(n,Math.max(i,t))},t}();t.MathTools=i;var n=function(){function n(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 n.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\"}\"},n.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},n.prototype.toColor4=function(t){return void 0===t&&(t=1),new r(this.r,this.g,this.b,t)},n.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},n.prototype.toLuminance=function(){return.3*this.r+.59*this.g+.11*this.b},n.prototype.multiply=function(t){return new n(this.r*t.r,this.g*t.g,this.b*t.b)},n.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},n.prototype.equals=function(t){return t&&this.r===t.r&&this.g===t.g&&this.b===t.b},n.prototype.equalsFloats=function(t,i,n){return this.r===t&&this.g===i&&this.b===n},n.prototype.scale=function(t){return new n(this.r*t,this.g*t,this.b*t)},n.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,this},n.prototype.add=function(t){return new n(this.r+t.r,this.g+t.g,this.b+t.b)},n.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},n.prototype.subtract=function(t){return new n(this.r-t.r,this.g-t.g,this.b-t.b)},n.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},n.prototype.clone=function(){return new n(this.r,this.g,this.b)},n.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this},n.prototype.copyFromFloats=function(t,i,n){return this.r=t,this.g=i,this.b=n,this},n.prototype.toHexString=function(){var t=255*this.r|0,n=255*this.g|0,r=255*this.b|0;return\"#\"+i.ToHex(t)+i.ToHex(n)+i.ToHex(r)},n.prototype.toLinearSpace=function(){var t=new n;return this.toLinearSpaceToRef(t),t},n.prototype.toLinearSpaceToRef=function(i){return i.r=Math.pow(this.r,t.ToLinearSpace),i.g=Math.pow(this.g,t.ToLinearSpace),i.b=Math.pow(this.b,t.ToLinearSpace),this},n.prototype.toGammaSpace=function(){var t=new n;return this.toGammaSpaceToRef(t),t},n.prototype.toGammaSpaceToRef=function(i){return i.r=Math.pow(this.r,t.ToGammaSpace),i.g=Math.pow(this.g,t.ToGammaSpace),i.b=Math.pow(this.b,t.ToGammaSpace),this},n.FromHexString=function(t){if(\"#\"!==t.substring(0,1)||7!==t.length)return new n(0,0,0);var i=parseInt(t.substring(1,3),16),r=parseInt(t.substring(3,5),16),o=parseInt(t.substring(5,7),16);return n.FromInts(i,r,o)},n.FromArray=function(t,i){return void 0===i&&(i=0),new n(t[i],t[i+1],t[i+2])},n.FromInts=function(t,i,r){return new n(t/255,i/255,r/255)},n.Lerp=function(t,i,r){var o=t.r+(i.r-t.r)*r,s=t.g+(i.g-t.g)*r,e=t.b+(i.b-t.b)*r;return new n(o,s,e)},n.Red=function(){return new n(1,0,0)},n.Green=function(){return new n(0,1,0)},n.Blue=function(){return new n(0,0,1)},n.Black=function(){return new n(0,0,0)},n.White=function(){return new n(1,1,1)},n.Purple=function(){return new n(.5,0,.5)},n.Magenta=function(){return new n(1,0,1)},n.Yellow=function(){return new n(1,1,0)},n.Gray=function(){return new n(.5,.5,.5)},n}();t.Color3=n;var r=function(){function t(t,i,n,r){this.r=t,this.g=i,this.b=n,this.a=r}return t.prototype.addInPlace=function(t){return this.r+=t.r,this.g+=t.g,this.b+=t.b,this.a+=t.a,this},t.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},t.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},t.prototype.add=function(i){return new t(this.r+i.r,this.g+i.g,this.b+i.b,this.a+i.a)},t.prototype.subtract=function(i){return new t(this.r-i.r,this.g-i.g,this.b-i.b,this.a-i.a)},t.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},t.prototype.scale=function(i){return new t(this.r*i,this.g*i,this.b*i,this.a*i)},t.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},t.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\" A:\"+this.a+\"}\"},t.prototype.clone=function(){return new t(this.r,this.g,this.b,this.a)},t.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this.a=t.a,this},t.prototype.toHexString=function(){var t=255*this.r|0,n=255*this.g|0,r=255*this.b|0,o=255*this.a|0;return\"#\"+i.ToHex(t)+i.ToHex(n)+i.ToHex(r)+i.ToHex(o)},t.FromHexString=function(i){if(\"#\"!==i.substring(0,1)||9!==i.length)return new t(0,0,0,0);var n=parseInt(i.substring(1,3),16),r=parseInt(i.substring(3,5),16),o=parseInt(i.substring(5,7),16),s=parseInt(i.substring(7,9),16);return t.FromInts(n,r,o,s)},t.Lerp=function(i,n,r){var o=new t(0,0,0,0);return t.LerpToRef(i,n,r,o),o},t.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},t.FromArray=function(i,n){return void 0===n&&(n=0),new t(i[n],i[n+1],i[n+2],i[n+3])},t.FromInts=function(i,n,r,o){return new t(i/255,n/255,r/255,o/255)},t.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},t}();t.Color4=r;var o=function(){function n(t,i){this.x=t,this.y=i}return n.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\"}\"},n.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,this},n.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},n.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this},n.prototype.copyFromFloats=function(t,i){return this.x=t,this.y=i,this},n.prototype.add=function(t){return new n(this.x+t.x,this.y+t.y)},n.prototype.addVector3=function(t){return new n(this.x+t.x,this.y+t.y)},n.prototype.subtract=function(t){return new n(this.x-t.x,this.y-t.y)},n.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this},n.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this},n.prototype.multiply=function(t){return new n(this.x*t.x,this.y*t.y)},n.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,this},n.prototype.multiplyByFloats=function(t,i){return new n(this.x*t,this.y*i)},n.prototype.divide=function(t){return new n(this.x/t.x,this.y/t.y)},n.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,this},n.prototype.negate=function(){return new n(-this.x,-this.y)},n.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this},n.prototype.scale=function(t){return new n(this.x*t,this.y*t)},n.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y},n.prototype.equalsWithEpsilon=function(n,r){return void 0===r&&(r=t.Epsilon),n&&i.WithinEpsilon(this.x,n.x,r)&&i.WithinEpsilon(this.y,n.y,r)},n.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},n.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y},n.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this},n.prototype.clone=function(){return new n(this.x,this.y)},n.Zero=function(){return new n(0,0)},n.FromArray=function(t,i){return void 0===i&&(i=0),new n(t[i],t[i+1])},n.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1]},n.CatmullRom=function(t,i,r,o,s){var e=s*s,h=s*e,a=.5*(2*i.x+(-t.x+r.x)*s+(2*t.x-5*i.x+4*r.x-o.x)*e+(-t.x+3*i.x-3*r.x+o.x)*h),u=.5*(2*i.y+(-t.y+r.y)*s+(2*t.y-5*i.y+4*r.y-o.y)*e+(-t.y+3*i.y-3*r.y+o.y)*h);return new n(a,u)},n.Clamp=function(t,i,r){var o=t.x;o=o>r.x?r.x:o,o=o<i.x?i.x:o;var s=t.y;return s=s>r.y?r.y:s,s=s<i.y?i.y:s,new n(o,s)},n.Hermite=function(t,i,r,o,s){var e=s*s,h=s*e,a=2*h-3*e+1,u=-2*h+3*e,m=h-2*e+s,y=h-e,c=t.x*a+r.x*u+i.x*m+o.x*y,p=t.y*a+r.y*u+i.y*m+o.y*y;return new n(c,p)},n.Lerp=function(t,i,r){var o=t.x+(i.x-t.x)*r,s=t.y+(i.y-t.y)*r;return new n(o,s)},n.Dot=function(t,i){return t.x*i.x+t.y*i.y},n.Normalize=function(t){var i=t.clone();return i.normalize(),i},n.Minimize=function(t,i){var r=t.x<i.x?t.x:i.x,o=t.y<i.y?t.y:i.y;return new n(r,o)},n.Maximize=function(t,i){var r=t.x>i.x?t.x:i.x,o=t.y>i.y?t.y:i.y;return new n(r,o)},n.Transform=function(t,i){var r=t.x*i.m[0]+t.y*i.m[4],o=t.x*i.m[1]+t.y*i.m[5];return new n(r,o)},n.Distance=function(t,i){return Math.sqrt(n.DistanceSquared(t,i))},n.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y;return n*n+r*r},n}();t.Vector2=o;var s=function(){function n(t,i,n){this.x=t,this.y=i,this.z=n}return n.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"}\"},n.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},n.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},n.prototype.toQuaternion=function(){var t=new h(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},n.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this},n.prototype.add=function(t){return new n(this.x+t.x,this.y+t.y,this.z+t.z)},n.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},n.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this},n.prototype.subtract=function(t){return new n(this.x-t.x,this.y-t.y,this.z-t.z)},n.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},n.prototype.subtractFromFloats=function(t,i,r){return new n(this.x-t,this.y-i,this.z-r)},n.prototype.subtractFromFloatsToRef=function(t,i,n,r){return r.x=this.x-t,r.y=this.y-i,r.z=this.z-n,this},n.prototype.negate=function(){return new n(-this.x,-this.y,-this.z)},n.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this},n.prototype.scale=function(t){return new n(this.x*t,this.y*t,this.z*t)},n.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t},n.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z},n.prototype.equalsWithEpsilon=function(n,r){return void 0===r&&(r=t.Epsilon),n&&i.WithinEpsilon(this.x,n.x,r)&&i.WithinEpsilon(this.y,n.y,r)&&i.WithinEpsilon(this.z,n.z,r)},n.prototype.equalsToFloats=function(t,i,n){return this.x===t&&this.y===i&&this.z===n},n.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this},n.prototype.multiply=function(t){return new n(this.x*t.x,this.y*t.y,this.z*t.z)},n.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},n.prototype.multiplyByFloats=function(t,i,r){return new n(this.x*t,this.y*i,this.z*r)},n.prototype.divide=function(t){return new n(this.x/t.x,this.y/t.y,this.z/t.z)},n.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},n.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},n.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},n.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},n.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z},n.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},n.prototype.clone=function(){return new n(this.x,this.y,this.z)},n.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this},n.prototype.copyFromFloats=function(t,i,n){return this.x=t,this.y=i,this.z=n,this},n.GetClipFactor=function(t,i,r,o){var s=n.Dot(t,r)-o,e=n.Dot(i,r)-o,h=s/(s-e);return h},n.FromArray=function(t,i){return i||(i=0),new n(t[i],t[i+1],t[i+2])},n.FromFloatArray=function(t,i){return i||(i=0),new n(t[i],t[i+1],t[i+2])},n.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2]},n.FromFloatArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2]},n.FromFloatsToRef=function(t,i,n,r){r.x=t,r.y=i,r.z=n},n.Zero=function(){return new n(0,0,0)},n.Up=function(){return new n(0,1,0)},n.TransformCoordinates=function(t,i){var r=n.Zero();return n.TransformCoordinatesToRef(t,i,r),r},n.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},n.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},n.TransformNormal=function(t,i){var r=n.Zero();return n.TransformNormalToRef(t,i,r),r},n.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]},n.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]},n.CatmullRom=function(t,i,r,o,s){var e=s*s,h=s*e,a=.5*(2*i.x+(-t.x+r.x)*s+(2*t.x-5*i.x+4*r.x-o.x)*e+(-t.x+3*i.x-3*r.x+o.x)*h),u=.5*(2*i.y+(-t.y+r.y)*s+(2*t.y-5*i.y+4*r.y-o.y)*e+(-t.y+3*i.y-3*r.y+o.y)*h),m=.5*(2*i.z+(-t.z+r.z)*s+(2*t.z-5*i.z+4*r.z-o.z)*e+(-t.z+3*i.z-3*r.z+o.z)*h);return new n(a,u,m)},n.Clamp=function(t,i,r){var o=t.x;o=o>r.x?r.x:o,o=o<i.x?i.x:o;var s=t.y;s=s>r.y?r.y:s,s=s<i.y?i.y:s;var e=t.z;return e=e>r.z?r.z:e,e=e<i.z?i.z:e,new n(o,s,e)},n.Hermite=function(t,i,r,o,s){var e=s*s,h=s*e,a=2*h-3*e+1,u=-2*h+3*e,m=h-2*e+s,y=h-e,c=t.x*a+r.x*u+i.x*m+o.x*y,p=t.y*a+r.y*u+i.y*m+o.y*y,f=t.z*a+r.z*u+i.z*m+o.z*y;return new n(c,p,f)},n.Lerp=function(t,i,r){var o=t.x+(i.x-t.x)*r,s=t.y+(i.y-t.y)*r,e=t.z+(i.z-t.z)*r;return new n(o,s,e)},n.Dot=function(t,i){return t.x*i.x+t.y*i.y+t.z*i.z},n.Cross=function(t,i){var r=n.Zero();return n.CrossToRef(t,i,r),r},n.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},n.Normalize=function(t){var i=n.Zero();return n.NormalizeToRef(t,i),i},n.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},n.Project=function(t,i,r,o){var s=o.width,e=o.height,h=o.x,u=o.y,m=a.FromValues(s/2,0,0,0,0,-e/2,0,0,0,0,1,0,h+s/2,e/2+u,0,1),y=i.multiply(r).multiply(m);return n.TransformCoordinates(t,y)},n.UnprojectFromTransform=function(t,r,o,s,e){var h=s.multiply(e);h.invert(),t.x=t.x/r*2-1,t.y=-(t.y/o*2-1);var a=n.TransformCoordinates(t,h),u=t.x*h.m[3]+t.y*h.m[7]+t.z*h.m[11]+h.m[15];return i.WithinEpsilon(u,1)&&(a=a.scale(1/u)),a},n.Unproject=function(t,r,o,s,e,h){var a=s.multiply(e).multiply(h);a.invert();var u=new n(t.x/r*2-1,-(t.y/o*2-1),t.z),m=n.TransformCoordinates(u,a),y=u.x*a.m[3]+u.y*a.m[7]+u.z*a.m[11]+a.m[15];return i.WithinEpsilon(y,1)&&(m=m.scale(1/y)),m},n.Minimize=function(t,i){var n=t.clone();return n.MinimizeInPlace(i),n},n.Maximize=function(t,i){var n=t.clone();return n.MaximizeInPlace(i),n},n.Distance=function(t,i){return Math.sqrt(n.DistanceSquared(t,i))},n.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},n.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},n.RotationFromAxis=function(t,i,r){var o=n.Zero();return n.RotationFromAxisToRef(t,i,r,o),o},n.RotationFromAxisToRef=function(r,o,s,e){var h=r.normalize(),a=s.normalize(),u=c.X,m=c.Y,y=0,p=0,f=0,l=0,x=0,z=0,w=0,v=-1,d=0,g=_.Vector3[0],T=0,R=_.Vector3[1];i.WithinEpsilon(a.z,0,t.Epsilon)?z=1:i.WithinEpsilon(a.x,0,t.Epsilon)?l=1:(w=a.z/a.x,l=-w*Math.sqrt(1/(1+w*w)),z=Math.sqrt(1/(1+w*w))),R.x=l,R.y=x,R.z=z,R.normalize(),n.CrossToRef(h,R,g),g.normalize(),n.Dot(a,g)<0&&(v=1),T=n.Dot(h,R),T=Math.min(1,Math.max(-1,T)),f=Math.acos(T)*v,n.Dot(R,u)<0&&(f=Math.PI+f,R=R.scaleInPlace(-1),d++);var M=_.Vector3[2],F=_.Vector3[3];l=0,x=0,z=0,v=-1,i.WithinEpsilon(a.z,0,t.Epsilon)?l=1:(w=R.z/R.x,l=-w*Math.sqrt(1/(1+w*w)),z=Math.sqrt(1/(1+w*w))),M.x=l,M.y=x,M.z=z,M.normalize(),n.CrossToRef(M,R,F),F.normalize(),n.CrossToRef(a,M,g),g.normalize(),n.Dot(R,g)<0&&(v=1),T=n.Dot(a,M),T=Math.min(1,Math.max(-1,T)),p=Math.acos(T)*v,n.Dot(F,m)<0&&(p=Math.PI+p,d++),v=-1,n.CrossToRef(u,R,g),g.normalize(),n.Dot(g,m)<0&&(v=1),T=n.Dot(R,u),T=Math.min(1,Math.max(-1,T)),y=-Math.acos(T)*v,0>T&&2>d&&(y=Math.PI+y),e.x=p,e.y=y,e.z=f},n}();t.Vector3=s;var e=function(){function n(t,i,n,r){this.x=t,this.y=i,this.z=n,this.w=r}return n.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"W:\"+this.w+\"}\"},n.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},n.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},n.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this},n.prototype.add=function(t){return new n(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)},n.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},n.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this},n.prototype.subtract=function(t){return new n(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)},n.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},n.prototype.subtractFromFloats=function(t,i,r,o){return new n(this.x-t,this.y-i,this.z-r,this.w-o)},n.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},n.prototype.negate=function(){return new n(-this.x,-this.y,-this.z,-this.w)},n.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},n.prototype.scale=function(t){return new n(this.x*t,this.y*t,this.z*t,this.w*t)},n.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},n.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},n.prototype.equalsWithEpsilon=function(n,r){return void 0===r&&(r=t.Epsilon),n&&i.WithinEpsilon(this.x,n.x,r)&&i.WithinEpsilon(this.y,n.y,r)&&i.WithinEpsilon(this.z,n.z,r)&&i.WithinEpsilon(this.w,n.w,r)},n.prototype.equalsToFloats=function(t,i,n,r){return this.x===t&&this.y===i&&this.z===n&&this.w===r},n.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this},n.prototype.multiply=function(t){return new n(this.x*t.x,this.y*t.y,this.z*t.z,this.w*t.w)},n.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},n.prototype.multiplyByFloats=function(t,i,r,o){return new n(this.x*t,this.y*i,this.z*r,this.w*o)},n.prototype.divide=function(t){return new n(this.x/t.x,this.y/t.y,this.z/t.z,this.w/t.w)},n.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},n.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},n.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},n.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},n.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},n.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},n.prototype.clone=function(){return new n(this.x,this.y,this.z,this.w)},n.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},n.prototype.copyFromFloats=function(t,i,n,r){return this.x=t,this.y=i,this.z=n,this.w=r,this},n.FromArray=function(t,i){return i||(i=0),new n(t[i],t[i+1],t[i+2],t[i+3])},n.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2],n.w=t[i+3]},n.FromFloatArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2],n.w=t[i+3]},n.FromFloatsToRef=function(t,i,n,r,o){o.x=t,o.y=i,o.z=n,o.w=r},n.Zero=function(){return new n(0,0,0,0)},n.Normalize=function(t){var i=n.Zero();return n.NormalizeToRef(t,i),i},n.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},n.Minimize=function(t,i){var n=t.clone();return n.MinimizeInPlace(i),n},n.Maximize=function(t,i){var n=t.clone();return n.MaximizeInPlace(i),n},n.Distance=function(t,i){return Math.sqrt(n.DistanceSquared(t,i))},n.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},n.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},n}();t.Vector4=e;var h=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.conjugateToRef=function(t){return t.copyFromFloats(-this.x,-this.y,-this.z,this.w),this},t.prototype.conjugateInPlace=function(){return this.x*=-1,this.y*=-1,this.z*=-1,this},t.prototype.conjugate=function(){var i=new t(-this.x,-this.y,-this.z,this.w);return i},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=s.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,y=e*e,c=h*h;n=Math.atan2(2*e*a-2*s*h,1-2*y-2*c),r=Math.asin(2*u),o=Math.atan2(2*s*a-2*e*h,1-2*m-2*c)}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],y=r[6],c=r[10],p=o+a+c;p>0?(n=.5/Math.sqrt(p+1),i.w=.25/n,i.x=(y-u)*n,i.y=(e-m)*n,i.z=(h-s)*n):o>a&&o>c?(n=2*Math.sqrt(1+o-a-c),i.w=(y-u)/n,i.x=.25*n,i.y=(s+h)/n,i.z=(e+m)/n):a>c?(n=2*Math.sqrt(1+a-o-c),i.w=(e-m)/n,i.x=(s+h)/n,i.y=.25*n,i.z=(u+y)/n):(n=2*Math.sqrt(1+c-o-a),i.w=(h-s)/n,i.x=(e+m)/n,i.y=(u+y)/n,i.z=.25*n)},t.Inverse=function(i){return new t(-i.x,-i.y,-i.z,i.w)},t.Identity=function(){return new t(0,0,0,1)},t.RotationAxis=function(i,n){var r=new t,o=Math.sin(n/2);return i.normalize(),r.w=Math.cos(n/2),r.x=i.x*o,r.y=i.y*o,r.z=i.z*o,r},t.FromArray=function(i,n){return n||(n=0),new t(i[n],i[n+1],i[n+2],i[n+3])},t.RotationYawPitchRoll=function(i,n,r){var o=new t;return t.RotationYawPitchRollToRef(i,n,r,o),o},t.RotationYawPitchRollToRef=function(t,i,n,r){var o=.5*n,s=.5*i,e=.5*t,h=Math.sin(o),a=Math.cos(o),u=Math.sin(s),m=Math.cos(s),y=Math.sin(e),c=Math.cos(e);r.x=c*u*a+y*m*h,r.y=y*m*a-c*u*h,r.z=c*m*h-y*u*a,r.w=c*m*a+y*u*h},t.RotationAlphaBetaGamma=function(i,n,r){var o=new t;return t.RotationAlphaBetaGammaToRef(i,n,r,o),o},t.RotationAlphaBetaGammaToRef=function(t,i,n,r){var o=.5*(n+t),s=.5*(n-t),e=.5*i;r.x=Math.cos(s)*Math.sin(e),r.y=Math.sin(s)*Math.sin(e),r.z=Math.sin(o)*Math.cos(e),r.w=Math.cos(o)*Math.cos(e)},t.Slerp=function(i,n,r){var o,s,e=r,h=i.x*n.x+i.y*n.y+i.z*n.z+i.w*n.w,a=!1;if(0>h&&(a=!0,h=-h),h>.999999)s=1-e,o=a?-e:e;else{var u=Math.acos(h),m=1/Math.sin(u);s=Math.sin((1-e)*u)*m,o=a?-Math.sin(e*u)*m:Math.sin(e*u)*m}return new t(s*i.x+o*n.x,s*i.y+o*n.y,s*i.z+o*n.z,s*i.w+o*n.w)},t}();t.Quaternion=h;var a=function(){function t(){this.m=new Float32Array(16)}return t.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},t.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)},t.prototype.toArray=function(){return this.m},t.prototype.asArray=function(){return this.toArray()},t.prototype.invert=function(){return this.invertToRef(this),this},t.prototype.reset=function(){for(var t=0;16>t;t++)this.m[t]=0;return this},t.prototype.add=function(i){var n=new t;return this.addToRef(i,n),n},t.prototype.addToRef=function(t,i){for(var n=0;16>n;n++)i.m[n]=this.m[n]+t.m[n];return this},t.prototype.addToSelf=function(t){for(var i=0;16>i;i++)this.m[i]+=t.m[i];return this},t.prototype.invertToRef=function(t){var i=this.m[0],n=this.m[1],r=this.m[2],o=this.m[3],s=this.m[4],e=this.m[5],h=this.m[6],a=this.m[7],u=this.m[8],m=this.m[9],y=this.m[10],c=this.m[11],p=this.m[12],f=this.m[13],l=this.m[14],x=this.m[15],z=y*x-c*l,w=m*x-c*f,v=m*l-y*f,d=u*x-c*p,g=u*l-y*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,S=s*f-e*p,I=h*c-a*y,q=e*c-a*m,E=e*y-h*m,D=s*c-a*u,V=s*y-h*u,W=s*m-e*u;return t.m[0]=R*b,t.m[4]=_*b,t.m[8]=M*b,t.m[12]=F*b,t.m[1]=-(n*z-r*w+o*v)*b,t.m[5]=(i*z-r*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*S)*b,t.m[14]=-(i*P-n*C+r*S)*b,t.m[3]=-(n*I-r*q+o*E)*b,t.m[7]=(i*I-r*D+o*V)*b,t.m[11]=-(i*q-n*D+o*W)*b,t.m[15]=(i*E-n*V+r*W)*b,this},t.prototype.setTranslation=function(t){return this.m[12]=t.x,this.m[13]=t.y,this.m[14]=t.z,this},t.prototype.multiply=function(i){var n=new t;return this.multiplyToRef(i,n),n},t.prototype.copyFrom=function(t){for(var i=0;16>i;i++)this.m[i]=t.m[i];return this},t.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},t.prototype.multiplyToRef=function(t,i){return this.multiplyToArray(t,i.m,0),this},t.prototype.multiplyToArray=function(t,i,n){var r=this.m[0],o=this.m[1],s=this.m[2],e=this.m[3],h=this.m[4],a=this.m[5],u=this.m[6],m=this.m[7],y=this.m[8],c=this.m[9],p=this.m[10],f=this.m[11],l=this.m[12],x=this.m[13],z=this.m[14],w=this.m[15],v=t.m[0],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],S=t.m[14],I=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*S,i[n+3]=r*T+o*F+s*P+e*I,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*S,i[n+7]=h*T+a*F+u*P+m*I,i[n+8]=y*v+c*R+p*b+f*Z,i[n+9]=y*d+c*_+p*A+f*C,i[n+10]=y*g+c*M+p*L+f*S,i[n+11]=y*T+c*F+p*P+f*I,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*S,i[n+15]=l*T+x*F+z*P+w*I,this},t.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]},t.prototype.clone=function(){return t.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])},t.prototype.decompose=function(n,r,o){o.x=this.m[12],o.y=this.m[13],o.z=this.m[14];var s=i.Sign(this.m[0]*this.m[1]*this.m[2]*this.m[3])<0?-1:1,e=i.Sign(this.m[4]*this.m[5]*this.m[6]*this.m[7])<0?-1:1,a=i.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=a*Math.sqrt(this.m[8]*this.m[8]+this.m[9]*this.m[9]+this.m[10]*this.m[10]),0===n.x||0===n.y||0===n.z)return r.x=0,r.y=0,r.z=0,r.w=1,!1;var u=t.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 h.FromRotationMatrixToRef(u,r),!0},t.FromArray=function(i,n){var r=new t;return n||(n=0),t.FromArrayToRef(i,n,r),r},t.FromArrayToRef=function(t,i,n){for(var r=0;16>r;r++)n.m[r]=t[r+i]},t.FromFloat32ArrayToRefScaled=function(t,i,n,r){for(var o=0;16>o;o++)r.m[o]=t[o+i]*n},t.FromValuesToRef=function(t,i,n,r,o,s,e,h,a,u,m,y,c,p,f,l,x){x.m[0]=t,x.m[1]=i,x.m[2]=n,x.m[3]=r,x.m[4]=o,x.m[5]=s,x.m[6]=e,x.m[7]=h,x.m[8]=a,x.m[9]=u,x.m[10]=m,x.m[11]=y,x.m[12]=c,x.m[13]=p,x.m[14]=f,x.m[15]=l},t.FromValues=function(i,n,r,o,s,e,h,a,u,m,y,c,p,f,l,x){var z=new t;return z.m[0]=i,z.m[1]=n,z.m[2]=r,z.m[3]=o,z.m[4]=s,z.m[5]=e,z.m[6]=h,z.m[7]=a,z.m[8]=u,z.m[9]=m,z.m[10]=y,z.m[11]=c,z.m[12]=p,z.m[13]=f,z.m[14]=l,z.m[15]=x,z},t.Compose=function(i,n,r){var o=t.FromValues(i.x,0,0,0,0,i.y,0,0,0,0,i.z,0,0,0,0,1),s=t.Identity();return n.toRotationMatrix(s),o=o.multiply(s),o.setTranslation(r),o},t.Identity=function(){return t.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},t.IdentityToRef=function(i){t.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,i)},t.Zero=function(){return t.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)},t.RotationX=function(i){var n=new t;return t.RotationXToRef(i,n),n},t.Invert=function(i){var n=new t;return i.invertToRef(n),n},t.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},t.RotationY=function(i){var n=new t;return t.RotationYToRef(i,n),n},t.RotationYToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);\ni.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},t.RotationZ=function(i){var n=new t;return t.RotationZToRef(i,n),n},t.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},t.RotationAxis=function(i,n){var r=t.Zero();return t.RotationAxisToRef(i,n,r),r},t.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},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){h.RotationYawPitchRollToRef(t,i,n,this._tempQuaternion),this._tempQuaternion.toRotationMatrix(r)},t.Scaling=function(i,n,r){var o=t.Zero();return t.ScalingToRef(i,n,r,o),o},t.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},t.Translation=function(i,n,r){var o=t.Identity();return t.TranslationToRef(i,n,r,o),o},t.TranslationToRef=function(i,n,r,o){t.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,i,n,r,1,o)},t.Lerp=function(i,n,r){var o=new s(0,0,0),e=new h,a=new s(0,0,0);i.decompose(o,e,a);var u=new s(0,0,0),m=new h,y=new s(0,0,0);n.decompose(u,m,y);var c=s.Lerp(o,u,r),p=h.Slerp(e,m,r),f=s.Lerp(a,y,r);return t.Compose(c,p,f)},t.LookAtLH=function(i,n,r){var o=t.Zero();return t.LookAtLHToRef(i,n,r,o),o},t.LookAtLHToRef=function(i,n,r,o){n.subtractToRef(i,this._zAxis),this._zAxis.normalize(),s.CrossToRef(r,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),s.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var e=-s.Dot(this._xAxis,i),h=-s.Dot(this._yAxis,i),a=-s.Dot(this._zAxis,i);return t.FromValuesToRef(this._xAxis.x,this._yAxis.x,this._zAxis.x,0,this._xAxis.y,this._yAxis.y,this._zAxis.y,0,this._xAxis.z,this._yAxis.z,this._zAxis.z,0,e,h,a,1,o)},t.OrthoLH=function(i,n,r,o){var s=t.Zero();return t.OrthoLHToRef(i,n,r,o,s),s},t.OrthoLHToRef=function(i,n,r,o,s){var e=2/i,h=2/n,a=1/(o-r),u=r/(r-o);t.FromValuesToRef(e,0,0,0,0,h,0,0,0,0,a,0,0,0,u,1,s)},t.OrthoOffCenterLH=function(i,n,r,o,s,e){var h=t.Zero();return t.OrthoOffCenterLHToRef(i,n,r,o,s,e,h),h},t.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},t.PerspectiveLH=function(i,n,r,o){var s=t.Zero();return s.m[0]=2*r/i,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},t.PerspectiveFovLH=function(i,n,r,o){var s=t.Zero();return t.PerspectiveFovLHToRef(i,n,r,o,s),s},t.PerspectiveFovLHToRef=function(t,i,n,r,o,s){void 0===s&&(s=!0);var e=1/Math.tan(.5*t);s?o.m[0]=e/i:o.m[0]=e,o.m[1]=o.m[2]=o.m[3]=0,s?o.m[5]=e:o.m[5]=e*i,o.m[4]=o.m[6]=o.m[7]=0,o.m[8]=o.m[9]=0,o.m[10]=-r/(n-r),o.m[11]=1,o.m[12]=o.m[13]=o.m[15]=0,o.m[14]=n*r/(n-r)},t.GetFinalMatrix=function(i,n,r,o,s,e){var h=i.width,a=i.height,u=i.x,m=i.y,y=t.FromValues(h/2,0,0,0,0,-a/2,0,0,0,0,e-s,0,u+h/2,a/2+m,s,1);return n.multiply(r).multiply(o).multiply(y)},t.GetAsMatrix2x2=function(t){return new Float32Array([t.m[0],t.m[1],t.m[4],t.m[5]])},t.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]])},t.Transpose=function(i){var n=new t;return n.m[0]=i.m[0],n.m[1]=i.m[4],n.m[2]=i.m[8],n.m[3]=i.m[12],n.m[4]=i.m[1],n.m[5]=i.m[5],n.m[6]=i.m[9],n.m[7]=i.m[13],n.m[8]=i.m[2],n.m[9]=i.m[6],n.m[10]=i.m[10],n.m[11]=i.m[14],n.m[12]=i.m[3],n.m[13]=i.m[7],n.m[14]=i.m[11],n.m[15]=i.m[15],n},t.Reflection=function(i){var n=new t;return t.ReflectionToRef(i,n),n},t.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},t._tempQuaternion=new h,t._xAxis=s.Zero(),t._yAxis=s.Zero(),t._zAxis=s.Zero(),t}();t.Matrix=a;var u=function(){function t(t,i,n,r){this.normal=new s(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=a.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],u=r*n.m[4]+o*n.m[5]+s*n.m[6]+e*n.m[7],m=r*n.m[8]+o*n.m[9]+s*n.m[10]+e*n.m[11],y=r*n.m[12]+o*n.m[13]+s*n.m[14]+e*n.m[15];return new t(h,u,m,y)},t.prototype.dotCoordinate=function(t){return this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z+this.d},t.prototype.copyFromPoints=function(t,i,n){var r,o=i.x-t.x,s=i.y-t.y,e=i.z-t.z,h=n.x-t.x,a=n.y-t.y,u=n.z-t.z,m=s*u-e*a,y=e*h-o*u,c=o*a-s*h,p=Math.sqrt(m*m+y*y+c*c);return r=0!==p?1/p:0,this.normal.x=m*r,this.normal.y=y*r,this.normal.z=c*r,this.d=-(this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z),this},t.prototype.isFrontFacingTo=function(t,i){var n=s.Dot(this.normal,t);return i>=n},t.prototype.signedDistanceTo=function(t){return s.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 s.Dot(n,i)+r},t}();t.Plane=u;var m=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,n){return new t(this.x*i,this.y*n,this.width*i,this.height*n)},t}();t.Viewport=m;var y=function(){function t(){}return t.GetPlanes=function(i){for(var n=[],r=0;6>r;r++)n.push(new u(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,function(t){t[t.LOCAL=0]=\"LOCAL\",t[t.WORLD=1]=\"WORLD\"}(t.Space||(t.Space={}));var c=(t.Space,function(){function t(){}return t.X=new s(1,0,0),t.Y=new s(0,1,0),t.Z=new s(0,0,1),t}());t.Axis=c;var p=function(){function t(){}return t.interpolate=function(t,i,n,r,o){for(var s=1-3*r+3*i,e=3*r-6*i,h=3*i,a=t,u=0;5>u;u++){var m=a*a,y=m*a,c=s*y+e*m+h*a,p=1/(3*s*m+2*e*a+h);a-=(c-t)*p,a=Math.min(1,Math.max(0,a))}return 3*Math.pow(1-a,2)*a*n+3*(1-a)*Math.pow(a,2)*o+Math.pow(a,3)},t}();t.BezierCurve=p,function(t){t[t.CW=0]=\"CW\",t[t.CCW=1]=\"CCW\"}(t.Orientation||(t.Orientation={}));var f=t.Orientation,l=function(){function t(t){var i=this;this.degrees=function(){return 180*i._radians/Math.PI},this.radians=function(){return i._radians},this._radians=t,this._radians<0&&(this._radians+=2*Math.PI)}return t.BetweenTwoPoints=function(i,n){var r=n.subtract(i),o=Math.atan2(r.y,r.x);return new t(o)},t.FromRadians=function(i){return new t(i)},t.FromDegrees=function(i){return new t(i*Math.PI/180)},t}();t.Angle=l;var x=function(){function t(t,i,n){this.startPoint=t,this.midPoint=i,this.endPoint=n;var r=Math.pow(i.x,2)+Math.pow(i.y,2),s=(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 o((s*(i.y-n.y)-e*(t.y-i.y))/h,((t.x-i.x)*e-(i.x-n.x)*s)/h),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=l.BetweenTwoPoints(this.centerPoint,this.startPoint);var a=this.startAngle.degrees(),u=l.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),m=l.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();u-a>180&&(u-=360),-180>u-a&&(u+=360),m-u>180&&(m-=360),-180>m-u&&(m+=360),this.orientation=0>u-a?f.CW:f.CCW,this.angle=l.FromDegrees(this.orientation===f.CW?a-m:m-a)}return t}();t.Arc2=x;var z=function(){function t(t,i){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new o(t,i))}return t.prototype.addLineTo=function(t,i){if(closed)return this;var n=new o(t,i),r=this._points[this._points.length-1];return this._points.push(n),this._length+=n.subtract(r).length(),this},t.prototype.addArcTo=function(t,i,n,r,s){if(void 0===s&&(s=36),closed)return this;var e=this._points[this._points.length-1],h=new o(t,i),a=new o(n,r),u=new x(e,h,a),m=u.angle.radians()/s;u.orientation===f.CW&&(m*=-1);for(var y=u.startAngle.radians()+m,c=0;s>c;c++){var p=Math.cos(y)*u.radius+u.centerPoint.x,l=Math.sin(y)*u.radius+u.centerPoint.y;this.addLineTo(p,l),y+=m}return this},t.prototype.close=function(){return this.closed=!0,this},t.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},t.prototype.getPoints=function(){return this._points},t.prototype.getPointAtLengthPosition=function(t){if(0>t||t>1)return o.Zero();for(var i=t*this.length(),n=0,r=0;r<this._points.length;r++){var s=(r+1)%this._points.length,e=this._points[r],h=this._points[s],a=h.subtract(e),u=a.length()+n;if(i>=n&&u>=i){var m=a.normalize(),y=i-n;return new o(e.x+m.x*y,e.y+m.y*y)}n=u}return o.Zero()},t.StartingAt=function(i,n){return new t(i,n)},t}();t.Path2=z;var w=function(){function n(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 n.prototype.getCurve=function(){return this._curve},n.prototype.getTangents=function(){return this._tangents},n.prototype.getNormals=function(){return this._normals},n.prototype.getBinormals=function(){return this._binormals},n.prototype.getDistances=function(){return this._distances},n.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},n.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]=s.Cross(n,this._normals[0]),this._raw||this._binormals[0].normalize(),this._distances[0]=0;for(var o,e,h,a,u=1;i>u;u++)o=this._getLastNonNullVector(u),i-1>u&&(e=this._getFirstNonNullVector(u),this._tangents[u]=o.add(e),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]=s.Cross(a,h),this._raw||this._normals[u].normalize(),this._binormals[u]=s.Cross(h,this._normals[u]),this._raw||this._binormals[u].normalize()},n.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},n.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},n.prototype._normalVector=function(n,r,o){var e;if(void 0===o||null===o){var h;i.WithinEpsilon(r.y,1,t.Epsilon)?i.WithinEpsilon(r.x,1,t.Epsilon)?i.WithinEpsilon(r.z,1,t.Epsilon)||(h=new s(0,0,1)):h=new s(1,0,0):h=new s(0,-1,0),e=s.Cross(r,h)}else e=s.Cross(r,o),s.CrossToRef(e,r,e);return e.normalize(),e},n}();t.Path3D=w;var v=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 e=new Array,h=function(t,i,n,r){var o=(1-t)*(1-t)*i+2*t*(1-t)*n+t*t*r;return o},a=0;o>=a;a++)e.push(new s(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(e)},t.CreateCubicBezier=function(i,n,r,o,e){e=e>3?e:4;for(var h=new Array,a=function(t,i,n,r,o){var s=(1-t)*(1-t)*(1-t)*i+3*t*(1-t)*(1-t)*n+3*t*t*(1-t)*r+t*t*t*o;return s},u=0;e>=u;u++)h.push(new s(a(u/e,i.x,n.x,r.x,o.x),a(u/e,i.y,n.y,r.y,o.y),a(u/e,i.z,n.z,r.z,o.z)));return new t(h)},t.CreateHermiteSpline=function(i,n,r,o,e){for(var h=new Array,a=1/e,u=0;e>=u;u++)h.push(s.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=v;var d=function(){function t(){this.L00=s.Zero(),this.L1_1=s.Zero(),this.L10=s.Zero(),this.L11=s.Zero(),this.L2_2=s.Zero(),this.L2_1=s.Zero(),this.L20=s.Zero(),this.L21=s.Zero(),this.L22=s.Zero()}return t.prototype.addLight=function(t,i,n){var r=new s(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=d;var g=function(){function t(){this.x=s.Zero(),this.y=s.Zero(),this.z=s.Zero(),this.xx=s.Zero(),this.yy=s.Zero(),this.zz=s.Zero(),this.xy=s.Zero(),this.yz=s.Zero(),this.zx=s.Zero()}return t.prototype.addAmbient=function(t){var i=new s(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=g;var T=function(){function t(t,i){void 0===t&&(t=s.Zero()),void 0===i&&(i=s.Up()),this.position=t,this.normal=i}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone())},t}();t.PositionNormalVertex=T;var R=function(){function t(t,i,n){void 0===t&&(t=s.Zero()),void 0===i&&(i=s.Up()),void 0===n&&(n=o.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=R;var _=function(){function t(){}return t.Color3=[n.Black(),n.Black(),n.Black()],t.Vector2=[o.Zero(),o.Zero(),o.Zero()],t.Vector3=[s.Zero(),s.Zero(),s.Zero(),s.Zero(),s.Zero(),s.Zero(),s.Zero(),s.Zero(),s.Zero()],t.Vector4=[e.Zero(),e.Zero(),e.Zero()],t.Quaternion=[new h(0,0,0,0)],t.Matrix=[a.Zero(),a.Zero(),a.Zero(),a.Zero(),a.Zero(),a.Zero(),a.Zero(),a.Zero()],t}();t.Tmp=_}(BABYLON||(BABYLON={}));";
  40939. BABYLON.Effect.IncludesShadersStore={"bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpFragment":"#ifdef BUMP\nvec2 bumpUV=vBumpUV;\n#endif\n#if defined(BUMP) || defined(PARALLAX)\nmat3 TBN=cotangent_frame(normalW*vBumpInfos.y,-viewDirectionW,bumpUV);\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nvec2 uvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,bumpUV,vBumpInfos.z);\n#else\nvec2 uvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\ndiffuseUV+=uvOffset;\nbumpUV+=uvOffset;\n\n#ifdef PARALLAXOCCLUSION\nif (diffuseUV.x>1.0 || diffuseUV.y>1.0 || diffuseUV.x<0.0 || diffuseUV.y<0.0) {\ndiscard;\n}\n#endif\n#endif\n#ifdef BUMP\nnormalW=perturbNormal(viewDirectionW,TBN,bumpUV);\n#endif","bumpFragmentFunctions":"#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform sampler2D bumpSampler;\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 binormal=dp2perp*duv1.y+dp1perp*duv2.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(binormal,binormal)));\nreturn mat3(tangent*invmax,binormal*invmax,normal);\n}\nvec3 perturbNormal(vec3 viewDir,mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*255./127.-128./127.;\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying float fFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fFogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fFogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fFogDistance*fFogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","fogVertex":"#ifdef FOG\nfFogDistance=(view*worldPos).z;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying float fFogDistance;\n#endif","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","helperFunctions":"mat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","lightFragment":"#ifdef LIGHT{X}\n#ifndef SPECULARTERM\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,vLightData{X},vLightDirection{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightGround{X},glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,glossiness);\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWVSM{X}\nshadow=computeShadowWithVSM(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\n#ifdef SHADOWPCF{X}\n#if defined(POINTLIGHT{X})\nshadow=computeShadowWithPCFCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#endif\n#else\n#if defined(POINTLIGHT{X})\nshadow=computeShadowCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#else\nshadow=computeShadow(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#endif\n#endif\n#endif\n#else\nshadow=1.;\n#endif\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SPOTLIGHT{X}) || defined(DIRLIGHT{X})\nvarying vec4 vPositionFromLight{X};\nuniform sampler2D shadowSampler{X};\n#else\nuniform samplerCube shadowSampler{X};\n#endif\nuniform vec3 shadowsInfo{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(-lightDirection.xyz,lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,-lightDirection.xyz));\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW-lightDirection.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\n","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","reflectionFunction":"vec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvec3 direction=normalize(vDirectionW);\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","shadowsFragmentFunctions":"#ifdef SHADOWS\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#if defined(POINTLIGHT0) || defined(POINTLIGHT1) || defined(POINTLIGHT2) || defined(POINTLIGHT3)\nuniform vec2 depthValues;\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float bias)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight))+bias;\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\nfloat biasedDepth=depth-bias;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\nreturn min(1.0,visibility+darkness);\n}\n#endif\n#if defined(SPOTLIGHT0) || defined(SPOTLIGHT1) || defined(SPOTLIGHT2) || defined(SPOTLIGHT3) || defined(DIRLIGHT0) || defined(DIRLIGHT1) || defined(DIRLIGHT2) || defined(DIRLIGHT3)\nfloat computeShadow(vec4 vPositionFromLight,sampler2D shadowSampler,float darkness,float bias)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadow=unpack(texture2D(shadowSampler,uv))+bias;\nif (depth.z>shadow)\n{\nreturn darkness;\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,sampler2D shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\nfloat biasedDepth=depth.z-bias;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\nreturn min(1.0,visibility+darkness);\n}\n\nfloat unpackHalf(vec2 color)\n{\nreturn color.x+(color.y/255.0);\n}\nfloat linstep(float low,float high,float v) {\nreturn clamp((v-low)/(high-low),0.0,1.0);\n}\nfloat ChebychevInequality(vec2 moments,float compare,float bias)\n{\nfloat p=smoothstep(compare-bias,compare,moments.x);\nfloat variance=max(moments.y-moments.x*moments.x,0.02);\nfloat d=compare-moments.x;\nfloat p_max=linstep(0.2,1.0,variance/(variance+d*d));\nreturn clamp(max(p,p_max),0.0,1.0);\n}\nfloat computeShadowWithVSM(vec4 vPositionFromLight,sampler2D shadowSampler,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0 || depth.z>=1.0)\n{\nreturn 1.0;\n}\nvec4 texel=texture2D(shadowSampler,uv);\nvec2 moments=vec2(unpackHalf(texel.xy),unpackHalf(texel.zw));\nreturn min(1.0,1.0-ChebychevInequality(moments,depth.z,bias)+darkness);\n}\n#endif\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\nvPositionFromLight0=lightMatrix0*worldPos;\n#endif\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\nvPositionFromLight1=lightMatrix1*worldPos;\n#endif\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\nvPositionFromLight2=lightMatrix2*worldPos;\n#endif\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\nvPositionFromLight3=lightMatrix3*worldPos;\n#endif\n#endif","shadowsVertexDeclaration":"#ifdef SHADOWS\n#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\nuniform mat4 lightMatrix0;\nvarying vec4 vPositionFromLight0;\n#endif\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\nuniform mat4 lightMatrix1;\nvarying vec4 vPositionFromLight1;\n#endif\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\nuniform mat4 lightMatrix2;\nvarying vec4 vPositionFromLight2;\n#endif\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\nuniform mat4 lightMatrix3;\nvarying vec4 vPositionFromLight3;\n#endif\n#endif"};
  40940. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  40941. module.exports = BABYLON;
  40942. };